code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_board_by_board_id(board_id): <NEW_LINE> <INDENT> return Board.get_by_id(board_id) | :param int board_id:
:return:
:rtype: Board or None | 625941d7442bda511e8be662 |
def test_init(self): <NEW_LINE> <INDENT> test_deck = Deck() <NEW_LINE> self.assertEqual(test_deck.length(), 52) | Test that deck is successfully created. | 625941d7aad79263cf390c90 |
def ReadUrlContent(url): <NEW_LINE> <INDENT> conn = urllib.urlopen(url) <NEW_LINE> try: <NEW_LINE> <INDENT> return conn.readlines() <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> logging.exception('Error connecting to %s. Error: %s', url, e) <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT... | Connect to a remote host and read the contents. Returns a list of lines. | 625941d7ff9c53063f47c43f |
def test_search_back_multi_multi_line(): <NEW_LINE> <INDENT> f = tutils.tflowview(request_contents="this is string\nthis is string\nthis is string") <NEW_LINE> f.search("string") <NEW_LINE> f.search_again() <NEW_LINE> f.search_again() <NEW_LINE> f.search_again(backwards=True) <NEW_LINE> text_object = tutils.get_body_li... | same as above for some bugs the above won't catch. | 625941d7a8370b7717052aeb |
def _plus_values_2013_(self, f3vg, f3vh, f3vl, f3vm, f3vi_holder, f3vf_holder, f3vd_holder, f3sa, _P, rpns_pvce_holder, plus_values = law.ir.plus_values): <NEW_LINE> <INDENT> rpns_pvce = self.sum_by_entity(rpns_pvce_holder) <NEW_LINE> f3vd = self.filter_role(f3vd_holder, role = VOUS) <NEW_LINE> f3sd = self.filter_role(... | Taxation des plus value
TODO: f3vt, 2013 f3Vg au barème / tout refaire | 625941d7bde94217f368303b |
def __get_json_or_raise(self, r): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return r.json() <NEW_LINE> <DEDENT> except ValueError as v: <NEW_LINE> <INDENT> raise ValueError("Invalid text found in response: %s" % self.format_response(r)) | Verify that the Response object has a valid json response.
:param r: requests.Response
:raises ValueError if the response doesn't have a valid json object | 625941d756ac1b37e6264419 |
def test_has_rupee(self): <NEW_LINE> <INDENT> self.has_character(self, u'₹') | Does this font include a glyph for ₹, the Indian Rupee Sign
codepoint? | 625941d7ab23a570cc2503d0 |
def startsWith(self, prefix: str) -> bool: <NEW_LINE> <INDENT> current = self.child <NEW_LINE> for l in prefix: <NEW_LINE> <INDENT> if l not in current: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> current = current[l] <NEW_LINE> <DEDENT> return True | Returns if there is any word in the trie that starts with the given prefix. | 625941d74e4d5625662d4622 |
def set_replacements(self, replacements): <NEW_LINE> <INDENT> for replacement in replacements: <NEW_LINE> <INDENT> if self.parser.has_section(replacement): <NEW_LINE> <INDENT> self.parser.set(replacement, replacement, replacements[replacement]) | See :meth:`dput.config.AbstractConfig.set_replacements` | 625941d7d53ae8145f87a4b9 |
def _abort(self): <NEW_LINE> <INDENT> self._logger.info("Aborting brute-force evaluation.") <NEW_LINE> self._combinations = [] | Aborts evaluation by clearing the remaining hyperparameter combinations left to evaluate.
:return: None. | 625941d771ff763f4b5498db |
def suspend(self, content): <NEW_LINE> <INDENT> pass | Appending this content has suspended.
@param content: The content for which proccessing has been suspended.
@type content: L{Content} | 625941d763b5f9789fde7332 |
def obtain_exports_list(pe=None, file_data=None) -> List[bytes]: <NEW_LINE> <INDENT> if file_data: <NEW_LINE> <INDENT> pe = obtain_pe(file_data) <NEW_LINE> <DEDENT> if pe: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [export.name for export in pe.DIRECTORY_ENTRY_EXPORT.symbols] <NEW_LINE> <DEDENT> except Attribu... | Obtain a list of export names for the input PE file.
:param pe: pefile.PE object
:param file_data: Input file data
:return: A list of export names, or None. | 625941d766673b3332b922de |
def clean_financeiro(self): <NEW_LINE> <INDENT> if self.financeiro == None: <NEW_LINE> <INDENT> self.financeiro = self.preco * self.quantidade | Preenche o campo financeiro, se ele já não estiver preenchido. Deve
haver um valor de cota e quantidade de cotas para que seja possível
calculá-lo. | 625941d776e4537e8c3518c0 |
def get_handler(self, handler_name): <NEW_LINE> <INDENT> for handler in self.handlers: <NEW_LINE> <INDENT> if handler.name == handler_name: <NEW_LINE> <INDENT> return handler <NEW_LINE> <DEDENT> <DEDENT> return None | Obtain handler by name.
Parameters
----------
handler_name : str or unicode
The name of the handler.
Returns
-------
PDS4StreamHandler or PDS4SilentHandler
Handler for this logger, matching the *handler_name*. | 625941d7b57a9660fec33ad3 |
def getThing(self,thing,start_val = 0): <NEW_LINE> <INDENT> val = self.content_string <NEW_LINE> start = val.find(thing,start_val) <NEW_LINE> if start == -1: <NEW_LINE> <INDENT> print("nothing found. ") <NEW_LINE> return start <NEW_LINE> <DEDENT> start -= 1 <NEW_LINE> while val[start] != '\n': <NEW_LINE> <INDENT> start... | convenience method for getting xml tags. | 625941d70a366e3fb873ea68 |
def save_crops(self, workspace): <NEW_LINE> <INDENT> objects_name = self.objects_name.value <NEW_LINE> objects = workspace.object_set.get_objects(objects_name) <NEW_LINE> bit_depth = self.bit_depth.value <NEW_LINE> if self.input_type == IF_IMAGE: <NEW_LINE> <INDENT> image_name = self.image_name.value <NEW_LINE> image =... | Crops the image by objects | 625941d70a50d4780f6670e0 |
def EliminateOverlaps(instRef, rigidParts, myAsm, myModel): <NEW_LINE> <INDENT> logger = logging.getLogger() <NEW_LINE> count = 0 <NEW_LINE> noOverlap = True <NEW_LINE> logger.info("**********************************************************************************\n") <NEW_LINE> logger.info("Checking for overlapping (b... | Attempt to resolve oerlapping components by merging offending instances. Only applies to buy parts. | 625941d715fb5d323cde0d5f |
def pkhbt(self, cond: Condition, rn: Reg, rd: Reg) -> None: <NEW_LINE> <INDENT> struct.pack_into("<I", self.buf, self.pos, (((109051920 | cond) | (rn << 16)) | (rd << 12))) <NEW_LINE> self.pos += 4 | Emits a 'pkhbt' instruction. | 625941d7de87d2750b85ffe1 |
def fsymbol(self, atom): <NEW_LINE> <INDENT> return self.full_atoms[atom].symbol() | Returns the cleaned up label of the atom (C2 => C, H4 = H) (includes dummies) (0-indexed)
>>> print(H2OH2O.fsymbol(4))
O | 625941d7167d2b6e31218de2 |
def prepare_tree(self): <NEW_LINE> <INDENT> self.tree.root.branch_length = 0.001 <NEW_LINE> self.tree.root.mutation_length = self.tree.root.branch_length <NEW_LINE> self.tree.root.mutations = [] <NEW_LINE> self.tree.ladderize() <NEW_LINE> self._prepare_nodes() <NEW_LINE> self._leaves_lookup = {node.name:node for node i... | Set link to parent and calculate distance to root for all tree nodes.
Should be run once the tree is read and after every rerooting,
topology change or branch length optimizations. | 625941d750485f2cf553cfe7 |
def write_stationsfile(self,STATIONS,EventName): <NEW_LINE> <INDENT> fname = path.join(self.path,self.name + '_{}.stn'.format(EventName)) <NEW_LINE> STATIONS.to_csv(fname,index=False) | Writing the stations file | 625941d7d99f1b3c44c677d8 |
def do_abrir(self, arg): <NEW_LINE> <INDENT> pass | - comando abrir que leva como parâmetro o nome de um ficheiro..: abrir <nome_ficheiro> | 625941d738b623060ff0b03a |
def findItinerary(self, tickets): <NEW_LINE> <INDENT> self.graph = collections.defaultdict(list) <NEW_LINE> for src, dst in sorted(tickets)[::-1]: <NEW_LINE> <INDENT> self.graph[src].append(dst) <NEW_LINE> <DEDENT> route, stack = [], ["JFK"] <NEW_LINE> while stack: <NEW_LINE> <INDENT> while self.graph[stack[-1]]: <NEW_... | :type tickets: List[List[str]]
:rtype: List[str] | 625941d796565a6dacc8f918 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApiResponseListUserHourlyRate): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941d792d797404e3043d8 |
def test_init_argfail_fixed(self): <NEW_LINE> <INDENT> for data in DATA_TYPES: <NEW_LINE> <INDENT> if data[0] == 'bool': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.assertRaises(RelaxBoolError, self.diffusion_tensor_fns.init, params=1e-9, fixed=data[1]) | The fixed arg test of the diffusion_tensor.init() user function. | 625941d7925a0f43d254a0c5 |
def _set_state(self, v, load=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass(v,base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp-policy', defining_mo... | Setter method for state, mapped from YANG variable /routing_policy/policy_definitions/policy_definition/statements/statement/actions/bgp_actions/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this v... | 625941d71d351010ab855d68 |
def checkout_subtotal( *, checkout: "Checkout", lines: Iterable["CheckoutLine"], discounts: Optional[Iterable[DiscountInfo]] = None, ) -> "TaxedMoney": <NEW_LINE> <INDENT> calculated_checkout_subtotal = get_plugins_manager().calculate_checkout_subtotal( checkout, lines, discounts or [] ) <NEW_LINE> return quantize_pric... | Return the total cost of all the checkout lines, taxes included.
It takes in account all plugins. | 625941d77d847024c06be50b |
def repr(Z1, Z2=None): <NEW_LINE> <INDENT> if Z2 is None: <NEW_LINE> <INDENT> return _repr(Z1) <NEW_LINE> <DEDENT> R1, R2 = _repr(Z1), _repr(Z2) <NEW_LINE> R = "" <NEW_LINE> for c1,c2 in zip(R1,R2): <NEW_LINE> <INDENT> c = c1 <NEW_LINE> if c1 == '●': <NEW_LINE> <INDENT> if c2 == '●': <NEW_LINE> <INDENT> c = '⦿' <NEW_LI... | ∙ : inactive
● : active
○ : precicted
⦿ : active and predicted | 625941d76e29344779a6285e |
def add_integer(a, b=98): <NEW_LINE> <INDENT> if type(a) is int or type(a) is float: <NEW_LINE> <INDENT> if type(b) is int or type(b) is float: <NEW_LINE> <INDENT> return int(a) + int(b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('b must be an integer') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <... | Python function to sum two integers and check if a/b is int & float | 625941d79b70327d1c4e1023 |
def _calcExpectations(u1, u0): <NEW_LINE> <INDENT> E = dict() <NEW_LINE> E['v'] = u1 / (u1 + u0) <NEW_LINE> E['1-v'] = u0 / (u1 + u0) <NEW_LINE> assert not np.any(np.isnan(E['v'])) <NEW_LINE> E['beta'] = v2beta(E['v']) <NEW_LINE> digammaBoth = digamma(u1 + u0) <NEW_LINE> E['logv'] = digamma(u1) - digammaBoth <NEW_LINE>... | Calculate expectations of v and beta(v)
under the model v[k] ~ Beta(U1[k], U0[k]) | 625941d710dbd63aa1bd2def |
def store(self, **kwargs): <NEW_LINE> <INDENT> for k,v in kwargs.items(): <NEW_LINE> <INDENT> if not(k in self.epoch_dict.keys()): <NEW_LINE> <INDENT> self.epoch_dict[k] = [] <NEW_LINE> <DEDENT> if isinstance(v, list): <NEW_LINE> <INDENT> self.epoch_dict[k] += v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.epoch_... | Save something into the epoch_logger's current state.
Provide an arbitrary number of keyword arguments with numerical
values. | 625941d7dc8b845886cb5783 |
def roc(prices, period=21): <NEW_LINE> <INDENT> num_prices = len(prices) <NEW_LINE> if num_prices < period: <NEW_LINE> <INDENT> raise SystemExit('Error: num_prices < period') <NEW_LINE> <DEDENT> roc_range = num_prices - period <NEW_LINE> rocs = np.zeros(roc_range) <NEW_LINE> for idx in range(roc_range): <NEW_LINE> <IND... | The Rate-of-Change (ROC) indicator, a.k.a. Momentum, is a pure momentum
oscillator that measures the percent change in price from one period to the
next.
The plot forms an oscillator that fluctuates above and below the zero line
as the Rate-of-Change moves from positive to negative.
ROC signals include centerline cross... | 625941d794891a1f4081bcf7 |
def object_data_point(self, name: str, description: str = "", unit: str = '', handler: Optional[Callable[[Dict,float,Any], Any]] = None, interval: float = 0, writable=True, subtype: str='', **kwargs): <NEW_LINE> <INDENT> self.datapoints[name] = None <NEW_LINE> def onChangeAttempt(v: Optional[str], t, a): <NEW_LINE> <IN... | Register a new object data point with the given properties. Here "object"
means a JSON-like object.
Handler will be called when it changes.
self.datapoints[name] will start out with tha value of None
Interval annotates the default data rate the point will produce, for use in setting default poll
rates by the host, ... | 625941d7090684286d50ef34 |
def __getitem__(self, aslice): <NEW_LINE> <INDENT> if isinstance(aslice, (int, slice)): <NEW_LINE> <INDENT> ret = self._list[aslice] <NEW_LINE> <DEDENT> elif isinstance(aslice, str): <NEW_LINE> <INDENT> ret = self._getitem_string(aslice) <NEW_LINE> <DEDENT> elif isinstance(aslice, tuple): <NEW_LINE> <INDENT> if len(asl... | Support slicing the UnifiedResponse as a 2D object.
The first index is to the client and the second index is the records
returned from those clients. | 625941d766673b3332b922df |
def setPolicy(self, JSONDataPolicy): <NEW_LINE> <INDENT> self.__policy = copy.deepcopy(JSONDataPolicy) <NEW_LINE> if len(self.__policy): <NEW_LINE> <INDENT> for i in self.__policy.keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(i) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> continue <NEW_LINE> <D... | when the script start, if the JSON has policy. add to policyTAB
but would not parse in/outbound's policy | 625941d78da39b475bd651c3 |
def __init__(self, url=None, username=None, password=None, ask=True, old_olog_api=None): <NEW_LINE> <INDENT> self._url = _conf.get_value('url', url) <NEW_LINE> self.verify = False <NEW_LINE> username = _conf.get_username(username) <NEW_LINE> password = _conf.get_value('password', password) <NEW_LINE> self._old_olog_api... | Initialize OlogClient and configure session
:param url: The base URL of the Olog glassfish server.
:param username: The username for authentication.
:param password: The password for authentication.
:param old_olog_api: Use the old olog api.
If :param username: is None, then the username will be read
from the config fi... | 625941d7711fe17d825425b6 |
def subscribe(self, uuid, callback=None, indication=False): <NEW_LINE> <INDENT> self.logger.info( 'Subscribing to uuid=%s with callback=%s and indication=%s', uuid, callback, indication) <NEW_LINE> definition_handle = self.get_handle(uuid) <NEW_LINE> value_handle = definition_handle + 1 <NEW_LINE> characteristic_config... | Enables subscription to a Characteristic with ability to call callback.
:param uuid:
:param callback:
:param indication:
:return:
:rtype: | 625941d7462c4b4f79d1d91d |
def array_to_raster(array, lons, lats): <NEW_LINE> <INDENT> dst_filename = '/a_file/name.tiff' <NEW_LINE> x_pixels = 16 <NEW_LINE> y_pixels = 16 <NEW_LINE> PIXEL_SIZE = 3 <NEW_LINE> x_min = 553648 <NEW_LINE> y_max = 7784555 <NEW_LINE> wkt_projection = 'a projection in wkt that you got from other file' <NEW_LINE> driver... | Array > Raster
Save a raster from a C order array.
:param array: ndarray | 625941d7cb5e8a47e48b7cf5 |
def _add_filters(self,old_filter,extra_filter): <NEW_LINE> <INDENT> filter_keys = extra_filter.keys() <NEW_LINE> new_filter = old_filter <NEW_LINE> for key in filter_keys: <NEW_LINE> <INDENT> for condition in extra_filter[key]: <NEW_LINE> <INDENT> new_filter = new_filter + " AND '{}' {} '{}'".format(key,condition["op"]... | Método interno para formatar o filtro
Parameters
----------
old_filter : str
string contendo o filtro anteriormente ultilizado
extra_filter : dict
Dicionario de array de dicioanrios, contendo a variavel a ser filtrada. O arrya sao os conjuntos de condiçoes aplicados aquela variavel
Returns
-------
d... | 625941d7ac7a0e7691ed4316 |
def run_raw_session(self, handler_ctx, session=None, command=None, timeout=300, prompt_regex=None, client_ip="", client_port="", uuid=""): <NEW_LINE> <INDENT> pass | Parameters:
- session
- command
- timeout
- prompt_regex
- client_ip
- client_port
- uuid | 625941d73539df3088e2e598 |
def wrapText2(text, size=defaultsize): <NEW_LINE> <INDENT> text = text.replace('\n', ' ') <NEW_LINE> lines = wrapLinesSmart([text], size) <NEW_LINE> return lines | same, but treat as one long line | 625941d730dc7b7665901bb2 |
def turn_on(self, **kwargs) -> None: <NEW_LINE> <INDENT> self._is_enabled = True <NEW_LINE> raise NotImplementedError() | Enable the entity controller. | 625941d73c8af77a43ae39ef |
def test_step(s1, s2, score): <NEW_LINE> <INDENT> feed_dict = { cnn.input_s1: s1, cnn.input_s2: s2, cnn.input_y: score, cnn.dropout_keep_prob: 1.0 } <NEW_LINE> loss, pearson = sess.run( [cnn.real_loss, cnn.pearson], feed_dict) <NEW_LINE> time_str = datetime.datetime.now().isoformat() <NEW_LINE> print("{}: loss {:g}, pe... | Evaluates model on a dev set | 625941d75fc7496912cc3bcb |
def find_datestr(htmltext): <NEW_LINE> <INDENT> datestr_el = htmltext.find('div', class_='c-blog-article__date') <NEW_LINE> datestr = datestr_el.text.strip() <NEW_LINE> articledate = datetime.strptime(datestr, '%Y.%m.%d %H:%M') <NEW_LINE> filenamestr = articledate.strftime('%Y%m%d%H%M%S') <NEW_LINE> return filenamestr | 記事情報から日付の部分を抽出する関数 | 625941d7bd1bec0571d9087d |
def test_pipeline_persistence(self): <NEW_LINE> <INDENT> temp_path = tempfile.mkdtemp() <NEW_LINE> try: <NEW_LINE> <INDENT> df = self.spark.createDataFrame([(["a", "b", "c"],), (["c", "d", "e"],)], ["words"]) <NEW_LINE> tf = HashingTF(numFeatures=10, inputCol="words", outputCol="features") <NEW_LINE> pca = PCA(k=2, inp... | Pipeline[HashingTF, PCA] | 625941d729b78933be1e58f6 |
def enquire(sc, dest=None): <NEW_LINE> <INDENT> codes = read_code_file() <NEW_LINE> if not dest: <NEW_LINE> <INDENT> info = get_info(sc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info = get_info(sc, destination=codes[dest]) <NEW_LINE> <DEDENT> if not info: <NEW_LINE> <INDENT> print("No services.") <NEW_LINE> <DEDEN... | Query the API for train information
Arguments:
sc {str} -- Three letter station code for source station
Keyword Arguments:
dest {str} -- Three letter station code for destination (Optional) | 625941d756b00c62f0f148a8 |
def df_strip(df): <NEW_LINE> <INDENT> df_copy = df.copy() <NEW_LINE> for var in df_copy.columns: <NEW_LINE> <INDENT> if df_copy[var].dtype == np.object: <NEW_LINE> <INDENT> df_copy[var] = pd.core.strings.str_strip(df_copy[var]) <NEW_LINE> df_copy = df_copy.rename(columns={var: var.strip()}) <NEW_LINE> <DEDENT> <DEDENT>... | Strips extra spaces from input | 625941d7adb09d7d5db6c9dc |
def find_volume(year, title, part): <NEW_LINE> <INDENT> vol_num = 1 <NEW_LINE> volume = Volume(year, title, vol_num) <NEW_LINE> while volume.exists: <NEW_LINE> <INDENT> if volume.should_contain(part): <NEW_LINE> <INDENT> return volume <NEW_LINE> <DEDENT> vol_num += 1 <NEW_LINE> volume = Volume(year, title, vol_num) <NE... | Annual editions have multiple volume numbers. Try to find the volume
that we care about | 625941d797e22403b379d1e8 |
def is_visible(self, request_or_user): <NEW_LINE> <INDENT> user = getattr(request_or_user, 'user', request_or_user) <NEW_LINE> return self.private is False or user in self.users.all() or user in self.applications.all() | Renvoyer si le groupe est accessible à un utilisateur | 625941d7cdde0d52a9e53282 |
def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.asDictionary) | returns the class as a string (JSON) | 625941d7a934411ee37518e1 |
def admin_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): <NEW_LINE> <INDENT> actual_decorator = user_passes_test( lambda u: u.is_active and (u.user_type == 'admin' or u.is_superuser), login_url=login_url, redirect_field_name=redirect_field_name ) <NEW_LINE> if function: <NEW_LINE>... | Decorator for views that checks that the logged in user is a admin,
redirects to the log-in page if necessary. | 625941d7851cf427c661a75b |
def testActorProductRole(self): <NEW_LINE> <INDENT> model = kinow_client.models.actor_product_role.ActorProductRole() | Test ActorProductRole | 625941d7be383301e01b56d1 |
def __init__(self, config, name, quit_check_callback=None): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.crash_store = config.crashstorage_class(config) | 'name' is unused by this class but is present for api consistency | 625941d75fc7496912cc3bcc |
def kindex(self, kpoint): <NEW_LINE> <INDENT> if duck.is_intlike(kpoint): <NEW_LINE> <INDENT> return int(kpoint) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.kpoints.index(kpoint) | Index of the k-point in the internal tables.
Accepts: :class:`Kpoint` instance or integer. | 625941d745492302aab5e513 |
def store_location(self, location: LocationValue) -> bool: <NEW_LINE> <INDENT> if not self.verify_location(location=location): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> with self.__locations_lock: <NEW_LINE> <INDENT> source_address = location.source_address <NEW_LINE> mapped_address = location.mapped_address... | When received 'HI' command, update the location in it
:param location: location info with time
:return: False on error | 625941d7d6c5a1020814429a |
def initialize_particles(**kwargs): <NEW_LINE> <INDENT> klass = kwargs.get('type', Particle) <NEW_LINE> number = kwargs.get('number', world_parameters.get('team_size')) <NEW_LINE> center = kwargs.get('center', (750,750)) <NEW_LINE> radius = kwargs.get('radius', 100) <NEW_LINE> team = kwargs.get('team', 'ally') <NEW_... | Initialize N particles in a circular distribution around a center
point, where N=number. Keyword arguments include a radius from the
center, an identifier pattern and other keyword arguments that would
instantiate a particle. | 625941d7566aa707497f47b4 |
def write_worker_to_file( worker:Worker.Worker ): <NEW_LINE> <INDENT> name = fill_spaces(worker.name) <NEW_LINE> if exists(name): <NEW_LINE> <INDENT> with open(name + ".pkl", "wb") as file: <NEW_LINE> <INDENT> pickle.dump(worker, file, pickle.HIGHEST_PROTOCOL) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with... | Write a Worker Object to a file with a Name.txt | 625941d77b25080760e396a6 |
def ibmwaston_nlu(repo_description): <NEW_LINE> <INDENT> usernm = '1a5fba40-ab91-4b36-92a0-f957b6abeb0f' <NEW_LINE> passwd = 'jut4J5KJaoXe' <NEW_LINE> natural_language_understanding = NaturalLanguageUnderstandingV1(username= usernm, password= passwd, version='2018-03-16') <NEW_LINE> text = repo_description.encode('utf-... | use IBM waston-NLU to process texutal input | 625941d77d847024c06be50c |
def makeObservables( event, sample): <NEW_LINE> <INDENT> event.deltaPhi_bb = deltaPhi( event.bj0['phi'], event.bj1['phi'] ) <NEW_LINE> event.deltaR_bb = deltaR( event.bj0, event.bj1 ) <NEW_LINE> event.nonZ_deltaPhi_ll = deltaPhi( event.l0['phi'], event.l1['phi'] ) <NEW_LINE> event.nonZ_deltaR_ll = deltaR( event.l0, eve... | Compute all relevant observables
| 625941d797e22403b379d1e9 |
def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1): <NEW_LINE> <INDENT> np.random.seed(1) <NEW_LINE> self.pre_process_data(reviews, labels) <NEW_LINE> self.init_network(len(self.review_vocab),hidden_nodes, 1, learning_rate) | Create a SentimenNetwork with the following
Args:
reviews(list) - List of reviews used for training
labels(list) - List of POSITIVE/NEGATIVE labels associated with the given reviews
hidden_nodes(int) - Number of nodes to create in the hidden layer
learning_rate(float) - Learning rate to use while traini... | 625941d755399d3f05588903 |
def test_get_event_list_auth_null(self): <NEW_LINE> <INDENT> r = requests.get(self.base_url,params={'eid':1}) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.result['status'],10011) <NEW_LINE> self.assertEqual(self.result['message'],'user auth null') | auth为空 | 625941d763d6d428bbe4473d |
def deny_user(type,username): <NEW_LINE> <INDENT> if type == 'shop': <NEW_LINE> <INDENT> with open(SHOP_LOCK,'a') as f: <NEW_LINE> <INDENT> print('\033[31;1m抱歉,用户[ %s ]密码错误次数太多,已被程序锁定,请联系管理员解锁,谢谢!'%username) <NEW_LINE> f.write(username+'\n') <NEW_LINE> log.logger_shop.info('%s密码错误次数太多,被锁定'%username) <NEW_LINE> return T... | 锁定用户函数,接受用户传入两个形参
:param type: type值为shop表示锁定的是商城的用户,atm是其他地方的
:param username: 接受用户传入形参用户名
:return: 成功为True,否则为False | 625941d7507cdc57c6306f2d |
def save_user(self): <NEW_LINE> <INDENT> User.users_list.append(self) | function saves new vault users to user_list. | 625941d731939e2706e4d0b5 |
def augment_object(self, reference_object, force_success=True): <NEW_LINE> <INDENT> ref_object_id = reference_object.metadata["object_id"] <NEW_LINE> random_str = "".join(np.random.choice(list(string.ascii_letters), 10)) <NEW_LINE> new_object_id = "%s_aug_%s" % (ref_object_id, random_str) <NEW_LINE> while True: <NEW_LI... | Generate an augmented version of an object.
Parameters
==========
reference_object : :class:`AstronomicalObject`
The object to use as a reference for the augmentation.
force_success : bool
If True, then if we fail to generate an augmented light curve for a
specific set of augmented parameters, we choose a ... | 625941d73617ad0b5ed68144 |
def is_venv(): <NEW_LINE> <INDENT> return hasattr(sys, "real_prefix") or ( hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix ) | Check to see if we are currently in a virtual environment
Returns:
[type] -- [description] | 625941d791f36d47f21ac742 |
@cached_feature("peak_around") <NEW_LINE> def create_peak_around_feature(df, peak_around): <NEW_LINE> <INDENT> print("create peak_around feature") <NEW_LINE> peak = peak_around.set_index("spectrum_filename") <NEW_LINE> feat = pd.DataFrame(index=peak.index) <NEW_LINE> feat["peak_around_max"] = peak.max(axis=1) <NEW_LINE... | ピークまわりの基本統計量を取る | 625941d750812a4eaa59c56e |
def load(self, model_path): <NEW_LINE> <INDENT> if isinstance(model_path, str): <NEW_LINE> <INDENT> if os.path.isdir(model_path): <NEW_LINE> <INDENT> print('Loading Ludwig nlg model...') <NEW_LINE> self.model = LudwigModel.load(model_path) <NEW_LINE> print('done!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Fi... | Loads the Ludwig model from the given path.
:param model_path: path to the model
:return: | 625941d7fbf16365ca6f6414 |
def new_param_func(self): <NEW_LINE> <INDENT> self.pk = self.get_pk() <NEW_LINE> self.line_search() <NEW_LINE> self.xk_new = self.xk + self.alpha * self.pk <NEW_LINE> self.fk_new, self.f_count = self.func(*(self.xk_new,)+self.args), self.f_count + 1 <NEW_LINE> self.dfk_new, self.g_count = self.dfunc(*(self.xk_new,)+sel... | The new parameter function.
Find the search direction, do a line search, and get xk+1 and fk+1. | 625941d7e76e3b2f99f3aa56 |
def __init__(self, id: int, first_name: str, last_name: str) -> None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.first_name = first_name <NEW_LINE> self.last_name = last_name | Create the object. | 625941d7a8ecb033257d331a |
def update_metadata_element(resource_short_id, element_model_name, element_id, **kwargs): <NEW_LINE> <INDENT> res = utils.get_resource_by_shortkey(resource_short_id) <NEW_LINE> res.metadata.update_element(element_model_name, element_id, **kwargs) | Updates the data associated with a metadata element for a specified resource
:param resource_short_id: id of the resource for which a metadata element needs to be updated
:param element_model_name: metadata element name (e.g., creator)
:param element_id: id of the metadata element to be updated
:param kwargs: metadata... | 625941d74d74a7450ccd4411 |
def test_qtconf_correctness(): <NEW_LINE> <INDENT> config = six.configparser.configparser() <NEW_LINE> config.read(qtconf_path) <NEW_LINE> prefix_dir = config.get("Paths", "prefix") <NEW_LINE> try: <NEW_LINE> <INDENT> binaries_dir = config.get("Paths", "binaries") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> binarie... | Is the qt.conf correctly configured? | 625941d7ec188e330fd5a9ea |
def test_previous_setter(self): <NEW_LINE> <INDENT> self.nodeone.setPrevious(Node('c')) <NEW_LINE> self.assertEqual(self.nodeone.getPrevious().getData(), 'c') <NEW_LINE> self.assertEqual(self.nodeone.getPrevious().data, 'c') | Tests Node previous Setter | 625941d77b180e01f3dc4a48 |
def serve(self): <NEW_LINE> <INDENT> timeout = 5 <NEW_LINE> Server.serve(self, 5) | enter the select loop... and wait for service requests | 625941d7cc40096d61595b9e |
def GetSshkeyMap(self, since=None): <NEW_LINE> <INDENT> return SshkeyUpdateGetter().GetUpdates(self, self.conf['sshkey_url'], since) | Return the sshkey map from this source.
Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.
Returns:
instance of sshkey.SshkeyMap | 625941d7f548e778e58cd7cd |
def publish_crash(self, crash_report): <NEW_LINE> <INDENT> raise NotImplementedError | Save the crash report. | 625941d74f88993c3716c2b4 |
def test_invalid_ruc_does_not_end_001(self): <NEW_LINE> <INDENT> self.invalid(tipo_identificacion="ruc", identificacion="1756760292002") | An invalid RUC that does not end in 001 | 625941d723849d37ff7b32dc |
def _check_inputs(self) -> None: <NEW_LINE> <INDENT> if not isinstance(self._method, str) or self._method.lower() not in ( "aic", "bic", "hqic", ): <NEW_LINE> <INDENT> raise ValueError('method must be one of "aic", "bic", or "hqic"') <NEW_LINE> <DEDENT> max_lag = self._max_lag <NEW_LINE> self._max_lag = int(max_lag) if... | Validate the inputs | 625941d757b8e32f524836ea |
def update_Title_Center(self, s, redraw=False): <NEW_LINE> <INDENT> self.title_c_str = s <NEW_LINE> if redraw: <NEW_LINE> <INDENT> self.redraw() | Update the text in the center of the title bar
redraw is a bool specifying whether to redraw window.
A window redraw can also be set with update. | 625941d71f5feb6acb0c4d9b |
def test_is_numeric_true(self): <NEW_LINE> <INDENT> self.assertTrue(self.md_table._is_numeric('1')) <NEW_LINE> self.assertTrue(self.md_table._is_numeric('1.0')) <NEW_LINE> self.assertTrue(self.md_table._is_numeric('-1.0')) <NEW_LINE> self.assertTrue(self.md_table._is_numeric('-1e-12')) | Test checking cell values that are numeric. | 625941d74f6381625f114c8a |
def _update_states_table_with_foreign_key_options(connection, engine): <NEW_LINE> <INDENT> inspector = sqlalchemy.inspect(engine) <NEW_LINE> alters = [] <NEW_LINE> for foreign_key in inspector.get_foreign_keys(TABLE_STATES): <NEW_LINE> <INDENT> if foreign_key["name"] and ( not foreign_key["options"] or foreign_key["opt... | Add the options to foreign key constraints. | 625941d756ac1b37e626441b |
def get_env(): <NEW_LINE> <INDENT> basedir = os.getcwd() <NEW_LINE> if os.path.isfile(f'{basedir}/../src/.env'): <NEW_LINE> <INDENT> load_dotenv(dotenv_path=f'{basedir}/../src/.env') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> load_dotenv(dotenv_path=f'{basedir}/src/.env') | uses dotenv to get environmental variables from .env file, where to search it (relative path),
depends on where script was started
:return: None | 625941d78e71fb1e9831d9f7 |
def flatten(self, root): <NEW_LINE> <INDENT> self.suc = None <NEW_LINE> self.helper(root) | :type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead. | 625941d79f2886367277aadb |
def add_new_block(self): <NEW_LINE> <INDENT> pass | Add a new block and return the new chain
| 625941d7be7bc26dc91cd84b |
def _should_retry(exc): <NEW_LINE> <INDENT> if not hasattr(exc, "errors"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(exc.errors) == 0: <NEW_LINE> <INDENT> return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES) <NEW_LINE> <DEDENT> reason = exc.errors[0]["reason"] <NEW_LINE> return reason in _RETRYABLE_R... | Predicate for determining when to retry.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'. | 625941d7cc40096d61595b9f |
def create_job( self, parent, job, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): <NEW_LINE> <INDENT> if "create_job" not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ "create_job" ] = google.api_core.gapic_v1.method.wrap_method( ... | Creates a new job.
Typically, the job becomes searchable within 10 seconds, but it may take
up to 5 minutes.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> parent = client.tenant_path('[PROJECT]', '[TENANT]')
>>>
>>> # TODO: ... | 625941d744b2445a339322e3 |
def matusita_distance(x,y): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> iter(x) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> logging.warning( 'Argument x is not iterable. None is returned') <NEW_LINE> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> iter(y) <NEW_LINE> <DEDENT> except TypeError: <N... | Calculates the matusita distance (euclidean distance variant) between the vectors x and y
Keyword arguments:
x,y -- the vectors between which the distance is to be calculated | 625941d74a966d76dd55125f |
def copy(self): <NEW_LINE> <INDENT> s = MemoryData(self.address, self.size, self.sort, self.irsb, self.irsb_addr, self.stmt, self.stmt_idx, pointer_addr=self.pointer_addr, max_size=self.max_size, insn_addr=self.insn_addr ) <NEW_LINE> s.refs = self.refs.copy() <NEW_LINE> return s | Make a copy of the MemoryData.
:return: A copy of the MemoryData instance.
:rtype: angr.analyses.cfg_fast.MemoryData | 625941d75166f23b2e1a53a7 |
def __init__(self, name, keyrefs, measures, bulkloader, fieldsep='\t', rowsep='\n', nullsubst=None, tempdest=None, bulksize=500000, usefilename=False, dependson=()): <NEW_LINE> <INDENT> _BaseBulkloadable.__init__(self, name, [k for k in keyrefs] + [m for m in measures], bulkloader, fieldsep, rowsep, nullsubst, tempdest... | Arguments:
- name: the name of the fact table in the DW
- keyrefs: a sequence of attribute names that constitute the
primary key of the fact tables (i.e., the dimension references)
- measures: a possibly empty sequence of measure names.
- bulkloader: A method
m(name, attributes, fieldsep, rowsep, nullsubst, tempde... | 625941d7b7558d58953c5160 |
def read_file(path, fileobj=None): <NEW_LINE> <INDENT> f = None <NEW_LINE> try: <NEW_LINE> <INDENT> if path.endswith('.gz'): <NEW_LINE> <INDENT> f = gzip.GzipFile(path, fileobj=fileobj) <NEW_LINE> <DEDENT> elif path.endswith('.bz2'): <NEW_LINE> <INDENT> if bz2 is None: <NEW_LINE> <INDENT> f = None <NEW_LINE> raise Exce... | Reads a file.
- Decompress ``.gz`` and ``.bz2`` files.
- If *fileobj* is not ``None``, stream lines from the *fileobj* | 625941d771ff763f4b5498dd |
def _training_loss(self, features, labels, logits=None, logits_input=None, name="training_loss"): <NEW_LINE> <INDENT> labels = _check_labels(labels, self._label_name) <NEW_LINE> centered_bias_step = None <NEW_LINE> if self._enable_centered_bias: <NEW_LINE> <INDENT> logits = nn.bias_add(logits, _centered_bias( self.logi... | Returns training loss tensor for this head.
Training loss is different from the loss reported on the tensorboard as we
should respect the example weights when computing the gradient.
L = sum_{i} w_{i} * l_{i} / B
where B is the number of examples in the batch, l_{i}, w_{i} are individual
losses, and example weight... | 625941d7e76e3b2f99f3aa57 |
def test_context_is_not_used_without_categories_inside(self): <NEW_LINE> <INDENT> category_list = ['c1', 'c2'] <NEW_LINE> categories = get_active_categories({'category_list': category_list}) <NEW_LINE> self.assertNotEqual(category_list, categories) <NEW_LINE> self.assertFalse(categories) | Test that template tag hits database and don't uses context if it
contains a list of objects other than Category instances | 625941d74428ac0f6e5baa42 |
def train(args, train_text_path, val_text_path): <NEW_LINE> <INDENT> checkpoint_path = os.path.join(args['checkpoint_dir'], 'checkpoint.hdf5') <NEW_LINE> model = None <NEW_LINE> if 'restore' in args and args['restore']: <NEW_LINE> <INDENT> if not os.path.exists(checkpoint_path): <NEW_LINE> <INDENT> err = 'cannot restor... | trains model using hyperparameters specified in args. | 625941d70a366e3fb873ea6a |
def flatten(df, stacked_cols=None, unstacked_indices=None): <NEW_LINE> <INDENT> if isinstance(df, pd.Series): <NEW_LINE> <INDENT> print(df.index.nlevels, df.columns.nlevels) <NEW_LINE> return df <NEW_LINE> <DEDENT> if df.index.nlevels == 1 and df.columns.nlevels == 1: <NEW_LINE> <INDENT> print(df.index.nlevels, df.colu... | Flattens a pandas.DataFrame with MultiIndex row and/or column indices to a 2D pandas.DataFrame with either
Index or RangeIndex row and column indices. If input is an instance of pandas.Series or an already flat
pandas.DataFrames, it is returned as-is.
When figuring out indices for stacked_cols and unstacked_indices, ... | 625941d723e79379d52ee7b0 |
def do__dump_ticket(self, ticket): <NEW_LINE> <INDENT> self.pp.pprint(self.tph.ticket_get(int(ticket))) | Dump the content of the ticket. Used for debugging. | 625941d763f4b57ef0001363 |
def filter_keyid_annot(src_annot, filter_ids): <NEW_LINE> <INDENT> new_list = [] <NEW_LINE> for item in src_annot: <NEW_LINE> <INDENT> if item[0] in filter_ids: <NEW_LINE> <INDENT> new_list.append(item) <NEW_LINE> <DEDENT> <DEDENT> return new_list | src_annot: a list of (keypoint_id, x, y)
filter_ids: a list of [keypoint_ids] to be remained | 625941d7236d856c2ad44a2b |
def create_inverted_tsv(label_tsv, inverted_label_file, label_map): <NEW_LINE> <INDENT> if not op.isfile(label_tsv): <NEW_LINE> <INDENT> logging.info('the label file does not exist: {}'.format(label_tsv)) <NEW_LINE> return <NEW_LINE> <DEDENT> rows = tsv_reader(label_tsv) <NEW_LINE> inverted = {} <NEW_LINE> for i, row i... | save the results based on the label_map in label_map_file. The benefit is
to seek the row given a label | 625941d7187af65679ca536e |
def get_liwc_features(words): <NEW_LINE> <INDENT> feature_vectors = {} <NEW_LINE> text = " ".join(words) <NEW_LINE> liwc_scores = word_category_counter.score_text(text) <NEW_LINE> negative_score = 0 <NEW_LINE> positive_score = 0 <NEW_LINE> negative_score += liwc_scores["Negative Emotion"] * 2 <NEW_LINE> negative_score ... | Adds a simple LIWC derived feature
:param words:
:return: | 625941d7de87d2750b85ffe3 |
def __init__(self, saved=here): <NEW_LINE> <INDENT> self.dir = saved <NEW_LINE> self.direct = utils.Directory_commands(self.dir) <NEW_LINE> self.direct.check_directory_exist("/Videos") <NEW_LINE> self.direct.check_directory_exist("/Images") <NEW_LINE> self.direct.check_directory_exist("/Images/Know_people") | Initialisation du module pygame.
Kwargs:
saved (str): Emplacement des enregistrements. | 625941d7e64d504609d74a8f |
def forward(self, x): <NEW_LINE> <INDENT> if self.h in (F.elu, F.leaky_relu): <NEW_LINE> <INDENT> u = self.u <NEW_LINE> <DEDENT> elif self.h == torch.tanh: <NEW_LINE> <INDENT> scal = torch.log(1+torch.exp(self.w @ self.u)) - self.w @ self.u - 1 <NEW_LINE> u = self.u + scal * self.w / torch.norm(self.w) <NEW_LINE> <DEDE... | Given x, returns z and the log-determinant log|df/dx|.
Returns
------- | 625941d7d99f1b3c44c677da |
def parse_next_url(self, soup): <NEW_LINE> <INDENT> next_url = soup.find(class_='p_redirect', text='>>').get('href') <NEW_LINE> self.k += 1 <NEW_LINE> return next_url | 获取下一页的URL
:param soup:页面的BeautifulSoup对象
:return:下一页的URL | 625941d738b623060ff0b03c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.