code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def print_channel_attrs(self, channels=[0]): <NEW_LINE> <INDENT> for c in channels: <NEW_LINE> <INDENT> print("Getting attributes for channel {}".format(c)) <NEW_LINE> attrs = self.get_channel_attrs(c) <NEW_LINE> for (k, it) in attrs.items(): <NEW_LINE> <INDENT> print("key: " + k) <NEW_LINE> print("value: " + str(it))
Print the attributes of channels. Defaults to only channel 0.
625941f3099cdd3c635f1247
def test_serialize_with_env_var_value(self): <NEW_LINE> <INDENT> mocked_serialized_value = MagicMock() <NEW_LINE> mocked_instance = MagicMock() <NEW_LINE> property = BaseProperty(Type, title="property") <NEW_LINE> property.is_expression = MagicMock(return_value=False) <NEW_LINE> property.is_env_var = MagicMock(return_v...
Return raw PropertyValue.value if it's an environment variable.
625941f3187af65679ca5710
def get_stack_set_operations(self, client_session, stack_set_name, inprogress_status): <NEW_LINE> <INDENT> stack_set_operations = [] <NEW_LINE> paginator = client_session.get_paginator('list_stack_set_operations') <NEW_LINE> try: <NEW_LINE> <INDENT> response_iterator = paginator.paginate( StackSetName=stack_set_name, )...
:param client_session: :param stack_set_name: :param inprogress_status: :return:
625941f330c21e258bdfaa94
def spp() -> None: <NEW_LINE> <INDENT> repo = git.Repo(search_parent_directories=True) <NEW_LINE> print(repo.git.stash('save'), repo.git.pull('--rebase'), repo.git.stash('pop'), repo.git.stash('list'))
Stash local changes, pull with ``--rebase``, and pop the latest stash. :note: Use ``spp()`` if you try to pull with ``--rebase`` and get an error that says:: error: cannot pull with rebase: You have unstaged changes. error: please commit or stash them. With ``spp()`` the stash is ...
625941f3ab23a570cc250777
def debug(self): <NEW_LINE> <INDENT> out = "" <NEW_LINE> for v in self.__dict__: <NEW_LINE> <INDENT> out += self.__dict__[v].debug() <NEW_LINE> <DEDENT> return out
Format all the variable values tu be displayed on a web page Parameters ---------- Returns ------- out: str Examples -------- >>> variables = HTMLVariableSet(["a", "b", "c"], ["d"]) >>> print(variables.debug()) a=-1 b=-1 c=-1 d= <BLANKLINE>
625941f3566aa707497f4b4f
def chunk(s, chunksize): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> length = len(s) <NEW_LINE> chunks = [] <NEW_LINE> while index < length: <NEW_LINE> <INDENT> chunks.append(s[index:index+chunksize]) <NEW_LINE> index += chunksize <NEW_LINE> <DEDENT> return chunks
Return a list of s chunked into chunksize bits. e.g. chunk("abcdefgh", 2) -> ['ab', 'cd', 'ef', 'gh']
625941f3b545ff76a8914405
def rk4_N(fx, x0, consts, ti, tf, steps): <NEW_LINE> <INDENT> w, t = [], [] <NEW_LINE> w.append(x0) <NEW_LINE> t.append(ti) <NEW_LINE> h = 1.0 * (tf-ti)/steps <NEW_LINE> for i in range(steps): <NEW_LINE> <INDENT> k1 = np.multiply(h, fx(t[i], w[i], consts[:])) <NEW_LINE> k2 = np.multiply(h, fx(t[i] + h/2, w[i] + 0.5*k1,...
4th order Runge-Kutta method with the option to pass the constant of the function separately, useful when you need to solve a system for different values of its parameters. :param fx: function to be iterated :param x0: initial conditions of in list for of size n, data type float :param consts: the parameters of your OD...
625941f33cc13d1c6d3c7967
def get_update_items(self): <NEW_LINE> <INDENT> return [ self.a_name, self.a_url, self.a_picurl, self.a_publisher, self.a_subtitle, self.a_description, self.a_classify, self.a_defaulttags, self.a_softgame, self.a_getdate, self.a_source, self.a_pkgname ]
get base item list(update)
625941f3e76e3b2f99f3adf1
def create_test_model(self, input_nc, output_nc): <NEW_LINE> <INDENT> model = nn.Sequential() <NEW_LINE> ngf=self.ngf <NEW_LINE> model.add_module('res_block_1', self.res_block(output_nc)) <NEW_LINE> return model
Function which pieces together the model
625941f3711fe17d8254294d
def rollback(service_ids, backend_ids): <NEW_LINE> <INDENT> failed = {'backend_ids': set(), 'service_ids': set()} <NEW_LINE> for id in service_ids: <NEW_LINE> <INDENT> retry = 0 <NEW_LINE> while retry < 5: <NEW_LINE> <INDENT> time.sleep(5 * retry) <NEW_LINE> req = requests.delete( base_url + "/admin/api/services/{0}.js...
Roll back the execution of populator Args: service_ids (list of integer): the list of services to delete backend_ids (list of integer): the list of backends to delete
625941f3f8510a7c17cf9cf1
def __getitem__(self, item): <NEW_LINE> <INDENT> return self.__vars[item]
Returns an item in this ExtractedContext or raises KeyError. :raises: KeyError :param item: Name of item to get. :type item: str :rtype: object
625941f3e8904600ed9f2527
def __init__(self, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, google_place_id=None, google_place_type=None): <NEW_LINE> <INDENT> super(InputVenueMessageContent, self).__init__() <NEW_LINE> assert_type_or_raise(latitude, float, parameter_name="latitude") <NEW_LINE> self.latitude = lat...
Represents the content of a venue message to be sent as the result of an inline query. Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. https://core.telegram.org/bots/api#inputvenuemessagecontent Parameters: :param latitude: Latitude of the venue in degree...
625941f3eab8aa0e5d26e14a
def __init__(self, name, x, y, compute_training_error=False, examples_for_training_error_approx=None, save=True, top_k_acc=False): <NEW_LINE> <INDENT> super().__init__(name, x, y, compute_training_error=compute_training_error, examples_for_training_error_approx=examples_for_training_error_approx, save=save, top_k_acc=t...
Using this class assumes that the model knows where training data comes from
625941f357b8e32f52483a8f
def set_weights(self, weights): <NEW_LINE> <INDENT> params = self.weights <NEW_LINE> if len(params) != len(weights): <NEW_LINE> <INDENT> raise ValueError('Length of the specified weight list (' + str(len(weights)) + ') does not match the number of weights ' + 'of the optimizer (' + str(len(params)) + ')') <NEW_LINE> <D...
Sets the weights of the optimizer, from Numpy arrays. Should only be called after computing the gradients (otherwise the optimizer has no weights). # Arguments weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the op...
625941f329b78933be1e5c94
def soft_reset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = self.send_cmd(create.OP_SOFT_RESET) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> sleep(3) <NEW_LINE> <DEDENT> return ret
Soft reset (an undocumented function). Useful when the Create has been switched to Passive Mode WHILE power is available -- it apparently only detects the rising current, so it might not actually begin charging. This is a somewhat undocumented feature (but is mentioned in the iRobot website support FAQ). It forces th...
625941f38a349b6b435e8762
def parse_creds_file(path='/etc/cfn/cfn-credentials'): <NEW_LINE> <INDENT> creds = {'AWSAccessKeyId': None, 'AWSSecretKey': None} <NEW_LINE> for line in open(path): <NEW_LINE> <INDENT> for key in creds: <NEW_LINE> <INDENT> match = re.match("^%s *= *(.*)$" % key, line) <NEW_LINE> if match: <NEW_LINE> <INDENT> creds[key]...
Parse the cfn credentials file. Default location is as specified, and it is expected to contain exactly two keys "AWSAccessKeyId" and "AWSSecretKey) The two keys are returned a dict (if found)
625941f34f6381625f11502b
def longestConsecutive(self, nums): <NEW_LINE> <INDENT> if nums is None or len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> nums_set = set(nums) <NEW_LINE> res = 0 <NEW_LINE> while len(nums_set)>0: <NEW_LINE> <INDENT> num = nums_set.pop() <NEW_LINE> begin_num,end_num=num,num <NEW_LINE> while (end_num+1)...
:type nums: List[int] :rtype: int
625941f38e7ae83300e4b5bf
def test_blank_string(self): <NEW_LINE> <INDENT> fasta = Fasta('data/genes.fasta', as_raw=True) <NEW_LINE> assert fasta['gi|557361099|gb|KF435150.1|'][0:0] == ''
seq[0:0] should return a blank string mdshw5/pyfaidx#53
625941f37c178a314d6efa5a
def longestValidParentheses(self, s): <NEW_LINE> <INDENT> openc,prevV,res,maxl = 0,0,0,0 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> if c=='(': openc += 1 <NEW_LINE> elif openc: <NEW_LINE> <INDENT> openc -= 1 <NEW_LINE> res += 2 <NEW_LINE> if not openc: <NEW_LINE> <INDENT> prevV += res <NEW_LINE> res = 0 <NEW_LINE> maxl...
:type s: str :rtype: int
625941f396565a6dacc8fcb9
def test___init__1(self): <NEW_LINE> <INDENT> r = Ray(Point((0, 0)), Point((1, 1))) <NEW_LINE> r = Ray(Point((8, -3)), Point((-5, 9)))
Tests generic cases. <tc>#tests#Ray.__init__</tc>
625941f38c3a8732951589b2
def random_user_id() -> int: <NEW_LINE> <INDENT> return random.randint(200000000, 299999999)
Generates a random user id
625941f3baa26c4b54cb1709
def white_diff_step(sandbox, output_filename, correct_output_filename): <NEW_LINE> <INDENT> if sandbox.file_exists(output_filename): <NEW_LINE> <INDENT> out_file = sandbox.get_file(output_filename) <NEW_LINE> res_file = sandbox.get_file("res.txt") <NEW_LINE> if white_diff(out_file, res_file): <NEW_LINE> <INDENT> outcom...
Assess the correctedness of a solution by doing a simple white diff against the reference solution. It gives an outcome 1.0 if the output and the reference output are identical (or differ just by white spaces) and 0.0 if they don't (or if the output doesn't exist). sandbox (Sandbox): the sandbox we consider. output_fi...
625941f3627d3e7fe0d69442
def __getitem__(self, ngram): <NEW_LINE> <INDENT> return self._ngrams.get(ngram, 0.0)
Return the n-gram frequency (zero if it does not appear).
625941f35fdd1c0f98dc0826
def invert_alpha(self): <NEW_LINE> <INDENT> self.alpha = 255 - self.alpha
This function ... :return:
625941f3adb09d7d5db6cd7c
def predict_text(self, tokens, **kwargs): <NEW_LINE> <INDENT> featurizer = kwargs.get('featurizer') <NEW_LINE> if featurizer is None: <NEW_LINE> <INDENT> mxlen = kwargs.get('mxlen', self.mxlen if hasattr(self, 'mxlen') else len(tokens)) <NEW_LINE> maxw = kwargs.get('maxw', self.maxw if hasattr(self, 'maxw') else max([l...
Utility function to convert lists of sentence tokens to integer value one-hots which are then passed to the tagger. The resultant output is then converted back to label and token to be printed. This method is not aware of any input features other than words and characters (and lengths). If you wish to use other feat...
625941f3004d5f362079a91e
def _repr_(self): <NEW_LINE> <INDENT> s = str(self._obj) <NEW_LINE> first_char = s[0] <NEW_LINE> s = s[1:].replace('+', ' + ').replace('-', ' - ') <NEW_LINE> return first_char + s
TESTS:: sage: U1 = UniversalCyclotomicField(names='E') sage: U2 = UniversalCyclotomicField(names='UCF') sage: U1.gen(5,2) E(5)^2 sage: U2.gen(5,2) E(5)^2
625941f37047854f462a19f2
def test_no_percent(self): <NEW_LINE> <INDENT> analysis = self.get_analysis(USES_STRING_FORMAT) <NEW_LINE> self.assertNotIn(self.comments.PERCENT_FORMATTING, (item.comment for item in analysis['comments']))
Test no percent string formatting false positive.
625941f399cbb53fe67931d4
def _variable_with_weight_decay(self, name, shape, stddev, wd): <NEW_LINE> <INDENT> dtype = tf.float32 <NEW_LINE> var = self._variable_on_cpu( name, shape, tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)) <NEW_LINE> if wd is not None: <NEW_LINE> <INDENT> weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, na...
Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of ints stddev: standard deviation of a truncated Gaussian wd: add L2Loss weight ...
625941f3ac7a0e7691ed46b0
def _save_registration_params(self): <NEW_LINE> <INDENT> log('>>> save_registration_params') <NEW_LINE> with open(self._reg_file, 'w') as of: <NEW_LINE> <INDENT> json.dump(self._reg_params, of, indent=True, sort_keys=True)
Save registration parameters (app_id/token) to a local file
625941f3d58c6744b425824d
def _side_expander(prop_fmt: str) -> Callable: <NEW_LINE> <INDENT> def expand(self, prop, value: str) -> Generator[tuple[str, str], None, None]: <NEW_LINE> <INDENT> tokens = value.split() <NEW_LINE> try: <NEW_LINE> <INDENT> mapping = self.SIDE_SHORTHANDS[len(tokens)] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <IND...
Wrapper to expand shorthand property into top, right, bottom, left properties Parameters ---------- side : str The border side to expand into properties Returns ------- function: Return to call when a 'border(-{side}): {value}' string is encountered
625941f324f1403a92601151
def compile(self, session=None): <NEW_LINE> <INDENT> session = self.enquire_session(session) <NEW_LINE> if self.is_built_coherence(session.graph) is Build.NO: <NEW_LINE> <INDENT> with session.graph.as_default(): <NEW_LINE> <INDENT> self.build() <NEW_LINE> <DEDENT> <DEDENT> self.initialize(session, force=True)
Compile is two phase operation: at first it calls `build` method and then intializes the node for passed session. The policy around `session` is defined inside the `initialize` method. :param session: TensorFlow session used for initializing. If the node is built the session's graph value must be equal to the node...
625941f3d58c6744b425824e
def loadb(self, b: bytes, options: dict) -> Any: <NEW_LINE> <INDENT> if self.is_overrided('loads'): <NEW_LINE> <INDENT> return self.loads(bytes2str(b, options), options) <NEW_LINE> <DEDENT> if self.is_overrided('loadf'): <NEW_LINE> <INDENT> return self.loadf(BytesIO(b), options) <NEW_LINE> <DEDENT> raise NotImplemented...
load a obj from bytes.
625941f30c0af96317bb87d7
def test_lms_user_id_from_social_auth(self): <NEW_LINE> <INDENT> user = self.create_user() <NEW_LINE> self.assertIsNone(user.lms_user_id) <NEW_LINE> self.set_user_id_in_social_auth(user, 'test-social-auth-user-id') <NEW_LINE> self.assertEqual(user.lms_user_id, 'test-social-auth-user-id')
Ensures the lms_user_id can be pulled from the tracking context.
625941f3dd821e528d63b794
def add_loss(self, loss, name=None, regularization=False, add_summaries=True): <NEW_LINE> <INDENT> _ = name <NEW_LINE> if regularization: <NEW_LINE> <INDENT> self._g.add_to_collection(GraphKeys.REGULARIZATION_LOSSES, loss) <NEW_LINE> <DEDENT> tf.add_to_collection(GraphKeys.LOSSES, loss) <NEW_LINE> if add_summaries: <NE...
Append a loss to the total loss for the network. Args: loss: append this loss operation name: The name for this loss, defaults to loss.op.name regularization: Set to True if this is a regularization loss. add_summaries: Set to True if you want to see scalar and average summary.
625941f392d797404e30477d
def load_node(self, x, y, prevnode=None, message=None): <NEW_LINE> <INDENT> newnode = Node(x,y, prevnode, message) <NEW_LINE> self.graph.create_rectangle(x-50, y-20, x+50, y+20, fill='red') <NEW_LINE> if prevnode is not None : newnode.create_link(self.graph) <NEW_LINE> if message is not None : self.graph.create_text((x...
Load nodes from dict
625941f3004d5f362079a91f
def print_words(self): <NEW_LINE> <INDENT> self.mode = "history" <NEW_LINE> for h,s in self: <NEW_LINE> <INDENT> if s.is_final: <NEW_LINE> <INDENT> print(h)
Print all the words recognized by the automaton
625941f399cbb53fe67931d5
def accepted(self, n, v): <NEW_LINE> <INDENT> if self.n == n: <NEW_LINE> <INDENT> logging.warning('Accepted, set my v to %d', v) <NEW_LINE> self.v = v <NEW_LINE> return n, v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.warning('Can not accept n:%s, v:%s. My n: %s, my v: %s', n, v, self.n, self.v) <NEW_LINE> re...
Accept the n, v pair
625941f3fff4ab517eb2fa31
@register.inclusion_tag("snow/breadcrumb.html") <NEW_LINE> def breadcrumb(request): <NEW_LINE> <INDENT> return {"breadcrumb_list": request.breadcrumb_list}
:param request: :return:
625941f34428ac0f6e5bade8
def runproc(self): <NEW_LINE> <INDENT> exepath = None <NEW_LINE> if hasattr(sys, 'frozen'): <NEW_LINE> <INDENT> progdir = paths.get_prog_root() <NEW_LINE> exe = os.path.join(progdir, 'hg.exe') <NEW_LINE> if os.path.exists(exe): <NEW_LINE> <INDENT> exepath = exe <NEW_LINE> <DEDENT> <DEDENT> if not exepath: <NEW_LINE> <I...
Run mercurial command in separate process
625941f3de87d2750b86038a
def _changelog_format(self): <NEW_LINE> <INDENT> result = '' <NEW_LINE> if self.config.has_option("globalconfig", "changelog_format"): <NEW_LINE> <INDENT> result = self.config.get("globalconfig", "changelog_format") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with_email = '' <NEW_LINE> if (self.config.has_option("glo...
If you have set changelog_format in [globalconfig], it will return that string. Otherwise, return one of two defaults: - '%s (%ae)', if changelog_with_email is unset or evaluates to True - '%s', if changelog_with_email is set and evaluates to False
625941f3d53ae8145f87a854
def add_effect(self, effect): <NEW_LINE> <INDENT> if type(effect) not in self.player.effect_count: <NEW_LINE> <INDENT> self.player.effect_count[type(effect)] = 0 <NEW_LINE> <DEDENT> self.player.effect_count[type(effect)] += 1 <NEW_LINE> effect.set_target(self) <NEW_LINE> effect.apply() <NEW_LINE> if not isinstance(effe...
Applies the the given effect to the :class:`Character`. The effect will be unapplied in the case of silence, and will be applied to any copies that are made. :param MinionEffect effect: The effect to apply to this :class:`Character
625941f35fcc89381b1e1cb5
def get_bus_stops(file_name, encoding, delimiter): <NEW_LINE> <INDENT> with open(file_name, 'r', encoding=encoding) as file: <NEW_LINE> <INDENT> content = reader(file, delimiter=delimiter) <NEW_LINE> next(content) <NEW_LINE> result = sorted( set((float(line[3]), float(line[2])) for line in content)) <NEW_LINE> return r...
Получаем набор (широта, долгота) остановок (3 и 2 столбцы).
625941f30a50d4780f667487
def encrypt(message, recipients=None, **kwargs): <NEW_LINE> <INDENT> body = _flatten(message) <NEW_LINE> if recipients is None: <NEW_LINE> <INDENT> recipients = [email for name,email in _email_targets(message)] <NEW_LINE> _LOG.debug('extracted encryption recipients: {}'.format(recipients)) <NEW_LINE> <DEDENT> encrypted...
Encrypt a ``Message``, returning the encrypted version. multipart/encrypted +-> application/pgp-encrypted (control information) +-> application/octet-stream (body) >>> from pgp_mime.email import encodedMIMEText >>> message = encodedMIMEText('Hi\nBye') >>> message['To'] = 'pgp-mime-test <pgp-mime@invalid.com>' >>> ...
625941f3596a89723608a0a8
def __next__(self): <NEW_LINE> <INDENT> return next(self._csv_reader)
Return the next row in this CSV.
625941f34527f215b584ca42
def resolvent(X, s): <NEW_LINE> <INDENT> return 1.0 / s * eye_minus_inv(X / s)
The resolvent of a positive matrix, :math:`(sI - X)^{-1}`. For an elementwise positive matrix :math:`X` and a positive scalar :math:`s`, this atom computes .. math:: (sI - X)^{-1}, and it enforces the constraint that the spectral radius of :math:`X/s` is at most :math:`1`. This atom is log-log convex. Paramet...
625941f321bff66bcd684f3d
def work_as_manager(self) -> bool: <NEW_LINE> <INDENT> if self.restricted_ip: <NEW_LINE> <INDENT> self._report_action("IP_BLACKLISTED", "Work as manager is not allowed from restricted IP!") <NEW_LINE> return False <NEW_LINE> <DEDENT> self.update_citizen_info() <NEW_LINE> self.update_companies() <NEW_LINE> wam_holdings:...
Does Work as Manager in all holdings with wam. If employees assigned - work them also :return: if there is more wam work to do :rtype: bool
625941f39c8ee82313fbbd68
def __init__(self, in_skill_products=None, is_truncated=None, next_token=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.in_skill_products = in_skill_products <NEW_LINE> self.is_truncated = is_truncated <NEW_LINE> self.next_token = next_token
:param in_skill_products: List of In-Skill Products :type in_skill_products: (optional) list[ask_sdk_model.services.monetization.in_skill_product.InSkillProduct] :param is_truncated: :type is_truncated: (optional) bool :param next_token: :type next_token: (optional) str
625941f3c4546d3d9de7302a
def read_array(fp): <NEW_LINE> <INDENT> version = read_magic(fp) <NEW_LINE> if version != (1, 0): <NEW_LINE> <INDENT> msg = "only support version (1,0) of file format, not %r" <NEW_LINE> raise ValueError(msg % (version,)) <NEW_LINE> <DEDENT> shape, fortran_order, dtype = read_array_header_1_0(fp) <NEW_LINE> if len(shap...
Read an array from an NPY file. Parameters ---------- fp : file_like object If this is not a real file object, then this may take extra memory and time. Returns ------- array : ndarray The array from the data on disk. Raises ------ ValueError If the data is invalid.
625941f376e4537e8c351c69
def sym_gen(seq_lens): <NEW_LINE> <INDENT> source_seq_len, target_seq_len = seq_lens <NEW_LINE> (source_embed, source_embed_length, source_embed_seq_len) = self.embedding_source.encode(source, source_length, source_seq_len) <NEW_LINE> (target_embed, target_embed_length, target_embed_seq_len) = self.embedding_target.enc...
Returns a (grouped) loss symbol given source & target input lengths. Also returns data and label names for the BucketingModule.
625941f350485f2cf553d38c
def update_current_objects(frame1, frame2, pairs, old_objects, counter): <NEW_LINE> <INDENT> nobj = np.max(frame1) <NEW_LINE> id1 = np.arange(nobj) + 1 <NEW_LINE> uid = np.array([], dtype='str') <NEW_LINE> obs_num = np.array([], dtype='i') <NEW_LINE> origin = np.array([], dtype='str') <NEW_LINE> for obj in np.arange(no...
Removes dead objects, updates living objects, and assigns new uids to new-born objects.
625941f356ac1b37e62647b3
def test_options_europe_incorect_raise_error(self): <NEW_LINE> <INDENT> assert select_options('Europe') != ['some text', 'some text']
Test that function select_options is not returning something different than countries from Europe
625941f34a966d76dd551606
def __init__(self, src =u'||:', container=None): <NEW_LINE> <INDENT> RTRepeat.__init__(self, src, container)
>>> repeat = romanText.RTRepeatStart() >>> repeat <RTRepeatStart u'||:'>
625941f3090684286d50f2e1
def unitVector(self): <NEW_LINE> <INDENT> return QLineF
unitVector(self) -> QLineF
625941f31f037a2d8b9467ec
def main(): <NEW_LINE> <INDENT> iris_file = helper.get_data_dir() + os.sep + "iris.arff" <NEW_LINE> helper.print_info("Loading dataset: " + iris_file) <NEW_LINE> loader = Loader("weka.core.converters.ArffLoader") <NEW_LINE> iris_data = loader.load_file(iris_file) <NEW_LINE> iris_data.class_is_last() <NEW_LINE> helper.p...
Just runs some example code.
625941f34a966d76dd551607
@public.add <NEW_LINE> def green(path): <NEW_LINE> <INDENT> replace(["green"], path)
set green tag
625941f373bcbd0ca4b2c666
def vmdk_test_getFunc(self, get_func, param): <NEW_LINE> <INDENT> monolithicSparse_vmdk = self.get_monolithicSparse_vmdk() <NEW_LINE> monolithicFlat_vmdk = self.get_monolithicFlat_vmdk() <NEW_LINE> streamOptimized_vmdk = self.get_streamOptimized_vmdk() <NEW_LINE> with NamedTemporaryFile() as monolithicSparse, ...
Create temporary vmdk files and test a get function which returns a particular parameter of the files The string data of a vmdk file is defined in get_*_vmdk() :param get_func: get function to be tested :param param: parameter defined in 'summary' of get_*_vmdk(...)
625941f316aa5153ce362a6a
def _store_source_via_intermediate(self, linked_items, *args): <NEW_LINE> <INDENT> duplicate_source_count = 0 <NEW_LINE> if self['splitintermediates']: <NEW_LINE> <INDENT> for intermediate, targets in linked_items.items(): <NEW_LINE> <INDENT> self._store_row_with_intermediate({intermediate: targets}, *args) <NEW_LINE> ...
Stores row(s) for a source, linking targets via intermediates Args: linked_items (dict): Mapping of all intermediate IDs to the list of sets of target items per target Returns: int: Number of rows that have been added with a duplicate source ID
625941f3009cb60464c6399d
def precision_acc(y_true, y_pred): <NEW_LINE> <INDENT> true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) <NEW_LINE> predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) <NEW_LINE> precision = true_positives / (predicted_positives + K.epsilon()) <NEW_LINE> return precision
Calculates the precision, a metric for multi-label classification of how many selected items are relevant.
625941f34f88993c3716c651
def onetimewrapper(called, orig, *args, **kwargs): <NEW_LINE> <INDENT> if not called[0]: <NEW_LINE> <INDENT> called[0] = True <NEW_LINE> return orig(*args, **kwargs)
Wrapper to call orig function only once. This function is meant to be bound with called=[False], orig=func using functools.partial.
625941f37b25080760e39a46
def finish(self, rule, sample_name): <NEW_LINE> <INDENT> return self.log(rule, sample_name, "finished")
Helper method to simplify logging the finish of a rule.
625941f3fb3f5b602dac3c8b
def get_arch(self): <NEW_LINE> <INDENT> return self.database['arch']
Get the Target Architecture
625941f3a05bb46b383ece0c
def restore_database(dest_folder, database_name, super_user_pass, host, port): <NEW_LINE> <INDENT> logger.info("Restoring database %s", database_name) <NEW_LINE> dump_name = os.path.join(dest_folder, 'database_dump.b64') <NEW_LINE> logger.debug("Restore dump - reading file %s", dump_name) <NEW_LINE> with open(dump_name...
Restore database using Oerplib in Base64 format Args: dest_folder (str): Folder where the backup is stored database_name (str): The database name that will be created to restore the dump super_user_pass (str): Super user password of the instance host (str): Hostname or ip where the Odoo instance is run...
625941f3c4546d3d9de7302b
def update_spel(self, spel_pos, new_affinity): <NEW_LINE> <INDENT> new_affinity = int(round(new_affinity * DialCache.max_index)) <NEW_LINE> old_affinity = self.pointer_array[spel_pos] <NEW_LINE> if old_affinity == new_affinity: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.main_list[old_affinity].remove(spel_pos)...
Updates the affinity value assigned to spel_pos in our internal data structures :param spel_pos: 3-tuple (needs to be hashable) of the spel position pixel coordinates :param new_affinity: new affinity value value in the [0.0, 1.0] float range :return: None
625941f3d6c5a10208144640
@route() <NEW_LINE> @defer.inlineCallbacks <NEW_LINE> def prestige_exchange_status(p, req): <NEW_LINE> <INDENT> res_err = UNKNOWN_ERROR <NEW_LINE> cid, = req <NEW_LINE> user = g_UserMgr.getUser(cid) <NEW_LINE> if not user: <NEW_LINE> <INDENT> log.error('Can not find user. cid: {0}.'.format( cid )) <NEW_LINE> defer.retu...
@summary: 获取竞技场 声望兑换中玩家的状态信息
625941f36e29344779a62c02
def test_get_cached_css(self): <NEW_LINE> <INDENT> self.assertEquals(len(api.get_cached_css()), 1)
Test the "get cached css" api call should return a file name in a list
625941f38a43f66fc4b5464f
def err_band_sz2(self, orth=False, svar=False, repl=1000, signif=0.05, seed=None, burn=100, component=None): <NEW_LINE> <INDENT> model = self.model <NEW_LINE> periods = self.periods <NEW_LINE> irfs = self._choose_irfs(orth, svar) <NEW_LINE> neqs = self.neqs <NEW_LINE> irf_resim = model.irf_resim(orth=orth, repl=repl, s...
IRF Sims-Zha error band method 2. This method Does not assume symmetric error bands around mean. Parameters ---------- orth : bool, default False Compute orthogonalized impulse responses repl : int, default 1000 Number of MC replications signif : float (0 < signif < 1) Significance level for error bars, d...
625941f33317a56b8693a23a
def spin(self, cancel: bool=False): <NEW_LINE> <INDENT> self.send_goal() <NEW_LINE> if cancel: <NEW_LINE> <INDENT> self._timer = self.node.create_timer(1.0, self.send_cancel_request) <NEW_LINE> <DEDENT> rclpy.spin(self.node)
Common spin method for clients. Args: cancel: send a cancel request shortly after sending the goal request
625941f3cb5e8a47e48b8090
def addTwoNumbers(self, l1, l2): <NEW_LINE> <INDENT> carry = 0 <NEW_LINE> ret = ListNode(0) <NEW_LINE> nowNode = ret <NEW_LINE> while nowNode: <NEW_LINE> <INDENT> ss = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry <NEW_LINE> carry = ss // 10 <NEW_LINE> nowNode.val = ss % 10 <NEW_LINE> if l1: <NEW_LINE> <INDENT>...
:type l1: ListNode :type l2: ListNode :rtype: ListNode
625941f34428ac0f6e5bade9
def paginator(context, adjacent_pages=2): <NEW_LINE> <INDENT> startPage = max(context['page'] - adjacent_pages, 1) <NEW_LINE> if startPage <= 3: startPage = 1 <NEW_LINE> endPage = context['page'] + adjacent_pages + 1 <NEW_LINE> if endPage >= context['pages'] - 1: endPage = context['pages'] + 1 <NEW_LINE> page_numbers =...
To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view.
625941f3f8510a7c17cf9cf2
def look(self): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> pointing = [(el, az) for el, az in zip(np.around(self.elev.flatten(),1), np.around(self.azim.flatten(),1))] <NEW_LINE> return np.unique(pointing)
Find radar pointing directions during selected experiment Parameters ---------- None Returns ------- np.unique(pointing) : Radar pointing directions during selected experiment
625941f3009cb60464c6399e
def reset_database(host): <NEW_LINE> <INDENT> subprocess.check_call( ['fab', 'reset_database', '--host=%s' % (host,)], cwd=THIS_FOLDER )
Run fabric to reset the database
625941f33eb6a72ae02ecadf
def predict_loader(self, dset_loaders, dset_sizes, batch_size=16): <NEW_LINE> <INDENT> phase = 'val' <NEW_LINE> list_outputs = [] <NEW_LINE> list_labels = [] <NEW_LINE> with tqdm(total=int(dset_sizes[phase]/batch_size)) as pbar: <NEW_LINE> <INDENT> for i, data in enumerate(dset_loaders[phase]): <NEW_LINE> <INDENT> inpu...
Use for train/fit data with dataset loader instead of pair X, Y, including 2 phases Train and Validation
625941f310dbd63aa1bd3193
def _minutes_to_text(self, minutes): <NEW_LINE> <INDENT> seconds = int(float(minutes) * 60) <NEW_LINE> return self._seconds_to_text(seconds)
Convert a number of minutes, specified as a float, int, or string, to a pretty string.
625941f3a934411ee3751c86
def use_custom_value_and_error(self, value, error): <NEW_LINE> <INDENT> self.__settings[lit.MONTE_CARLO_STRATEGY] = lit.MC_CUSTOM <NEW_LINE> if not isinstance(value, Real): <NEW_LINE> <INDENT> raise TypeError("Cannot assign a {} to the value!".format(type(value).__name__)) <NEW_LINE> <DEDENT> if not isinstance(error, R...
Manually set the value and uncertainty for this quantity Sometimes when the distribution is not typical, and you wish to see for yourself what the best approach is to choose the center value and uncertainty for this quantity, use this method to manually set these values.
625941f33539df3088e2e93d
def share_to_qzone(self, openid, req): <NEW_LINE> <INDENT> return self.request(openid, self._ShareToQzoneUrl, req)
分享到QQ空间
625941f3236d856c2ad44dd4
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941f371ff763f4b549c88
def copyRandomFiles(currentdirectory, newdirectory, randomfiles): <NEW_LINE> <INDENT> import glob <NEW_LINE> import shutil <NEW_LINE> import random <NEW_LINE> dirExtention = currentdirectory + "/*.wav" <NEW_LINE> fileList = glob.glob(dirExtention) <NEW_LINE> randomNumbers = random.sample(xrange(len(fileList)), randomfi...
Function to copy a random selection of audio (.wav) files from one directory to another. currentdirectory is where the .wav file(s) are currently situated and must be defined in the form "C:\...\Folder name" newdirectory is where it is desired the .wav file(s) will be copied to. It can be defined in the same form as ...
625941f3377c676e91272798
def on_failsafe(self, func): <NEW_LINE> <INDENT> self._failsafe_func = func <NEW_LINE> return func
If no function matches the request, call this function to provide an automatic failsafe response.
625941f34c3428357757c915
def stop(self): <NEW_LINE> <INDENT> if self._stopped: <NEW_LINE> <INDENT> raise RuntimeError("Illegal state: sniffer already terminated") <NEW_LINE> <DEDENT> self._stopped = True
Provides ability to gracefully terminate the sniffer (makes sense if sniffer is running in the separate thread)
625941f391af0d3eaac9c00e
def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.Qvalue = util.Counter() <NEW_LINE> self.states = []
You can initialize Q-values here...
625941f3d7e4931a7ee9e511
def tostring(element, *args, **kwargs): <NEW_LINE> <INDENT> global modules <NEW_LINE> _bootstrap() <NEW_LINE> t = _get_type(element) <NEW_LINE> etree = modules.get(t, None) <NEW_LINE> if not etree: <NEW_LINE> <INDENT> raise RuntimeError('Unable to find the etree implementation related ' 'to %r (type %r)' % (element, t)...
Helper func to provide easy access to the (possibly) moving target that is C{ET}.
625941f3ec188e330fd5ad83
def build_stata(target, source, env): <NEW_LINE> <INDENT> source = misc.make_list_if_string(source) <NEW_LINE> target = misc.make_list_if_string(target) <NEW_LINE> start_time = misc.current_time() <NEW_LINE> source_file = str(source[0]) <NEW_LINE> misc.check_code_extension(source_file, '.do') <NEW_LINE> loc_lo...
Build targets with a Stata command This function executes a Stata script to build objects specified by target using the objects specified by source. Parameters ---------- target: string or list The target(s) of the SCons command. source: string or list The source(s) of the SCons command. The first source spe...
625941f33cc13d1c6d3c7968
def __init__(self): <NEW_LINE> <INDENT> self.platformName = "Thepiratebay" <NEW_LINE> self.tags = ["downloads", "torrents"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {}...
Constructor...
625941f3d10714528d6002dc
def _hide_dialog(self, sender=None, data=None): <NEW_LINE> <INDENT> self.export_dialog.hide() <NEW_LINE> return True
Hide dialog
625941f30383005118ecfbd2
def po_organisation_onaccept(form): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> organisation_id = form.vars["id"] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> db = current.db <NEW_LINE> s3db = current.s3db <NEW_LINE> otable = s3db.org_organisation <NEW_LINE> record = db(ota...
1. Set the owned_by_group to PO_ADMIN so that they can see these agencies in the household referrals dropdown 2. Create a po_referral_organisation record onaccept of an org_organisation to link it to this module. Args: form: the form
625941f397e22403b379d58d
def test_tuple_index(self): <NEW_LINE> <INDENT> self.interp("a_tuple = (5, 'a', 'x')") <NEW_LINE> self.istrue("a_tuple[0] == 5") <NEW_LINE> self.istrue("a_tuple[2] == 'x'")
tuple indexing
625941f35166f23b2e1a574b
def test_tmp_file(): <NEW_LINE> <INDENT> def write_data(file_handle): <NEW_LINE> <INDENT> file_handle.write("Hello world!") <NEW_LINE> <DEDENT> def write_data_with_args(file_handle, *args, **kwargs): <NEW_LINE> <INDENT> file_handle.write(str(args) + str(kwargs)) <NEW_LINE> <DEDENT> with pytest.raises(RuntimeError) as e...
Test TmpFile context manager behavior.
625941f3ad47b63b2c50a571
def chosen_area(location): <NEW_LINE> <INDENT> all_locations={"urias":"23.25/253.5/23.125/253.625", "terminos":"18.75/268.125/18.5/268.625", "pto.morelos":"21/273.125/20.875/273.25", "sta.ma.oro":"21.375/255.375/21.25/255.5" } <NEW_LINE> return str(all_locations[location])
Gives a string with the geographic coordenates of the chosen area
625941f363b5f9789fde76d8
def performIoUCalculation(ground_truth_annotation_dictionary, predicted_annotation_dictionary): <NEW_LINE> <INDENT> Image_IoU = {} <NEW_LINE> for ground_truth_key in ground_truth_annotation_dictionary: <NEW_LINE> <INDENT> print("Reading Image:", ground_truth_key) <NEW_LINE> if ground_truth_key in predicted_annotation_d...
Takes ground truth annotations and predicted annotations to create a dictionary of IoU scores Inputs: - ground_truth_annotation_dictionary: Dictionary of images and associated ground truth annotations - predicted_annotation_dictionary: Dictionary of images and predicted annotations Outputs: - Image_IoU: Dic...
625941f3187af65679ca5712
def __init__(self, label, datee): <NEW_LINE> <INDENT> self.label = label.upper() <NEW_LINE> self.datee = upcomming(datee) <NEW_LINE> self.dist = cal_dist(self.datee) <NEW_LINE> self.dist_months = cal_months(self.dist.days) <NEW_LINE> self.date_formated = d_format(self.datee) <NEW_LINE> self.day_of_week = day_of_week(se...
Individual Event information
625941f36aa9bd52df037399
def find_collisions(mylist, collision_set=None, normalized=False): <NEW_LINE> <INDENT> x1_index, y1_index, x2_index, y2_index, obj_index = range(5) <NEW_LINE> if collision_set is None: <NEW_LINE> <INDENT> collision_set = set() <NEW_LINE> <DEDENT> if not normalized: <NEW_LINE> <INDENT> mylist = normalize(mylist) <NEW_LI...
Assumes list of (x1, y1, x2, y2, obj) items Returns a set of all two-item collisions.
625941f37cff6e4e81117f77
def __init__(self, resX, resY, gx, gy): <NEW_LINE> <INDENT> self.sx = resX / gx <NEW_LINE> self.sy = resY / gy
Scale point u by factor s
625941f3b545ff76a8914407
def getSampleid(self, sd, interval): <NEW_LINE> <INDENT> id = self.getPrefix() + '_' + sd + '_' + str(interval) + 'M' <NEW_LINE> return id
Generate Unique sample ID - append prefix for subtypes :param sd: Subject ID :param row: row data with unique number :return: id
625941f3adb09d7d5db6cd7d
def testCircularUnshare(self): <NEW_LINE> <INDENT> UnshareOperation._UNSHARE_LIMIT = 3 <NEW_LINE> vp_id, ep_ids = self._tester.ShareNew(self._cookie2, [(self._new_ep_id, self._photo_ids)], [self._user3.user_id]) <NEW_LINE> self._tester.ShareExisting(self._cookie2, self._new_vp_id, [(ep_ids[0], self._photo_ids)]) <NEW_L...
Share both photos from originator to user2, then user2 back to the the originating viewpoint (but different episode), then unshare.
625941f3711fe17d8254294f
def __init__ (self, x, y, maxWidth, maxHeight): <NEW_LINE> <INDENT> gtk.Window.__init__ (self, gtk.WINDOW_POPUP) <NEW_LINE> self.__x = x <NEW_LINE> self.__y = y <NEW_LINE> self.__maxWidth = maxWidth <NEW_LINE> self.__maxHeight = maxHeight <NEW_LINE> self.__width = maxWidth <NEW_LINE> self.__height = maxHeight <NEW_LINE...
Initialize object
625941f3d268445f265b5461
def constructMaximumBinaryTree(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if len(nums) == 1: <NEW_LINE> <INDENT> return TreeNode(nums[0]) <NEW_LINE> <DEDENT> maxx = max(nums) <NEW_LINE> ind = nums.index(maxx) <NEW_LINE> res = TreeNode(maxx) <NEW_LINE> res.lef...
:type nums: List[int] :rtype: TreeNode
625941f3f9cc0f698b140be7
def read_schema(schema_path): <NEW_LINE> <INDENT> with open(schema_path) as f: <NEW_LINE> <INDENT> schema = avro.schema.Parse(f.read()) <NEW_LINE> <DEDENT> return schema
It will read the avro schema file and return the parsed schema
625941f382261d6c526aba9a
def test_login_fail(self): <NEW_LINE> <INDENT> response = self.login(identity='foo@bar.com') <NEW_LINE> assert_status_with_message(200, response, _('Identity or password is incorrect.'))
Login failure due to invalid login credentials.
625941f35510c4643540f9c6
def __run_thinning(img, inplace, cfun): <NEW_LINE> <INDENT> if not inplace: <NEW_LINE> <INDENT> img = img.copy() <NEW_LINE> <DEDENT> __check_image_grayscale_2d(img) <NEW_LINE> img = force_c_order_contiguous(img) <NEW_LINE> __check_image_min_wh(img, 3, 3) <NEW_LINE> __check_array_uint8(img) <NEW_LINE> height, width = im...
Internal common thinning function
625941f3d53ae8145f87a855
def playGame(wordList): <NEW_LINE> <INDENT> current_hand = {} <NEW_LINE> current_hand_len = 0 <NEW_LINE> first_hand_flag = False <NEW_LINE> while True: <NEW_LINE> <INDENT> choice = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: r") <NEW_LINE> if choice == 'n': <NEW_LINE> <INDENT> first_...
Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'e', immediately exit the game. * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again. 2) Asks the user to input a 'u' or a 'c'. * If the user inputs anything ...
625941f32eb69b55b151ceaa