code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def confusion_matrix_0p18(y_true, y_pred, labels=None, sample_weight=None): <NEW_LINE> <INDENT> assert sample_weight is None or len(sample_weight) == len(y_true) <NEW_LINE> assert len(y_true) == len(y_pred) <NEW_LINE> if labels is None: <NEW_LINE> <INDENT> labels = unique_labels(y_true, y_pred) <NEW_LINE> <DEDENT> else...
Compute confusion matrix to evaluate the accuracy of a classification By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` is equal to the number of observations known to be in group :math:`i` but predicted to be in group :math:`j`. Thus in binary classification, the count of true negatives is :math...
625941d5d486a94d0b98e364
def __cmp__(self, other): <NEW_LINE> <INDENT> if self.priority != other.priority: <NEW_LINE> <INDENT> return cmp(self.priority, other.priority) <NEW_LINE> <DEDENT> elif self.timestamp != other.timestamp: <NEW_LINE> <INDENT> return cmp(self.timestamp, other.timestamp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return...
Compare self's and other's priorities.
625941d5f8510a7c17cf991a
def paste(self): <NEW_LINE> <INDENT> if self.pastingActive: <NEW_LINE> <INDENT> self.gscene.removeItem(self.pasteObjectItemGroup) <NEW_LINE> del pasteObjectItemGroup <NEW_LINE> <DEDENT> self.pasteObjectItemGroup = self.gscene.createItemGroup(mainWin.cutCopyObjectList) <NEW_LINE> self.pasteDelta = self.pasteObjectItemGr...
TOWRITE
625941d5a934411ee37518b1
def random_string(minlen=5, maxlen=8): <NEW_LINE> <INDENT> length = randint(minlen, maxlen) <NEW_LINE> return ''.join(choice(string.lowercase) for x in xrange(length))
Generate random string of length between ``minlen`` and ``maxlen``.
625941d5a05bb46b383eca3f
def test_plot_series(self): <NEW_LINE> <INDENT> pass
Test plot_series().
625941d532920d7e50b283ef
def _resKeys(self, state): <NEW_LINE> <INDENT> if state not in ('cmp', 'exp'): <NEW_LINE> <INDENT> raise SieveException("state must be 'cmp' or 'exp'") <NEW_LINE> <DEDENT> if state == 'cmp': <NEW_LINE> <INDENT> libKeys = [] <NEW_LINE> for key in self._resLib: <NEW_LINE> <INDENT> if key in self._cmpTree: <NEW_LINE> <IND...
get residual keys based on library
625941d5379a373c97cfad63
def auth_loginRedirect(request, redirect, gateway=False): <NEW_LINE> <INDENT> if hasattr(settings, "ALWAYS_AUTH_USER"): <NEW_LINE> <INDENT> return always_auth(request, redirect) <NEW_LINE> <DEDENT> return cas_loginRedirect(request, redirect, gateway)
A general login redirection :param request: The incoming request :param redirect: The absolute/relative path to redirect the user after authentication :param gateway: If true, all login attempts should be PASSIVE (that is, the user should not be prompted for a login) :return: httpResponseRedirect: User selected area to...
625941d5287bf620b61d3c80
def _bokeh_residual_histogram( data: RegressionData, title_rows: Sequence[str], n_bins: int = DEFAULT_N_HISTOGRAM_BINS, ) -> Callable[[], Column]: <NEW_LINE> <INDENT> def function() -> Column: <NEW_LINE> <INDENT> targets = data.targets <NEW_LINE> predictions = data.predictions <NEW_LINE> p = figure(tools=TOOLS) <NEW_LI...
Plots a histogram of the errors.
625941d58e05c05ec3eea594
def has_new_ver(ver_fname, ver_url): <NEW_LINE> <INDENT> if not os.path.isfile(ver_fname): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> with open(ver_fname) as fobj: <NEW_LINE> <INDENT> local_ver = fobj.read() <NEW_LINE> <DEDENT> r = requests.get(ver_url) <NEW_LINE> if local_ver != r.text: <NEW_LINE> <INDENT> re...
有新版本返回True,否则返回False
625941d515baa723493c4195
def menu(file): <NEW_LINE> <INDENT> print("********************************************************************************") <NEW_LINE> print("* PDB FILE ANALYZER *") <NEW_LINE> print("***************************************************************************...
This function prints out the display menu. It takes file as an argument. The display menu contains all the options the user may input.
625941d55510c4643540f5fe
def print_metadata_info_quiet(metadata): <NEW_LINE> <INDENT> if 'data' in metadata: <NEW_LINE> <INDENT> print(str(metadata['data']))
Print condensed version of metadata.
625941d5e64d504609d74a5e
def firstMissingPositive1(self, A): <NEW_LINE> <INDENT> if len(A) ==0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> set0 = set() <NEW_LINE> for num in A: <NEW_LINE> <INDENT> if num <=0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif num not in set0: <NEW_LINE> <INDENT> set0.add(num) <NEW_LINE> <DEDENT> <DEDE...
My O(n) time and O(n) space solution Well, the requirement is O(1) space OJ time: 216ms
625941d5baa26c4b54cb133b
def _update_job(job_uuid, data, token): <NEW_LINE> <INDENT> r = requests.patch('{}/api/v1/jobs/{}/'.format(SHAREDCLOUD_CLI_URL, job_uuid), data=data, headers={'Authorization': 'Token {}'.format(token)}) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise Exception(r.content) <NEW_LINE> <DEDENT> return r
Updates a job in Sharedcloud. It's mostly used to send the results. :param job_uuid: job uuid :param data: dict containing the data to change :param token: user token
625941d58c3a8732951585d9
def _substitute_strings(self, string): <NEW_LINE> <INDENT> while '$' in string: <NEW_LINE> <INDENT> varname = re.search('\$\w*', string).group() <NEW_LINE> if varname in self.variables: <NEW_LINE> <INDENT> varvalue = self.variables[varname] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> errormsg = "Undefined variable " ...
Performs string substitution
625941d531939e2706e4d086
def test_0005_no_skip_signin(self): <NEW_LINE> <INDENT> with Transaction().start(DB_NAME, USER, context=CONTEXT): <NEW_LINE> <INDENT> self.setup_defaults() <NEW_LINE> app = self.get_app() <NEW_LINE> with app.test_client() as c: <NEW_LINE> <INDENT> c.post( '/cart/add', data={ 'product': self.product1.id, 'quantity': 5 }...
Ensure that guest orders cant directly skip to enter delivery method
625941d51f037a2d8b94641b
def vinn_eller_uavgjort(rute): <NEW_LINE> <INDENT> global rutefarger, counter <NEW_LINE> rutefarger[rute] = farge <NEW_LINE> counter += 1 <NEW_LINE> for i in [0, 3, 6]: <NEW_LINE> <INDENT> if rutefarger[1+i] == rutefarger[2+i] == rutefarger[3+i]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> for i in [0,...
For å kåre vinner så lagrer vi hvilken spiller som har skrevet i hvilken rute, i rutefarger = {. Variabelen --> farge, representerer spilleren til en hver tid. Spiller1 = 'red', Spiller2 = 'green' rute sendes videre fra tegn_stamp() ---------------------------------------Jonas--------
625941d563d6d428bbe4470e
def calculate_force(body, space_objects): <NEW_LINE> <INDENT> body.Fx = body.Fy = 0 <NEW_LINE> for obj in space_objects: <NEW_LINE> <INDENT> if body == obj: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> r = ((body.x - obj.x)**2 + (body.y - obj.y)**2)**0.5 <NEW_LINE> f = gravitational_constant*body.m*obj.m/(r**2) <NE...
Вычисляет силу, действующую на тело. Параметры: **body** — тело, для которого нужно вычислить дейстующую силу. **space_objects** — список объектов, которые воздействуют на тело.
625941d5004d5f362079a550
def insert(self, intervals, newInterval): <NEW_LINE> <INDENT> pos = -1 <NEW_LINE> for i in range(len(intervals)): <NEW_LINE> <INDENT> if intervals[i].start >= newInterval.start: <NEW_LINE> <INDENT> pos = i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if pos == -1: <NEW_LINE> <INDENT> if intervals and newInterval.start...
:type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]
625941d5377c676e912723c6
def asn_file_info(asn_file, verbose=1, path_to_FLT = './'): <NEW_LINE> <INDENT> asn = ASNFile(asn_file) <NEW_LINE> lines = ['# %s' %asn_file] <NEW_LINE> lines.append( '# flt_file filter exptime date_obs time_obs pos_targ1 pos_targ2') <NEW_LINE> for exp in asn.exposures: <NEW_LINE> <INDENT> flt_file = find_fits_gz(p...
asn_file_info(asn_file, verbose=1) Get header information from files defined in an ASN table. >>> asn_file_info('ib3702060_asn.fits') # ib3702060_asn.fits # flt_file filter exptime date_obs time_obs pos_targ1 pos_targ2 ib3702u4q_flt.fits.gz G141 1302.9 2010-04-15 19:03:01 0.00 ...
625941d597e22403b379d1b9
def can_shoot(goal_dist, goal_angle): <NEW_LINE> <INDENT> if goal_dist < params['SHT_DST'] and goal_angle > params['SHT_ANG']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Returns True if if player can have a good shot at goal
625941d523e79379d52ee780
def serialize( portobj ): <NEW_LINE> <INDENT> view = {} <NEW_LINE> if portobj.model.widget_hint: <NEW_LINE> <INDENT> view[ 'widget_hint' ] = portobj.model.widget_hint <NEW_LINE> <DEDENT> if portobj.model.widget_help: <NEW_LINE> <INDENT> view[ 'widget_help' ] = portobj.model.widget_help <NEW_LINE> <DEDENT> if portobj.mo...
We don't use the as_docs() method because that would not un-embed the port from its container object; but we do need this function to serialize the port on behalf of the objects that contain it.
625941d501c39578d7e7505a
def calculate_metrics(self, logits, labels, positive_class, step, display=True): <NEW_LINE> <INDENT> label = np.squeeze(labels.astype(np.int8)) <NEW_LINE> logit = np.squeeze(np.argmax(logits.astype(np.float), axis=1)) <NEW_LINE> self.AUC += skm.roc_auc_score(label, logit) <NEW_LINE> self.calls += 1 <NEW_LINE> for z in ...
Retreive the Accuracy, Sensitivity, Specificity :param logits: network predictions :param labels: the ground truth :param positive_class: the class we will consider positive for calculating ground truth :param step: what step we're on :param display: whether to print examples :return: acc, sn, sp
625941d52ae34c7f2600d34f
def repo_create(path: str) -> GitRepository: <NEW_LINE> <INDENT> repo = GitRepository(path, True) <NEW_LINE> if repo.worktree.exists(): <NEW_LINE> <INDENT> if not repo.worktree.is_dir(): <NEW_LINE> <INDENT> raise ValueError(f"{path} is not a directory!") <NEW_LINE> <DEDENT> if list(repo.worktree.iterdir()): <NEW_LINE> ...
Create a new repository at path.
625941d530bbd722463cbfe5
def test_get_tree_changes_delete(self): <NEW_LINE> <INDENT> filename = 'foo' <NEW_LINE> with open(os.path.join(self.repo.path, filename), 'w') as f: <NEW_LINE> <INDENT> f.write('stuff') <NEW_LINE> <DEDENT> porcelain.add(repo=self.repo.path, paths=filename) <NEW_LINE> porcelain.commit(repo=self.repo.path, message='test ...
Unit test for get_tree_changes delete.
625941d5d7e4931a7ee9e13c
def get_version(): <NEW_LINE> <INDENT> VERSION_FILE = 'datum/version.py' <NEW_LINE> mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) <NEW_LINE> if mo: <NEW_LINE> <INDENT> return mo.group(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Unable to find versi...
Extracts the version number from the version.py file.
625941d50c0af96317bb8407
def reducer(self, key, values): <NEW_LINE> <INDENT> seen = None <NEW_LINE> for item in values: <NEW_LINE> <INDENT> if item != seen: <NEW_LINE> <INDENT> seen = item <NEW_LINE> yield (key, [item]) <NEW_LINE> <DEDENT> <DEDENT> ''' ...................... fill in your code above ........................'''
...................... fill in your code below ........................
625941d507f4c71912b116a2
def run(self): <NEW_LINE> <INDENT> play_source = dict( name = "Ansible Tasks", hosts = self.hosts, gather_facts = 'no', tasks = self.tasks, ) <NEW_LINE> play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) <NEW_LINE> self.setOptions() <NEW_LINE> self._run(play=play)
run ansible tasks for hosts
625941d563b5f9789fde7304
def loads(body, context=None, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> decoder = objects.SpynlDecoder(context) <NEW_LINE> return json.loads(body, object_hook=decoder) <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> raise MalformedRequestException('application/json', error_cause=str(err)...
Return body as JSON.
625941d507d97122c4178aad
def forward_right(self): <NEW_LINE> <INDENT> self.forward() <NEW_LINE> self.turn_right()
前向右转
625941d576d4e153a657ed50
def is_rc(self): <NEW_LINE> <INDENT> return bool(re.search(r"-rc\d+$", self.version()))
Return True if rc.
625941d53c8af77a43ae39c0
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): <NEW_LINE> <INDENT> avg_X2 = np.dot(responsibilities.T, X * X) * norm <NEW_LINE> avg_means2 = gmm.means ** 2 <NEW_LINE> avg_X_means = gmm.means * weighted_X_sum * norm <NEW_LINE> return avg_X2 - 2 * avg_X_means + avg_means2 + min_covar
Performing the covariance M step for diagonal cases
625941d55e10d32532c5f145
def run(self, runWithEnviron=False): <NEW_LINE> <INDENT> suffix = '.png' <NEW_LINE> _MOD = "test.timeGraphImportStar" <NEW_LINE> if runWithEnviron: <NEW_LINE> <INDENT> from music21 import environment <NEW_LINE> environLocal = environment.Environment(_MOD) <NEW_LINE> fp = environLocal.getTempFile(suffix) <NEW_LINE> <DED...
Main code runner for testing. To set a new test, update the self.callTest attribute in __init__().
625941d54d74a7450ccd43e2
def getGroupInfo(self, group_id): <NEW_LINE> <INDENT> return self._groups.get(group_id, None)
Over-ride parent to not explode when getting group info dict by group id.
625941d57047854f462a1626
def add_variant(self, cp_or_sequence, variant_cp_or_sequence, variant_type=None, when=None, not_when=None, comment=None, ref=None): <NEW_LINE> <INDENT> char = self.get_char(cp_or_sequence) <NEW_LINE> char.add_variant(variant_cp_or_sequence, variant_type=variant_type, when=when, not_when=not_when, comment=comment, ref=r...
Add a variant to a code point. :param cp_or_sequence: Code point or code point sequence of the character to add the variant to. :param variant_cp_or_sequence: The code point or code point sequence of the variant. :param variant_type: The type for the variant, if an...
625941d5e76e3b2f99f3aa27
def _doGMM(self, samples, covariance_type): <NEW_LINE> <INDENT> n_samples = len(samples) <NEW_LINE> if n_samples > self.minSample: <NEW_LINE> <INDENT> score = np.zeros(self.maxComponents) <NEW_LINE> for test, train in self._split_crossvalidation(samples): <NEW_LINE> <INDENT> for k in xrange(self.maxComponents): <NEW_LI...
Learns the GMM probabilities for the particular class pair i,j with samples containing distance information as a list of 2-d vectors. Learning is done with EM algorithm. Number of components is determined with the BIC-score. Restricting the number of components to MAXCOMPONENTS. Returns the learned model as a class. ...
625941d54e4d5625662d45f4
@api_view(['GET']) <NEW_LINE> def get_credits(request, tmdb): <NEW_LINE> <INDENT> payload = { 'api_key': settings.TMDB_KEY} <NEW_LINE> url = settings.TMDB_URL.format(endpoint='movie') <NEW_LINE> url += str(tmdb) <NEW_LINE> url += '/credits' <NEW_LINE> r = requests.get(url=url, params=payload) <NEW_LINE> print(r.url) <N...
Returns movie's credits. Args: tmdb: movie's id. Returns: movie: a JSON containing the movie's credits.
625941d582261d6c526ab6c0
def _stop_iteration(self): <NEW_LINE> <INDENT> if not self._alive: <NEW_LINE> <INDENT> return True
Override the parent implementation, because we deal with this in the producer thread.
625941d5a8ecb033257d32eb
def lstm_step_backward(dnext_h, dnext_c, cache): <NEW_LINE> <INDENT> dx, dprev_h, dprev_c, dWx, dWh, db = None, None, None, None, None, None <NEW_LINE> (next_c, x, prev_h, prev_c, Wx, Wh, b, Ai, Af, Ao, Ag, i, f, o, g) = cache <NEW_LINE> do = np.tanh(next_c) * dnext_h <NEW_LINE> dtanh_next_c = o * dnext_h <NEW_LINE> dn...
Backward pass for a single timestep of an LSTM. Inputs: - dnext_h: Gradients of next hidden state, of shape (N, H) - dnext_c: Gradients of next cell state, of shape (N, H) - cache: Values from the forward pass Returns a tuple of: - dx: Gradient of input data, of shape (N, D) - dprev_h: Gradient of previous hidden sta...
625941d55fdd1c0f98dc0452
def test_reset_read_only_is_sent_to_all_clusters(self): <NEW_LINE> <INDENT> elasticsearch_clusters = self.default_elasticsearch_clusters() <NEW_LINE> for client in [self.elasticsearch1, self.elasticsearch2]: <NEW_LINE> <INDENT> client.indices.put_settings = mock.Mock() <NEW_LINE> <DEDENT> elasticsearch_clusters.reset_i...
Reset read only status should be sent to all clusters.
625941d545492302aab5e4e4
def __getattr__(self, name): <NEW_LINE> <INDENT> if name in self._data: <NEW_LINE> <INDENT> return self._data[name] <NEW_LINE> <DEDENT> elif name == 'pk': <NEW_LINE> <INDENT> return self._data.get(self._model._meta.pk.attname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError( "%r object has no attribu...
Return an attribute from the cached data.
625941d5d10714528d5fff03
def predicate_head(): <NEW_LINE> <INDENT> return first( Pattern.identifier_pattern() , Pattern.predicate_word_pattern() , Pattern.symbol_pattern() )
Parser for the LHS pattern of a predicate def
625941d56e29344779a6282f
def SerializationObjectNames(objectList, nameFormat='Temp*', start=0, padding=3): <NEW_LINE> <INDENT> if not isinstance(objectList, (list, tuple)): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if nameFormat.count('*') != 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> newNameList = [] <NEW_LINE> for i, obj in enume...
objectList must is a list or a tuple nameFormat mutst have one " * " Exp: [pCulbe, pCulbe1, pCulbe2, pCulbe3, pCulbe4] -> temp* -> [temp000, temp001, temp002, temp003, temp004] [pCulbe, pCulbe1, pCulbe2, pCulbe3, pCulbe4] -> C_temp*_geo_0 -> [C_temp000_geo_0, C_temp001_geo_0, C_temp002_geo_...
625941d556ac1b37e62643ec
def main(): <NEW_LINE> <INDENT> argument_spec = dict( type=dict(required=True, type='str', choices=['ip', 'vxlan']), source_ip=dict(required=False, type='str'), host_ip=dict(required=False, type='str'), host_port=dict(required=False, type='str'), host_vpn=dict(required=False, type='str'), version=dict(required=False, t...
main function entry
625941d57c178a314d6ef680
def test_append_keywords(self): <NEW_LINE> <INDENT> layer, _ = clone_padang_layer() <NEW_LINE> new_keywords = {'category': 'exposure', 'test': 'TEST'} <NEW_LINE> self.keyword_io.update_keywords(layer, new_keywords) <NEW_LINE> keywords = self.keyword_io.read_keywords(layer) <NEW_LINE> for key, value in new_keywords.iter...
Can we append file keywords with the generic readKeywords method.
625941d5460517430c3943a0
def test_uncluster_table_with_index(self): <NEW_LINE> <INDENT> stmts = [CREATE_TABLE_STMT, CREATE_STMT, "CLUSTER t1 USING t1_idx"] <NEW_LINE> inmap = self.std_map() <NEW_LINE> inmap['schema sd'].update({'table t1': { 'columns': [{'c1': {'type': 'integer'}}, {'c2': {'type': 'text'}}], 'indexes': {'t1_idx': {'keys': ['c1...
Change a table clustered on an index to remove cluster
625941d550485f2cf553cfb9
def _parse_result_row(self, row, candidates, county, county_ocd_id, **common_kwargs): <NEW_LINE> <INDENT> results = [] <NEW_LINE> assert len(candidates) == len(row) - 1 <NEW_LINE> i = 1 <NEW_LINE> raw_jurisdiction = self._parse_jurisdiction(row[0]) <NEW_LINE> if raw_jurisdiction in self.COUNTY_JURISDICTIONS: <NEW_LINE>...
Create result records from a row of results for a precinct Args: row (list): Data from a row in the spreadsheet. The first column should be the precinct name. All other columns are vote values candidates (list): List of candidate full names county (string): County name county_ocd_id (...
625941d5fbf16365ca6f63e4
def _get_url(self, uri): <NEW_LINE> <INDENT> return '{}/{}'.format(Pocket.api_url, uri)
Construct the request URL :param uri: the required URI :return: The full URL :rtype: str
625941d5a4f1c619b28b0254
@task <NEW_LINE> def clean(): <NEW_LINE> <INDENT> puts('Removing local object files and caches...') <NEW_LINE> with settings(warn_only=True): <NEW_LINE> <INDENT> local('find . -name "*.pyc" | xargs rm') <NEW_LINE> local('find . -name "*.pyo" | xargs rm') <NEW_LINE> local('find . -name "__pycache__" -type directory | xa...
Removes local python cache files.
625941d5711fe17d82542587
def is_module_installed(env, module_name): <NEW_LINE> <INDENT> return module_name in env.registry._init_modules
Check if an odoo addon is installed. :param module_name: name of the addon
625941d53cc13d1c6d3c7598
@pytest.mark.parametrize('validator_headers', [{'ETag': ETAG}, {'Last-Modified': LAST_MODIFIED}]) <NEW_LINE> @pytest.mark.parametrize('cache_headers', [{'Cache-Control': 'max-age=0'}, {'Expires': '0'}]) <NEW_LINE> @patch('requests_cache.cache_control.datetime') <NEW_LINE> def test_update_from_response__revalidate(mock_...
If expiration is 0 and there's a validator, the response should be cached, but with immediate expiration
625941d57b180e01f3dc4a19
def format(self, record): <NEW_LINE> <INDENT> message = logging.Formatter.format(self, record) <NEW_LINE> try: <NEW_LINE> <INDENT> color = ColorFormatter.color_level[record.levelno] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> color = self.default_color <NEW_LINE> <DEDENT> message = color + message + ColorFormatter....
Format log messages. Piggybacks off the default format method. Injects color escapes & resets, based on the log level.
625941d59b70327d1c4e0ff4
def register(self, event_name, handler): <NEW_LINE> <INDENT> self._events.register(event_name, handler)
Register a handler with an event. :type event_name: str :param event_name: The name of the event. :type handler: callable :param handler: The callback to invoke when the event is emitted. This object must be callable, and must accept ``**kwargs``. If either of these preconditions are not met, a ``ValueE...
625941d5009cb60464c635cf
def format_date(date): <NEW_LINE> <INDENT> if isinstance(date, six.string_types): return date <NEW_LINE> return date.strftime("%A, %d/%m/%Y")
Standard date formatting
625941d566673b3332b922b0
def prefetch_metrics(self, container_id): <NEW_LINE> <INDENT> self.__lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if container_id not in self.__container_scoreboard: <NEW_LINE> <INDENT> self._add_fetch_task(container_id) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.__lock.release()
Initiates requesting invoking `stats` for the specified container. If you invoke this, you must also eventually invoke `get_metrics` with the same container. By invoking this first, the `get_metrics` call will take less time when issuing many `stats` requests. Whenever possible, you should first invoke this method f...
625941d5046cf37aa974cf65
def magnetization(squid_voltage, orientation='perpendicular'): <NEW_LINE> <INDENT> if orientation not in ('perpendicular', 'parallel'): <NEW_LINE> <INDENT> raise Exception('No valid orientation') <NEW_LINE> <DEDENT> if orientation == 'parallel': <NEW_LINE> <INDENT> return 487346.93877551 * squid_voltage <NEW_LINE> <DED...
Return the magnetization (unit: Ampere/Meter) at the SQUID as a function of the SQUID voltage (unit: Volt).
625941d58e71fb1e9831d9c7
def __init__(self): <NEW_LINE> <INDENT> self.Image = None <NEW_LINE> self.Url = None <NEW_LINE> self.FaceModelVersion = None
:param Image: 图片 base64 数据,base64 编码后大小不可超过5M。 jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。(图片的宽高比请接近3:4,不符合宽高比的图片返回的分值不具备参考意义)。 支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。 :type Image: str :param Url: 图片的 Url 。对应图片 base64 编码后大小不可超过5M。 jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。 Url、Image必须提供一个,如果都提供,只使用 Url。 (图片的宽高比请接近 3...
625941d5283ffb24f3c55b1e
def Clear(self): <NEW_LINE> <INDENT> IN_MEMORY_CACHE.clear() <NEW_LINE> with self.Session(commit=True) as session: <NEW_LINE> <INDENT> session.query(HashCacheRecord).delete() <NEW_LINE> <DEDENT> app.Log(2, "Emptied cache")
Empty the cache. If the HashCache was created with keep_in_memory=True, this clears the in-memory cache. Note that the in-memory cache is shared between all instances of HashCache.
625941d591af0d3eaac9bc39
def test_join_leave_methods(self): <NEW_LINE> <INDENT> instance = GroupMembers() <NEW_LINE> first_user = GroupMembers.objects.get(pk=10) <NEW_LINE> second_user = GroupMembers.objects.get(pk=11) <NEW_LINE> instance.join(first_user.nick, first_user.group, first_user.offline, first_user.channel) <NEW_LINE> instance.join(s...
Tests the join and leave methods in class GroupMembers. First two users join and we check the parameters of the created object. Then one user leaves and we make sure that their object is deleted
625941d5293b9510aa2c34b3
def send_status(self, status): <NEW_LINE> <INDENT> self._request._response_status_line = status <NEW_LINE> self._request.response_status = int(status[:3]) <NEW_LINE> self._set_state(ResponseHeadersWaitState)
Send status line
625941d5adb09d7d5db6c9ae
def pdf(self, val): <NEW_LINE> <INDENT> return np.where(val > 0, np.polyval(np.polyder(self.p), val) * np.exp(np.polyval(self.p, val)), self.eta)
Probability densitiy function
625941d5d8ef3951e324375c
def inst_j(vm, offset): <NEW_LINE> <INDENT> vm.regs[vm.REG_PC] += offset
Unconditional jump.
625941d54428ac0f6e5baa12
def new_saved_frame_seq(self): <NEW_LINE> <INDENT> return []
Creates a new sequence of saved/cached frame information.
625941d5d486a94d0b98e365
def fill_in(gender, age_list, weights): <NEW_LINE> <INDENT> for index, row in df.iterrows(): <NEW_LINE> <INDENT> if str(row[5])=="nan" and row[3] == gender: <NEW_LINE> <INDENT> for age_cat in age_list: <NEW_LINE> <INDENT> if row[4] == age_cat: <NEW_LINE> <INDENT> max_key = max(weights[age_cat], key=weights[age_cat].get...
gender: since we cant to get this function for females and males we have to determine for which gender do we want to get the fill out age_list: the age categories can be found for a particular gender weights: dictionary, which has the age_categories and in that age category different weight categories with number of...
625941d576d4e153a657ed51
def portfolio_markowitz(a, b, c, d, mu, Sigma_inv, C_0, gamma): <NEW_LINE> <INDENT> n = mu.shape[0] <NEW_LINE> logger.debug('Number of assets = {0}'.format(n)) <NEW_LINE> ones_matrix = np.ones((n, 1)) <NEW_LINE> logger.debug('\nones_matrix\n{0}'.format(ones_matrix)) <NEW_LINE> if isinstance(gamma, (list, tuple, np.ndar...
Calculate sigma_opt, mu_opt and theta_opt Args: a (scalar): b (scalar): c (scalar): d (scalar): mu (ndarray): dimensions n x 1 Sigma_inv (ndarray): dimensions n x n C_0 (scalar): capital that can be invested gamma (scalar or ndarray): absolute risk aversion parameter Raises: Retur...
625941d51d351010ab855d3b
def schedule(self, func, *args, **kwargs): <NEW_LINE> <INDENT> item = _ScheduledItem(func, args, kwargs) <NEW_LINE> self._schedule_items.append(item)
Schedule a function to be called every frame. The function should have a prototype that includes ``dt`` as the first argument, which gives the elapsed time, in seconds, since the last clock tick. Any additional arguments given to this function are passed on to the callback:: def callback(dt, *args, **kwargs): ...
625941d5fff4ab517eb2f65c
def __len__(self): <NEW_LINE> <INDENT> return len(self.__routes);
Gets the number of Routes in this collection. @return: int The number of routes
625941d5b57a9660fec33aa6
def create_download_link(product=None, order=None, subtype=None, **kwargs): <NEW_LINE> <INDENT> if product and order and subtype == "download": <NEW_LINE> <INDENT> new_link = DownloadLink(downloadable_product=product, order=order, key=product.create_key(), num_attempts=0) <NEW_LINE> new_link.save() <NEW_LINE> <DEDENT> ...
Creates a download link for a Downloadable Product on order success.
625941d524f1403a92600d84
def addTrpHydrogen(residue): <NEW_LINE> <INDENT> CD = None <NEW_LINE> NE = None <NEW_LINE> DE = None <NEW_LINE> for atom in residue: <NEW_LINE> <INDENT> if atom.name == "CD1": <NEW_LINE> <INDENT> CD = atom <NEW_LINE> <DEDENT> elif atom.name == "NE1": <NEW_LINE> <INDENT> NE = atom <NEW_LINE> <DEDENT> elif atom.name ...
Adds Trp hydrogen atoms to residues according to the 'old way'.
625941d5cdde0d52a9e53253
def __gt__(self, other): <NEW_LINE> <INDENT> return self.const > other.const
Implement >.
625941d573bcbd0ca4b2c295
def upload_configuration_files(upload_url, tar_path): <NEW_LINE> <INDENT> log.info('uploading configuraiton file: {} to {}'.format(tar_path, upload_url)) <NEW_LINE> if upload_url: <NEW_LINE> <INDENT> headers = {'Content-Type': 'application/octet-stream'} <NEW_LINE> file = open(tar_path, 'rb') <NEW_LINE> response = requ...
Upload the configuration files to the target workspace.
625941d5dc8b845886cb5755
def fillFromAnalytic(self, *args): <NEW_LINE> <INDENT> return _MEDCouplingClient.MEDCouplingFieldDouble_fillFromAnalytic(self, *args)
fillFromAnalytic(self, int nbOfComp, char func) 1
625941d58e7ae83300e4b1ed
def _loadMeasurement(self, measurement_filename): <NEW_LINE> <INDENT> self.logger.debug("Entering _loadMeasurement") <NEW_LINE> measurement_filename = str(measurement_filename) <NEW_LINE> freq_response = self.loadFrequencyResponse(measurement_filename) <NEW_LINE> self.window.freq_response = freq_response <NEW_LINE> sel...
Loads measurement from the specified filename. :param measurement_filename: The filename containing the measurement to load. :type measurement_filename: str
625941d5a05bb46b383eca40
def decode_cf_variables(variables, attributes, concat_characters=True, mask_and_scale=True, decode_times=True, decode_coords=True): <NEW_LINE> <INDENT> dimensions_used_by = defaultdict(list) <NEW_LINE> for v in variables.values(): <NEW_LINE> <INDENT> for d in v.dims: <NEW_LINE> <INDENT> dimensions_used_by[d].append(v) ...
Decode a several CF encoded variables. See: decode_cf_variable
625941d54c3428357757c547
def _init_graph(self): <NEW_LINE> <INDENT> with tf.variable_scope('edge_nn_in'): <NEW_LINE> <INDENT> self.W_in, self.b_in = _fully_connected_var( self.params.edge_dim, self.params.edge_nn_layers, self.params.edge_fc_dim, self.params.node_dim**2) <NEW_LINE> <DEDENT> with tf.variable_scope('edge_nn_out'): <NEW_LINE> <IND...
Edge network
625941d5f548e778e58cd79e
def add_menu(self, menu: 'Menu') -> bool: <NEW_LINE> <INDENT> newer_list = [] <NEW_LINE> if menu not in self.menus and menu != []: <NEW_LINE> <INDENT> for values in menu.dishes: <NEW_LINE> <INDENT> if values in self.dishes: <NEW_LINE> <INDENT> newer_list.append(values) <NEW_LINE> <DEDENT> <DEDENT> if newer_list == self...
Add a menu to the restaurant if all the dishes are available. Menu cannot be added if: - it has no dishes - the menu with the same dishes (in any order) already exists
625941d5e1aae11d1e749ed8
def set_coordtype_cb(self, w, val): <NEW_LINE> <INDENT> self.use_radec = val
Toggle between RA/DEC or X/Y coordinates.
625941d5046cf37aa974cf66
def __init__(self, bbcon, line_sensob): <NEW_LINE> <INDENT> if not isinstance(line_sensob, LineSensob): <NEW_LINE> <INDENT> raise Exception("Invalid type for line_sensob: "+str(type(line_sensob))) <NEW_LINE> <DEDENT> super().__init__(bbcon, [line_sensob]) <NEW_LINE> self.PRIORITY = 50
:param bbcon: Bbcon :param ir_sensob: :return:
625941d58da39b475bd65195
def ling_angular_detail_form(**kwargs): <NEW_LINE> <INDENT> return LingAngularDetailForm(**kwargs)
Function to get LingAngular's detail form. :param kwargs: form properties :return: Form
625941d5796e427e537b07e7
def ch1_9(): <NEW_LINE> <INDENT> print("\nch1_9:") <NEW_LINE> a={'x':1,'y':2,'z':3} <NEW_LINE> b={'w':100,'x':50,'y':2} <NEW_LINE> print(a.keys() & b.keys()) <NEW_LINE> print(a.keys() - b.keys()) <NEW_LINE> print(a.items()& b.items())
1.9 在两个字典中寻找相同点 寻找相同的键,相同的值等 使用集合操作 如 & -
625941d59b70327d1c4e0ff5
def pid_get(self, pid_id, setting): <NEW_LINE> <INDENT> return self.mycodo.pid_get(pid_id, setting)
Get PID setting
625941d5dd821e528d63b3c8
def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): <NEW_LINE> <INDENT> self.dlg = MainAppDialog() <NEW_LINE> icon = QIcon(icon_path) <NEW_LINE> action = QAction(icon, text, parent) <NEW_LINE> action.triggered.connect...
Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be cal...
625941d55e10d32532c5f146
def __init__(self, dev, backend): <NEW_LINE> <INDENT> self._ctx = _ResourceManager(dev, backend) <NEW_LINE> self.__default_timeout = _DEFAULT_TIMEOUT <NEW_LINE> self._serial_number, self._product, self._manufacturer = None, None, None <NEW_LINE> self._langids = None <NEW_LINE> desc = backend.get_device_descriptor(dev) ...
Initialize the Device object. Library users should normally get a Device instance through the find function. The dev parameter is the identification of a device to the backend and its meaning is opaque outside of it. The backend parameter is a instance of a backend object.
625941d57b180e01f3dc4a1a
def get_basename_without_extension(filepath): <NEW_LINE> <INDENT> return os.path.basename(os.path.splitext(filepath)[0])
Getting the basename of the filepath without the extension E.g. 'data/formatted/dischargeSummariesClean.csv' -> 'dischargeSummariesClean'
625941d5379a373c97cfad66
def _get_data_from_context(context): <NEW_LINE> <INDENT> data = '' <NEW_LINE> try: <NEW_LINE> <INDENT> if context.text: <NEW_LINE> <INDENT> data = context.text <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> data = '' <NEW_LINE> <DEDENT> context.text = u'' <NEW_LINE> result = jinja2.Template(dat...
Use context.text as a template and render against any stored state.
625941d55fdd1c0f98dc0453
def run_notch_filter_example(): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> import numpy as np <NEW_LINE> import pyrb <NEW_LINE> from scipy import signal <NEW_LINE> from pyrb.mpl import open_figure, format_axes, largefonts <NEW_LINE> plt.style.use('bmh') <NEW_LINE> fs = 6000 <NEW_LINE> N = 1e5 <NEW_L...
run a notch filter example
625941d58e05c05ec3eea596
def apk(actual, predicted, k=10): <NEW_LINE> <INDENT> if not isinstance(predicted, list): <NEW_LINE> <INDENT> predicted = list(predicted) <NEW_LINE> <DEDENT> if len(predicted) > k: <NEW_LINE> <INDENT> predicted = predicted[:k] <NEW_LINE> <DEDENT> score = 0.0 <NEW_LINE> num_hits = 0.0 <NEW_LINE> for i, p in enumerate(pr...
Computes the average precision at k. This function computes the average prescision at k between two lists of items. Parameters ---------- actual : list A list of elements that are to be predicted (order doesn't matter) predicted : list A list of predicted elements (order does matter) k : int, optio...
625941d5ad47b63b2c50a19f
def Commit(self, user=""): <NEW_LINE> <INDENT> self.usedconnection.commit()
Commit the changes made to the database, if supported
625941d5e64d504609d74a60
def get_resource_mapping(self): <NEW_LINE> <INDENT> events = {} <NEW_LINE> for transition in self._transitions: <NEW_LINE> <INDENT> if self.state == transition.get('source', None): <NEW_LINE> <INDENT> events.update({self._trigger_attrs.get(transition['trigger']).get('resource'): transition['trigger']}) <NEW_LINE> <DEDE...
This will return a dict containing a mapping of resource => trigger Example: {'approve': 'approval_from_someone'} resource should be utilised in the endpoint/resource and trigger is the callee trigger method in the workflow
625941d54f6381625f114c5b
def test_evalua_NodoProducto(self): <NEW_LINE> <INDENT> n_producto = NodoProducto(NodoValor(2),NodoValor(3)) <NEW_LINE> self.assertEqual(n_producto.evalua(),6)
La evaluacion de un NodoProducto ha de ser el producto de las evaluaciones de sus hijos
625941d585dfad0860c3b07b
def safe_set_from_dict(obj, key, src={}, always_cpy=True, def_val=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if def_val is None and hasattr(obj, key): <NEW_LINE> <INDENT> def_val = getattr(obj, key) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.info(e) <NEW_LINE> <DEDENT> try: <NE...
will set an object's attribute from a value in a source dict
625941d5baa26c4b54cb133e
def __init__(self, hub, cert_conf=None, secure=True, app_name=None, app_id=None): <NEW_LINE> <INDENT> self._hub = hub <NEW_LINE> self._manager = tendril.get_manager('tcp', util.outgoing_endpoint(hub)) <NEW_LINE> self._wrapper = util.cert_wrapper(cert_conf, 'notifier', secure=secure) <NEW_LINE> self._app_name = app_name...
Initialize a ``NotificationServer`` object. :param hub: The address of the hub, as a tuple of hostname and port. :param cert_conf: The path to the certificate configuration file. Optional. :param secure: If ``False``, SSL will not be used. Defaults to ``True``. :param app...
625941d5bde94217f368300f
@slim.add_arg_scope <NEW_LINE> def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None, use_bounded_activations=False): <NEW_LINE> <INDENT> with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc: <NEW_LINE> <INDENT> depth_in = slim.utils.last_dimension(inputs.get_sha...
Bottleneck residual unit variant with BN after convolutions. This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should u...
625941d5377c676e912723c8
def _get_median_weiszfeld(points_list,epsilon) : <NEW_LINE> <INDENT> sum_distances=[0]*len(points_list) <NEW_LINE> initial_point_latitude,initial_point_longitude=0,0 <NEW_LINE> for point in points_list : <NEW_LINE> <INDENT> initial_point_latitude+=point.latitude <NEW_LINE> initial_point_longitude+=point.longitude <NEW_...
It's an iterative algorithme of Weiszdeld corrected by Yehuda Vardi and Cun-Hui Zhang in the paper "The multivariate L1-median and associated data depth, 1999", the returned geometric median isn't necessarily chosen from the given list of points. The used initial point is the mean point of the points_list. Parameters ...
625941d51f037a2d8b94641e
def ofertas(request): <NEW_LINE> <INDENT> productos = Producto.objects.filter(estado="O") <NEW_LINE> return direct_response(request,"productos/ofertas.html", {"productos": productos, "titulo": "Ofertas Laboratorios La cooper"})
muestra todas las ofertas para los feeds
625941d594891a1f4081bcca
@typechecked <NEW_LINE> def np_incorrect_return_dtype(arr: Array[np.int64]) -> Array[np.int32]: <NEW_LINE> <INDENT> return arr
Test function.
625941d56aa9bd52df036fc4
def format_mac_string_to_bytes(mac_string): <NEW_LINE> <INDENT> return [int(b,16) for b in mac_string.split('-')]
"00-11-22-33-44-55-66-77" -> [0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77]
625941d521a7993f00bc7f12
def month_with_items(request): <NEW_LINE> <INDENT> months = Post.objects.published(site_id=settings.SITE_ID).dates('published_on', 'month') <NEW_LINE> return {'month_with_items': months}
Return the latest posts.
625941d5a79ad161976cc366
def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT): <NEW_LINE> <INDENT> traceroute_result = {} <NEW_LINE> source_str = '' <NEW_LINE> maxttl_str = '' <NEW_LINE> wait_str = '' <NEW_LINE> if source: <NEW_LINE> <INDENT> source_str = 'source {source}'.format(sou...
Execute traceroute and return results.
625941d5462c4b4f79d1d8f0
def required_laurent_prec(self, min_exp=0, order_1=ZZ(0)): <NEW_LINE> <INDENT> (min_exp, order_1) = self._canonical_min_exp(min_exp, order_1) <NEW_LINE> return self._quasi_form_matrix(min_exp=min_exp, order_1=order_1).dimensions()[0] + min_exp
Return an upper bound for the required precision for Laurent series to uniquely determine a corresponding (quasi) form in ``self`` with the given lower bound ``min_exp`` for the order at infinity (for each quasi part). .. NOTE:: For ``n=infinity`` only the holomorphic case (``min_exp >= 0``) is supported (in ...
625941d50383005118ecf802
def find_md5checksum(device=None, file_name=None): <NEW_LINE> <INDENT> if device is None or file_name is None: <NEW_LINE> <INDENT> raise Exception("device and file_name are mandatory arguments") <NEW_LINE> <DEDENT> resp = device.shell(command="md5sum " + file_name).response() <NEW_LINE> match = re.search("([a-fA-F\d]{3...
TO find the MD5 Checksum of a file on linux. Example : Find MD5checksum device=${server} file=/var/www/html/1kb.html :param str device: **REQUIRED** Device handle of the Linux PC :param str file_name: **REQUIRED** File name with its path whose MD5 checksum needs to be found. :return: Returns the MD5 checksum...
625941d57b25080760e39679