code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def make_temp_dir(self, path, sub_dir=None, prefix=''): <NEW_LINE> <INDENT> base_path = self.resolve_path(base_dir=path, path='.', sub_dir=sub_dir) <NEW_LINE> self.make_dir(base_path) <NEW_LINE> new_path = tempfile.mkdtemp(prefix=prefix, dir=base_path) <NEW_LINE> self.validate_dir(new_path, check_exists=True) <NEW_LINE...
Creates a temp directory in the specified path :param path: The path to where the temp dir is to be created. @type path: str :param user: Username of the user that is currently logged in can be retrived by bottle.request.environ @type user: str :param prefix: The prefix to be attached to the temp dir. @type prefix:...
625941d87b180e01f3dc4a67
def saveAmpMaps(ant, npix): <NEW_LINE> <INDENT> p, a=mkALMAAperture(ant=ant, npix=npix) <NEW_LINE> pyplot.FitsWrite(a, "!"+ampMapFName(ant, npix)) <NEW_LINE> return a
Create and save the amplitude maps
625941d830dc7b7665901bd2
def execute(self, command, commit=True): <NEW_LINE> <INDENT> self.cursor.execute(command) <NEW_LINE> if commit: <NEW_LINE> <INDENT> self.cnxn.commit()
Execute any SQL command, set commit flag to False to avoid saving any commands :param command: SQL command to execute :param commit: whether to commit changes to SQL
625941d8cdde0d52a9e532a2
def parse_args(argv): <NEW_LINE> <INDENT> usage_template = '{} {} [OPTION...] -- [CURL ARGS...]'.format <NEW_LINE> parser = argparse.ArgumentParser( usage=usage_template('%(prog)s', 'COMMAND'), version='%(prog)s {}'.format(__version__), ) <NEW_LINE> common = argparse.ArgumentParser(add_help=False) <NEW_LINE> common.add...
Parse command-line arguments. Returns: argparse.Namespace
625941d8fbf16365ca6f6434
def model_fn(features, labels, mode, params): <NEW_LINE> <INDENT> del labels <NEW_LINE> assert mode == tf.estimator.ModeKeys.PREDICT, "Mode should be PREDICT." <NEW_LINE> span, _ = rc_span( question_ids=features["question_inputs"].token_ids, question_mask=features["question_inputs"].mask, context_ids=features["context_...
A model function satisfying the tf.estimator API.
625941d85fdd1c0f98dc04a1
def iter_objects(premis_el): <NEW_LINE> <INDENT> for elem in iter_elements(premis_el, 'object'): <NEW_LINE> <INDENT> yield elem
Iterate all PREMIS objects from starting element. :starting_element: Element where matching elements are searched :returns: Generator object for iterating all elements
625941d867a9b606de4a8126
def _adb_su_shell(self, *args): <NEW_LINE> <INDENT> build_version_sdk = int(self._get_property('ro.build.version.sdk')) <NEW_LINE> if build_version_sdk >= _ANDROID_M_BUILD_VERSION: <NEW_LINE> <INDENT> cmd = ['su', '0'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = ['su', '-c'] <NEW_LINE> <DEDENT> cmd.extend(args)...
Runs command as root.
625941d8baa26c4b54cb138b
def decode(self, gene) -> int: <NEW_LINE> <INDENT> distance = 0 <NEW_LINE> for i in range(len(gene)): <NEW_LINE> <INDENT> if i == (len(gene) - 1): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> distance = distance + self.distance_matrix[gene[i]][gene[i + 1]] <NEW_LINE> <DEDENT> return distance
解码, 基因 -> 表现型, 飞行的距离 :param gene: 基因序列 list/numpy array :return: 表现型
625941d8bd1bec0571d9089d
def sanitizeName(name): <NEW_LINE> <INDENT> return ''.join(c if c.isalnum() else '_' for c in name)
Replace all non-alphanumeric characters in name to alpha-numeric characters
625941d832920d7e50b28440
def genkey(keyfile): <NEW_LINE> <INDENT> if not keyfile: <NEW_LINE> <INDENT> crypto.generate_keys(config.key_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> crypto.generate_keys(os.path.join(config.key_path, keyfile))
generates key files
625941d829b78933be1e5916
def rekey(self): <NEW_LINE> <INDENT> self.allowed = None <NEW_LINE> self.privee = nacling.Privateer() <NEW_LINE> self.publee = nacling.Publican()
Regenerate short term keys
625941d8dd821e528d63b416
def read_s3_file(bucket_name, file_key, role_arn=None): <NEW_LINE> <INDENT> if not bucket_name or not file_key: <NEW_LINE> <INDENT> raise Exception('Bucket name or file key is empty while trying to read file', bucket_name, file_key) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> logger.info('Reading file %s in bucket %s'...
reads data from file_key within bucket_name :param bucket_name: encapsulating s3 bucket :param file_key: key of the file to read content from :param role_arn: Role under which to run the S3 commands :return:
625941d8bd1bec0571d9089e
def miso_identification(input_generator, output_wgn, branches): <NEW_LINE> <INDENT> if hasattr(input_generator,"GetOutput"): <NEW_LINE> <INDENT> input_wgn = input_generator.GetOutput() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_wgn = input_generator <NEW_LINE> <DEDENT> l = [] <NEW_LINE> L = [] <NEW_LINE> signa...
MISO approach of system identification. :param input_generator: the input generator or the input signal :param output_wgn: the response of the nonlinear system :param branches: the number of branches :return: the filter kernels and the nonlinear function of a HGM
625941d82eb69b55b151cb1f
def __init__(self, box): <NEW_LINE> <INDENT> ConstructionFunctor.__init__(self, Objects(), Objects()) <NEW_LINE> if not callable(box): <NEW_LINE> <INDENT> raise TypeError("input must be callable") <NEW_LINE> <DEDENT> self.box = box
TESTS:: sage: from sage.categories.pushout import BlackBoxConstructionFunctor sage: FG = BlackBoxConstructionFunctor(gap) sage: FM = BlackBoxConstructionFunctor(maxima) sage: FM == FG False sage: FM == loads(dumps(FM)) True
625941d87047854f462a1675
@cache('step') <NEW_LINE> def shimen_wpp_storage_pool(): <NEW_LINE> <INDENT> return integ_shimen_wpp_storage_pool()
Real Name: ShiMen WPP Storage Pool Original Eqn: INTEG ( IF THEN ELSE(ShiMen WPP+ShiMen WPP Storage Pool-ShiMen WPP Adjusted>=500000, 0 , ShiMen WPP\ -ShiMen WPP Adjusted ), 500000) Units: m3 Limits: (None, None) Type: component 500000 m^3 Max Storage Pool Volume
625941d85fc7496912cc3bec
def run( self, host: str = "localhost", port: int = 8000, workers: Union[bool, int, None] = True, ): <NEW_LINE> <INDENT> _e("Pixie-web 0.1") <NEW_LINE> if workers is not None: <NEW_LINE> <INDENT> if workers is True: <NEW_LINE> <INDENT> self.use_process_pool() <NEW_LINE> <DEDENT> elif workers is False: <NEW_LINE> <INDEN...
Run pixie_web on the stated hostname and port.
625941d801c39578d7e750aa
def q03_ohe_encoder(): <NEW_LINE> <INDENT> pass
write your solution here
625941d8a934411ee3751902
def start_request(port: str, ip: str = '127.0.0.1'): <NEW_LINE> <INDENT> context = zmq.Context() <NEW_LINE> socket = context.socket(zmq.REQ) <NEW_LINE> socket.connect('tcp://{}:{}'.format(ip, port)) <NEW_LINE> request = tfcshandler.generate_request('register', { 'last_update': None, 'tags': None, 'publics': None }, 'co...
Делает запрос на основной сервер с целью получения основных данных для начала действия бота. :param port: порт основного сервера :param ip: ip основного сервера :return: объекты для настройки начальных свойств бота
625941d899fddb7c1c9de5ff
def __init__( self, *, markdown: builtins.str, height: typing.Optional[jsii.Number] = None, width: typing.Optional[jsii.Number] = None, ) -> None: <NEW_LINE> <INDENT> self._values: typing.Dict[str, typing.Any] = { "markdown": markdown, } <NEW_LINE> if height is not None: <NEW_LINE> <INDENT> self._values["height"] = hei...
Properties for a Text widget. :param markdown: The text to display, in MarkDown format. :param height: Height of the widget. Default: 2 :param width: Width of the widget, in a grid of 24 units wide. Default: 6
625941d8bf627c535bc1343d
def save_file(bytes_file, filename): <NEW_LINE> <INDENT> with open(filename, 'wb+') as f: <NEW_LINE> <INDENT> f.write(bytes_file.getbuffer())
Save the file
625941d8283ffb24f3c55b6d
def seleccionar(self): <NEW_LINE> <INDENT> self.seleccionado = True <NEW_LINE> self.imagen.limpiar() <NEW_LINE> self.imagen.pintar_imagen(self.imagen_selector_seleccionado) <NEW_LINE> self.pintar_texto() <NEW_LINE> self.centro = ("centro", "centro")
Tilda el selector.
625941d81f037a2d8b94646c
def to_yaml(self): <NEW_LINE> <INDENT> collection_dict = self.to_dict() <NEW_LINE> del collection_dict['id'] <NEW_LINE> return utils.yaml_from_dict(collection_dict)
Convert the Collection domain object into YAML. Returns: str. The YAML representation of this Collection.
625941d8dc8b845886cb57a4
def show_problem_score(score_data: list, problemid: str): <NEW_LINE> <INDENT> for data in score_data: <NEW_LINE> <INDENT> data['new_score'] = data['score'] * 100 <NEW_LINE> <DEDENT> new_score_data = [] <NEW_LINE> for data in score_data: <NEW_LINE> <INDENT> for new_data in new_score_data: <NEW_LINE> <INDENT> if new_data...
统计每题得分的分布情况 横轴为得分,纵轴为人数(个) :param score_data: [{'student_id':str, 'question_id':str, 'score':float}] :param problemid: 题号 :return:figure
625941d8b5575c28eb68e270
def upload_content(self, handle): <NEW_LINE> <INDENT> response = client.post( self.path('upload_content'), files={'content': handle}, **self._server_config.get_client_kwargs() ) <NEW_LINE> response.raise_for_status() <NEW_LINE> response_json = response.json() <NEW_LINE> if response_json['status'] != 'success': <NEW_LIN...
Upload a file to the current repository. :param handle: A file object, such as the one returned by ``open('path', 'rb')``. :returns: The JSON-decoded response. :raises nailgun.entities.APIResponseError: If the response has a status other than "success".
625941d8091ae356686671c9
def add_graph_from_data(self, graph_id, node_list, edge_list, attrs=None): <NEW_LINE> <INDENT> self.add_empty_graph(graph_id, attrs) <NEW_LINE> g = self.get_graph(graph_id) <NEW_LINE> if node_list is not None: <NEW_LINE> <INDENT> g.add_nodes_from(node_list) <NEW_LINE> <DEDENT> if edge_list is not None: <NEW_LINE> <INDE...
Add a new graph to the hierarchy from the input node/edge lists. Parameters ---------- graph_id : hashable Id of a new node in the hierarchy node_list : iterable List of nodes (with attributes) edge_list : iterable List of edges (with attributes) graph_attrs : dict, optional Dictionary containing attri...
625941d88e71fb1e9831da17
def _match_value_type(self, other: TimeValueConstructTypes) -> TimeValueRepTypes: <NEW_LINE> <INDENT> other_tv = TimeValue(other, rate=self._rate) <NEW_LINE> if isinstance(self._value, Timestamp): <NEW_LINE> <INDENT> return other_tv.as_timestamp() <NEW_LINE> <DEDENT> elif isinstance(self._value, TimeOffset): <NEW_LINE>...
Converts the other value type to self's value type. A rate conversion is done if `other` is a TimeValue and the rate differs from self._rate. :param other: A TimeValue, TimeOffset, Timestamp or int.
625941d84d74a7450ccd4432
def power_iteration(matrix_a, variables=None, initial_vector=None, iterations=100, delta=10 ** -3): <NEW_LINE> <INDENT> build = Builder(matrix_a.diagram.pool) <NEW_LINE> if variables is None: <NEW_LINE> <INDENT> raise RuntimeError("Variables computation not yet implemented.") <NEW_LINE> <DEDENT> names = [t[0] for t in ...
Computes the pagerank of a matrix. By convention, the variables in the matrix are prefixed with r_ if they are used as row variables and c_ if they are used as column variables. :param Matrix matrix_a: The square, stochastic adjacency matrix :param variables: The variables of the matrix (if None it is inferred from the...
625941d83eb6a72ae02ec750
def distributeFrequencies(self,f0s): <NEW_LINE> <INDENT> if len(f0s) != self.nres: <NEW_LINE> <INDENT> raise ValueError('Number of frequencies doesn\'t match number of resonators') <NEW_LINE> <DEDENT> for n in range(self.nres): <NEW_LINE> <INDENT> self.resonators[n].setFrequency(f0s[n])
Distributes the target resonance frequencies
625941d85f7d997b87174d08
def setTimeLag(self, i_timeLag): <NEW_LINE> <INDENT> self.m_prinCompTL.setTimeLag(i_timeLag)
Set the time-lag. :param i_timeLag: New time-lag. :type i_timeLag: int
625941d84e696a04525c96ba
def get_url(self) -> str: <NEW_LINE> <INDENT> return self._url
Get endpoint for command.
625941d89c8ee82313fbb9e4
def open_file(self, fname, length=None, offset=None, swap=None, block=None, peek=None): <NEW_LINE> <INDENT> if length is None: <NEW_LINE> <INDENT> length = self.length <NEW_LINE> <DEDENT> if offset is None: <NEW_LINE> <INDENT> offset = self.offset <NEW_LINE> <DEDENT> if swap is None: <NEW_LINE> <INDENT> swap = self.swa...
Opens the specified file with all pertinent configuration settings.
625941d83346ee7daa2b2fdb
def forward(self, x1, x1_lens, x2, x2_lens): <NEW_LINE> <INDENT> embed1 = self.embed(x1) <NEW_LINE> embed2 = self.embed(x2) <NEW_LINE> new_embed1 = self.bilstm1(self.dropout(embed1), x1_lens) <NEW_LINE> new_embed2 = self.bilstm1(self.dropout(embed2), x2_lens) <NEW_LINE> x1_align, x2_align = self.soft_align_attention(ne...
:param x1: (batch, seq1_len) :param x1_lens: (batch,) :param x2: (batch, seq2_len) :param x2_lens: (batch,) :return: (batch, num_class)
625941d89f2886367277aafa
def chmod(self, target, mode, timeout_seconds=300, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError("The fileutils module {} " "does not implement chmod.".format(self.__module__))
Change file permissions Parameters ---------- target : `str` The URL of the file whose permissions are to be changed. mode : `int` Same format as `os.chmod`. timeout_seconds : `int` Maximum allowed amount of time for the operation. Returns ------- `None` if operation succeede...
625941d8e5267d203edcdf09
def __init__(self, gun): <NEW_LINE> <INDENT> self.gun = gun
(Weapon)->void Constructor
625941d87c178a314d6ef6d1
def test_delete_share(self): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def do_delete(client): <NEW_LINE> <INDENT> yield client.dummy_authenticate("open sesame") <NEW_LINE> root = yield client.get_root() <NEW_LINE> res = yield client.create_share(root, self.usr1.username, u"name", Share.VIEW) <NEW_LINE> shar...
Test deletion of an offered by me share.
625941d82ae34c7f2600d39f
def debug(self, *args, **kwargs): <NEW_LINE> <INDENT> return _runtime_swig.logger_debug(self, *args, **kwargs)
debug(logger self, std::string msg)
625941d8187af65679ca538d
def undelete(self): <NEW_LINE> <INDENT> if not self.deleted: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> data = Extension.extract_manifest_fields(self.manifest, ('version',)) <NEW_LINE> self.update(deleted=False, **data) <NEW_LINE> return True
Undelete this instance, making it available to all manager methods again and restoring its version number. Return False if it was not marked as deleted, True otherwise. May raise IntegrityError if another instance has been uploaded with the same version number in the meantime.
625941d80a50d4780f667102
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(_struct_h.pack(self.num_groups)) <NEW_LINE> length = len(self.groups) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> for val1 in self.groups: <NEW_LINE> <INDENT> _x = val1 <NEW_LINE> buff.write(_struct_3h.pack(_x.group_number, ...
serialize message into buffer :param buff: buffer, ``StringIO``
625941d8a8370b7717052b0d
def diff_stat(repository_path=None, commit='HEAD^', path=None): <NEW_LINE> <INDENT> if not repository_path: <NEW_LINE> <INDENT> repository_path = debian.pwd() <NEW_LINE> <DEDENT> with cd(repository_path), silent(): <NEW_LINE> <INDENT> output = run('git diff --shortstat {} -- {}'.format(commit, path), pty=False) <NEW_LI...
Get diff stats for path. :param repository_path: Repository path :param commit: Commit to diff against, ex 12345..67890 :param path: Path or file to diff :return tuple: int(files changed), int(insertions), int(deletions)
625941d8a8ecb033257d333b
def default_lda(**kw): <NEW_LINE> <INDENT> args = {**lda_defaults, **kw} <NEW_LINE> return LatentDirichletAllocation(**args)
Return lda initialized with defaults (overridden by params).
625941d8d8ef3951e32437ac
def get_param_error(self, param_id): <NEW_LINE> <INDENT> param_index = self.param_id_to_index(param_id) <NEW_LINE> return self.errors[param_index]
Returns error of parameter specified by `param_id`. Parameters ---------- param_id : int or str Name or index in list of names of wanted paramater Returns ------- float
625941d83617ad0b5ed68165
def get_empty_space(self, material=None): <NEW_LINE> <INDENT> for x, y, tile in self.tile_layer.all(): <NEW_LINE> <INDENT> if tile.is_public(obj=material) and self[y][x] is None: <NEW_LINE> <INDENT> yield x, y
空いているスペースを全てyieldで返す。 そのオブジェクトを受け入れるタイルであり、 まだオブジェクトがない座標ならばOK。
625941d896565a6dacc8f939
def __init__(self, list_path, img_size=416, augment=True, multiscale=True, normalized_labels=True): <NEW_LINE> <INDENT> with open(list_path, "r") as file: <NEW_LINE> <INDENT> self.img_files = file.readlines() <NEW_LINE> <DEDENT> self.label_files = [ path.replace("images", "labels").replace(".png", ".txt").replace(".jpg...
list_path:数据集的路径,这个文件是一个 txt 文件,里面每一行是一个图片的路径
625941d8e64d504609d74aaf
def generate_statmech(self): <NEW_LINE> <INDENT> logging.debug("Generating statmech for species {}".format(self.label)) <NEW_LINE> from rmgpy.data.rmg import get_db <NEW_LINE> try: <NEW_LINE> <INDENT> statmech_db = get_db('statmech') <NEW_LINE> if not statmech_db: raise Exception <NEW_LINE> <DEDENT> except Exception: <...
Generate molecular degree of freedom data for the species. You must have already provided a thermodynamics model using e.g. :meth:`generate_thermo_data()`.
625941d87b25080760e396c7
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model('sites', 'Site') <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'example.com', 'name': 'news-reader-backend' } )
Set site domain and name.
625941d863f4b57ef0001382
def expr(x): <NEW_LINE> <INDENT> if isinstance(x, str): <NEW_LINE> <INDENT> return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x
Shortcut to create an Expression. x is a str in which: - identifiers are automatically defined as Symbols. - ==> is treated as an infix |'==>'| as are <== and <=> If x is already an Expression, it is returned unchanged. Example: >>> expr('P & Q ==> Q') ((P & Q) ==> Q)
625941d81f5feb6acb0c4dbb
def testParcelProtectionPolicyResponseShipmentDetails(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
Test ParcelProtectionPolicyResponseShipmentDetails
625941d8cc40096d61595bbf
def get_jobs(self, jobstore=None, pending=None): <NEW_LINE> <INDENT> with self._jobstores_lock: <NEW_LINE> <INDENT> jobs = [] <NEW_LINE> if pending is not False: <NEW_LINE> <INDENT> for job, alias, replace_existing in self._pending_jobs: <NEW_LINE> <INDENT> if jobstore is None or alias == jobstore: <NEW_LINE> <INDENT> ...
Returns a list of pending jobs (if the scheduler hasn't been started yet) and scheduled jobs, either from a specific job store or from all of them. :param str|unicode jobstore: alias of the job store :param bool pending: ``False`` to leave out pending jobs (jobs that are waiting for the scheduler start to be added...
625941d856ac1b37e626443b
def process_response(self, statement): <NEW_LINE> <INDENT> init() <NEW_LINE> try: <NEW_LINE> <INDENT> print(Fore.GREEN + statement.text) <NEW_LINE> print(Style.RESET_ALL) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print(statement.text) <NEW_LINE> <DEDENT> return statement.text
Print the response to the user's input.
625941d88da39b475bd651e4
def match_list(a, b): <NEW_LINE> <INDENT> return np.array([ b.index(x) if x in b else -1 for x in a ])
find the indices of matching element :param a: list a b: list b :return: The indices of elements in list a in list b
625941d88e7ae83300e4b23c
def _wal_report(self): <NEW_LINE> <INDENT> pass
Report obsolete/valid WALs according to the retention policy
625941d8d486a94d0b98e3b5
def zadej_pismeno(): <NEW_LINE> <INDENT> vstup = input('Zadej pismeno: ').lower() <NEW_LINE> if len(vstup) == 0 or len(vstup) > 1: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> return vstup
funkce vraci vstup uzivatele - znak.
625941d8e76e3b2f99f3aa77
def events_renamer(event): <NEW_LINE> <INDENT> event = event.lower() <NEW_LINE> event = event.replace(' , ', '_').replace('-', ('_')) <NEW_LINE> return event
Standadrize values in the events column in the weather data
625941d810dbd63aa1bd2e11
def enter_scope_after(fn: NodeVisitorFunction) -> Callable: <NEW_LINE> <INDENT> def wrapper(chk, node): <NEW_LINE> <INDENT> ret = fn(chk, node) <NEW_LINE> chk._enter_scope(node) <NEW_LINE> return ret <NEW_LINE> <DEDENT> return wrapper
Enter scope after. Signal to the syntax checker that a scope is entered AFTER visiting this node. :param fn: Node visitor function :return: Decorated function
625941d8d7e4931a7ee9e18d
def output(data, show_links=False, show_headers=False, output_json=False): <NEW_LINE> <INDENT> if isinstance(data, types.GeneratorType) and not output_json: <NEW_LINE> <INDENT> resources_count = 0 <NEW_LINE> for d in data: <NEW_LINE> <INDENT> _output(d, show_links=show_links, show_headers=show_headers, output_json=outp...
Main output function used for printing to stdout. It will invoke helper output function using generator or list and output total number of Resources if needed.
625941d8dc8b845886cb57a5
def calculate_overtime(self, attendance, salary_per_day): <NEW_LINE> <INDENT> rate = self.overtime <NEW_LINE> ln = self.normal_overtime * attendance.ln <NEW_LINE> lp = attendance.lp * Decimal(salary_per_day) <NEW_LINE> lk = attendance.lk * Decimal(salary_per_day) <NEW_LINE> l1 = attendance.l1 * rate * Decimal(1.50) <NE...
Get calculated overtime. Calculating overtime based on employee attendance, this method get called in calculate_total() Parameters ---------- attendance : ``Attendance`` object salary_per_day : decimal Return ---------- decimal Total salary on all type of overtime
625941d8cb5e8a47e48b7d16
def parse(testcode, withSystemMacros=True, withGlobalIncludeWrappers=False): <NEW_LINE> <INDENT> state = cparser.State() <NEW_LINE> if withSystemMacros: <NEW_LINE> <INDENT> state.autoSetupSystemMacros() <NEW_LINE> <DEDENT> if withGlobalIncludeWrappers: <NEW_LINE> <INDENT> state.autoSetupGlobalIncludeWrappers() <NEW_LIN...
:param str testcode: :param bool withSystemMacros: :param bool withGlobalIncludeWrappers: :rtype: cparser.State
625941d81d351010ab855d8a
def transpose(x, axes=None): <NEW_LINE> <INDENT> return T.transpose(x, axes=axes)
Transpose x according to the order of axes.
625941d850485f2cf553d00a
@login_required <NEW_LINE> def get_challenges(request): <NEW_LINE> <INDENT> challenges = Challenge.objects.filter(min_level__lte=request.user.spierdonuser.level, max_level__gte=request.user.spierdonuser.level, blocked=False) <NEW_LINE> user_challenges = [i.challenge for i in UserActiveChallenge.objects.filter(user__exa...
Get five random challenges available for current user (ie. those which are assigned to current user's level and not already completed). :param request: HttpRequest object :return: HttpResponse object with drawn challenges
625941d823e79379d52ee7d0
def clean(self): <NEW_LINE> <INDENT> data = FormHelper.stripSpacesFromFields( self.cleaned_data, self.fields) <NEW_LINE> self.cleaned_data = data <NEW_LINE> return super(LocationKeyEditForm, self).clean()
Strip spaces from the fields.
625941d830bbd722463cc037
def update_cached_counts(self, deltas, negate=False): <NEW_LINE> <INDENT> if negate: <NEW_LINE> <INDENT> deltas = deltas.copy() <NEW_LINE> for k, v in deltas.items(): <NEW_LINE> <INDENT> deltas[k] = -v <NEW_LINE> <DEDENT> <DEDENT> if deltas.get('brands', 0): <NEW_LINE> <INDENT> self.brand_count = F('brand_count') + del...
Updates the database fields that cache child object counts. Expects a deltas object in the form returned by stat_counts() methods, and also expected by CountStats.update_all_counts().
625941d8091ae356686671ca
def get_children(self, max_level=1, current_level=1, date=None): <NEW_LINE> <INDENT> if max_level != -1 and current_level > max_level: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if not date: <NEW_LINE> <INDENT> links = self.parentchildlink_parent.filter(end_time__exact=None) <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
Returns a list of all children at time *date*. :rtype: list of :class:`Child`
625941d8cad5886f8bd27248
def service_handle(hass: HomeAssistantType): <NEW_LINE> <INDENT> async def async_service_command(call): <NEW_LINE> <INDENT> entity_ids = call.data[ATTR_ENTITY_ID] <NEW_LINE> command = call.data[ATTR_COMMAND] <NEW_LINE> for device in hass.data[PS4_DATA].devices: <NEW_LINE> <INDENT> if device.entity_id in entity_ids: <NE...
Handle for services.
625941d80fa83653e4657229
def mkdir_idempotent(curpath, uid=None, gid=None): <NEW_LINE> <INDENT> if not os.path.exists(curpath): <NEW_LINE> <INDENT> os.mkdir(curpath, MODE_755) <NEW_LINE> <DEDENT> elif not os.path.isdir(curpath): <NEW_LINE> <INDENT> raise RuntimeError('%s: Not a directory' % curpath) <NEW_LINE> <DEDENT> if uid is None: <NEW_LIN...
Idempotent mkdir with 0755 permissions
625941d86e29344779a62880
def test_rollbackErrorLogged(self): <NEW_LINE> <INDENT> class ConnectionRollbackRaise(object): <NEW_LINE> <INDENT> def rollback(self): <NEW_LINE> <INDENT> raise RuntimeError("problem!") <NEW_LINE> <DEDENT> <DEDENT> pool = FakePool(ConnectionRollbackRaise) <NEW_LINE> connection = Connection(pool) <NEW_LINE> self.assertR...
If an error happens during rollback, L{ConnectionLost} is raised but the original error is logged.
625941d88a43f66fc4b542d2
def GET(self): <NEW_LINE> <INDENT> import inspect <NEW_LINE> clients = [name for name, _ in inspect.getmembers(saltapi.APIClient, predicate=inspect.ismethod) if not name.startswith('__')] <NEW_LINE> clients.remove('run') <NEW_LINE> formats = [ctype for ctype, _ in ct_out_map] <NEW_LINE> return { 'return': "Welcome", 'c...
.. http:get:: / An explanation of the API with links of where to go next. **Example request**:: % curl -i localhost:8000 .. code-block:: http GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response**: .. code-block:: http HTTP/1...
625941d832920d7e50b28441
def _connect(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if sys.version_info[:2] >= (2,6): <NEW_LINE> <INDENT> self._conn = telnetlib.Telnet(self._host, self._port, connTimeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._conn = telnetlib.Telnet(self._host, self._port) <NEW_LINE> <DEDENT> <DEDENT> excep...
Connect to Memcached.
625941d8956e5f7376d710db
def dev_extra_summaries(self, stacked_model_outs, stacked_loss_outs, is_training, dev_stats_scope, phase_set_dev, these_s): <NEW_LINE> <INDENT> with tf.name_scope(None): <NEW_LINE> <INDENT> for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES): <NEW_LINE> <INDENT> if 'weights' in w.name: <NEW_LINE> <INDENT> var_...
Add user-defined per-device summaries
625941d826238365f5f0f0e0
def valid_direction(self,pos,dir): <NEW_LINE> <INDENT> if dir != WEST and pos.x+1 < self.maze_width and self.maze[pos.x+1][pos.y] == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if dir != EAST and pos.x-1 >= 0 and self.maze[pos.x-1][pos.y] == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if dir != ...
for each direction: if ( COND_1 && COND_2 && COND_3 ): return False # direction/spot is invalid # COND_1 -> ensure we're not checking the spot we came from # COND_2 -> ensure we're not checking out of bounds (it's okay for us to be on the edge) # COND_3 -> check if the ...
625941d8ff9c53063f47c462
def getStatus(self): <NEW_LINE> <INDENT> return self.status
Sends the current status of the gripper (estimated from the commands sent to the gripper, since there is no feedback as of yet).
625941d810dbd63aa1bd2e12
def reset(self): <NEW_LINE> <INDENT> return _atsc_swig.atsc_fpll_sptr_reset(self)
reset(atsc_fpll_sptr self)
625941d821a7993f00bc7f62
def multilinearInterpolation(self,points,values,point): <NEW_LINE> <INDENT> point=np.asarray(point) <NEW_LINE> points=np.asarray(points) <NEW_LINE> values=np.asarray(values) <NEW_LINE> sizeOfCube=np.amax(points, axis=0) - np.amin(points, axis=0) <NEW_LINE> sizeMask=sizeOfCube!=0 <NEW_LINE> sizeOfCube=sizeOfCube[sizeMas...
Do multilinear Interpolation
625941d8435de62698dfdebd
def add_frame(self, frame, pts): <NEW_LINE> <INDENT> if frame is None: <NEW_LINE> <INDENT> self._frame_queue.put('eof', block=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._frame_queue.put((frame, pts), block=False)
Adds a frame to be written to disk. :Parameters: `frame`: A :class:`ffpyplayer.pic.Image` instance. The image to be written. `pts`: float The time stamp of the image. A frame of None is passed internally when the device is to be deactivated.
625941d85fdd1c0f98dc04a3
def do_path_regex_sub(self, pathexp, regexp, subst): <NEW_LINE> <INDENT> if not hasattr(pathexp, "match"): <NEW_LINE> <INDENT> pathexp = re.compile(pathexp) <NEW_LINE> <DEDENT> match = pathexp.match <NEW_LINE> file_list = [f for f in self.copied_files if match(f['srcpath'])] <NEW_LINE> for file in file_list: <NEW_LINE>...
Apply a regexp substituation to a set of files archived by sos. The set of files to be substituted is generated by matching collected file pathnames against `pathexp`. :param pathexp: A regex to match filenames within the archive :type pathexp: ``str`` or compiled ``re`` object :param regexp: A regex to match against...
625941d867a9b606de4a8128
def test_onchange_default_template(self): <NEW_LINE> <INDENT> form = Form(self.env["product.template"]) <NEW_LINE> form.name = "Prod A" <NEW_LINE> form.default_code = "PROD-A" <NEW_LINE> self.assertFalse(form.barcode) <NEW_LINE> record = form.save() <NEW_LINE> self.assertFalse(record.barcode)
Nothing changes since the constraint is not enabled.
625941d8de87d2750b860004
def do_show(self, line): <NEW_LINE> <INDENT> args = shlex.split(line) <NEW_LINE> if not len(args): <NEW_LINE> <INDENT> return print('Please specify a valid network ID') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> network = self.network_list.get(int(args[0])) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> r...
Display detailed information about a specified network Syntax: show <id>
625941d8baa26c4b54cb138d
def addFrequencyIndicator(self, ax): <NEW_LINE> <INDENT> width = 0.01 <NEW_LINE> height = 0.03 <NEW_LINE> if not hasattr(self, 'hvsr_frequency'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ax.hvsr_frequency_indicator.remove() <NEW_LINE> del ax.hvsr_frequency_indicator <NEW_LINE> <DEDENT> ex...
Adds an indicator to fig at self.hvsr_frequency. Does not redraw the figure.
625941d8bd1bec0571d9089f
def __init__(self): <NEW_LINE> <INDENT> pass
Create an abstract syntax tree node
625941d80383005118ecf851
def get(self): <NEW_LINE> <INDENT> session['user'] = None <NEW_LINE> session['token'] = None <NEW_LINE> return {'status': 'ok'}
用户退出 :return:
625941d80383005118ecf852
def fit(self, X, y=None, **params): <NEW_LINE> <INDENT> sampled_params = ParameterSampler(self.param_distributions, self.n_iter) <NEW_LINE> return self._fit(X, y, sampled_params, **params)
Run fit on the estimator with randomly drawn parameters. Parameters ---------- X: array-like, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. y: array-like, shape = [n_samples], optional Target vector relative to X for cl...
625941d856ac1b37e626443c
def test_special_exams(self): <NEW_LINE> <INDENT> self.transformers = BlockStructureTransformers([self.TRANSFORMER_CLASS_TO_TEST(True)]) <NEW_LINE> self.course.enable_subsection_gating = True <NEW_LINE> self.setup_gated_section(self.blocks['H'], self.blocks['A']) <NEW_LINE> expected_blocks = ( 'course', 'A', 'B', 'C', ...
When the block structure transformers are set to allow users to view special exams, ensure that we can see the special exams and not any of the otherwise gated blocks.
625941d81b99ca400220ad22
def _build_dynamic_sub_element(self, definition, sub_elements): <NEW_LINE> <INDENT> logger.debug('\tBuilding dynamic sub-element [%s] with elements [%s]', definition.name, sub_elements) <NEW_LINE> result = definition.klass( *sub_elements, **definition.keywords ) <NEW_LINE> return result
Returns the fully composed ViewSubElement from the sub-element contributions to the dynamic sub-element identified by the definition.
625941d8293b9510aa2c3504
def init(self, nameGetter, parentGetter, inputs): <NEW_LINE> <INDENT> remainders = [] <NEW_LINE> allNames = [ nameGetter(x) for x in inputs ] <NEW_LINE> allParents = [] <NEW_LINE> [ allParents.extend(parentGetter(x)) for x in inputs ] <NEW_LINE> externalParents = set(allParents).difference(set(allNames)) <NEW_LINE> for...
Really do the init here
625941d815baa723493c41e7
def test_hypervisor_stats_v2_88(self): <NEW_LINE> <INDENT> ex = self.assertRaises( exceptions.CommandError, self.run_command, 'hypervisor-stats', api_version='2.88') <NEW_LINE> self.assertIn( 'The hypervisor-stats command is not supported in API version ' '2.88 or later.', str(ex))
Tests nova hypervisor-stats at the 2.88 microversion.
625941d8d4950a0f3b08c5bc
def get_available_port(preferred_port: Optional[int] = None) -> int: <NEW_LINE> <INDENT> def is_available(port: int) -> bool: <NEW_LINE> <INDENT> with socket.socket() as sock: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sock.bind(("localhost", port)) <NEW_LINE> return True <NEW_LINE> <DEDENT> except OSError: <NEW_LINE...
Finds an available port for use in webviz on localhost. If a reload process, it will reuse the same port as found in the parent process by using an inherited environment variable. If preferred_port is given, ports in the range [preferred_port, preferred_port + 20) will be tried first, before an OS provided random port...
625941d829b78933be1e5918
def rank_sc(req, page, context): <NEW_LINE> <INDENT> page = int(page) <NEW_LINE> (users, list_info) = paging(User.objects.order_by('-ac', 'submit'), PAGE_RANK_NUM, page) <NEW_LINE> if users == None: <NEW_LINE> <INDENT> return error('4o4', 'far behind, you ', context, 'error.html') <NEW_LINE> <DEDENT> k = 1 <NEW_LINE> f...
the rank of the user
625941d8bd1bec0571d908a0
def _is_child(self, parent: Key, child: Key) -> bool: <NEW_LINE> <INDENT> parent_parts = tuple(parent) <NEW_LINE> child_parts = tuple(child) <NEW_LINE> if parent_parts == child_parts: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return parent_parts == child_parts[: len(parent_parts)]
Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another.
625941d899fddb7c1c9de600
def __discover_node(self, node, depth): <NEW_LINE> <INDENT> if (node == None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if (depth >= self.max_depth): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if (node.discovered > 0): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> node.discovered = 1 <NEW_LINE> if (node.ip[0...
Given a node, recursively enumerate its adjacencies until we reach the specified depth (>0). Args: node: natlas_node object to enumerate. depth: The depth left that we can go further away from the root.
625941d83617ad0b5ed68166
def __init__(self, states, parameters, rules, sum_state="N"): <NEW_LINE> <INDENT> self.states = states <NEW_LINE> self.n_states = len(states) <NEW_LINE> self.parameters = parameters <NEW_LINE> self.rules = rules <NEW_LINE> self.sum_state = sum_state
Args: states (list of str): Names of the states. parameters (dict of str to float): Mapping from parameters to their values. rules (list of tuples): Tuples of the form (origin, destination, f), those being: - origin: Index of the origin state. ...
625941d8a4f1c619b28b02a5
def update(self, loss_info): <NEW_LINE> <INDENT> super(OGD, self).update(loss_info) <NEW_LINE> gradient = loss_info['gradient'] <NEW_LINE> self.parameter -= self.eta * gradient <NEW_LINE> return
updates parameters
625941d87047854f462a1677
def __truediv__(self, another): <NEW_LINE> <INDENT> if isinstance(another, Expression): <NEW_LINE> <INDENT> return Expression(Div,self,another) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Expression(Div, self, Constant(another))
Implement dunder method for division
625941d830c21e258bdfa70e
def close(self): <NEW_LINE> <INDENT> self._proc.sendeof()
Terminate the underlying interpreter
625941d8596a897236089d2e
def forward_backward(evidence_vector, prior, states, evidence_variables, transition_probs, emission_probs): <NEW_LINE> <INDENT> prodf = lambda x, y: x * y <NEW_LINE> alpha = [dict(prior)] <NEW_LINE> for o in evidence_vector: <NEW_LINE> <INDENT> new_a = {} <NEW_LINE> for s in states: <NEW_LINE> <INDENT> new_a[s] = sum([...
This method takes as input the following: evidence_vector: A list of dictionaries mapping evidence variables to their values at each time step prior: A dictionary corresponding to the prior distribution over states states: A list of all possible system states evidence_variables: A list of all valid evidence variables t...
625941d80c0af96317bb8458
def timestamp_to_format(timestamp=None, format = '%Y-%m'): <NEW_LINE> <INDENT> if timestamp: <NEW_LINE> <INDENT> time_tuple = localtime(timestamp) <NEW_LINE> res = strftime(format, time_tuple) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = strftime(format) <NEW_LINE> <DEDENT> return res
时间戳转年月
625941d81f037a2d8b94646e
def fatorial(n, show=False): <NEW_LINE> <INDENT> f = 1 <NEW_LINE> for c in range(n, 0, -1): <NEW_LINE> <INDENT> if show: <NEW_LINE> <INDENT> print(c, end='') <NEW_LINE> if c > 1: <NEW_LINE> <INDENT> print(' x ', end='') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(' = ', end='') <NEW_LINE> <DEDENT> <DEDENT> f *=...
-> Calcula o Fatorial de um número. :param n: O número a ser calculado. :param show: (opcional) Mostrar ou não a conta :return: O valor do Fatorial de um número n.
625941d891f36d47f21ac764
def string_to_texture(s): <NEW_LINE> <INDENT> font = pg.font.Font("font"+str(random.randint(0, 4))+".ttf", 150).render(s, True, (255, 255, 255, 255)) <NEW_LINE> sx, sy = font.get_width(), font.get_height() <NEW_LINE> data = pg.image.tostring(font, "RGBA", True) <NEW_LINE> text = glGenTextures(1) <NEW_LINE> glBindTextur...
Create a texture of the string that can be displayed on a quad. :param s: string to be displayed. :returns: texture object and aspect ratio.
625941d83539df3088e2e5bb
def classify(self, title_text:str) -> str: <NEW_LINE> <INDENT> num_classes = len(self.mapping) <NEW_LINE> classification = random.randint(0, num_classes - 1) <NEW_LINE> return self.mapping[classification]
Classify randomly This classifier returns a random label string
625941d807f4c71912b116f4
def yieldroutes(func): <NEW_LINE> <INDENT> path = func.__name__.replace('__','/').lstrip('/') <NEW_LINE> spec = inspect.getargspec(func) <NEW_LINE> argc = len(spec[0]) - len(spec[3] or []) <NEW_LINE> path += ('/:%s' * argc) % tuple(spec[0][:argc]) <NEW_LINE> yield path <NEW_LINE> for arg in spec[0][argc:]: <NEW_LINE> <...
Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/:x/:y' c(x, y=5) -> '/c/:x' and '/c/:x/:y' ...
625941d82eb69b55b151cb22
def test_was_published_recently_with_recent_poll(self): <NEW_LINE> <INDENT> recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1)) <NEW_LINE> self.assertEqual(recent_poll.was_published_recently(), True)
was_published_recently should return true for polls whose pub_date is within the last day
625941d8cc40096d61595bc0
def MultipartFormdataEncoder(image, name): <NEW_LINE> <INDENT> boundary = uuid.uuid4().hex <NEW_LINE> content_type = 'multipart/form-data; boundary={}'.format(boundary) <NEW_LINE> item_list = [] <NEW_LINE> if image_host == 'fastpic': <NEW_LINE> <INDENT> templist1 = ('jpeg_quality', 'uploading', 'check_thumb', 'thumb_te...
Функция кодирования изображения для отправки multipart/form-data. Вход : ссылку на изображение и имя для Content-Disposition Выход : Content-Type и байтовый объект (или что-то такое xD)
625941d8566aa707497f47d6