code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def deprecated( key: str, replacement_key: Optional[str] = None, invalidation_version: Optional[str] = None, default: Optional[Any] = None, ) -> Callable[[Dict], Dict]: <NEW_LINE> <INDENT> module = inspect.getmodule(inspect.stack()[1][0]) <NEW_LINE> if module is not None: <NEW_LINE> <INDENT> module_name = module.__name... | Log key as deprecated and provide a replacement (if exists).
Expected behavior:
- Outputs the appropriate deprecation warning if key is detected
- Processes schema moving the value from key to replacement_key
- Processes schema changing nothing if only replacement_key provided
- No warning if only repl... | 625941d645492302aab5e505 |
def on_build(self, project, name): <NEW_LINE> <INDENT> pass | Handler called when a project including this job is built.
:param project: :class:`~azkaban.project.Project` instance
:param name: name corresponding to this job in the project.
The default implementation does nothing. | 625941d6a05bb46b383eca61 |
def parse_private_key(data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pka = asn1_parse(ASN1_RSAPrivateKey, data) <NEW_LINE> <DEDENT> except ASN1FormatError as e: <NEW_LINE> <INDENT> raise UnparsableKeyError('Unparsable private key: ' + str(e)) <NEW_LINE> <DEDENT> pk = { 'version': pka[0][0], 'modulus': pka[0][1], '... | Parse an RSA private key.
@param data: DER-encoded RFC3447 RSAPrivateKey.
@return: RSA private key | 625941d61b99ca400220acf1 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogify.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure... | Run administrative tasks. | 625941d6167d2b6e31218dd5 |
def colorize(labeled_trees): <NEW_LINE> <INDENT> for mle in sqtrees: <NEW_LINE> <INDENT> for nd in mle.postorder_node_iter(): <NEW_LINE> <INDENT> if nd.label == None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif float(nd.label) == 0: <NEW_LINE> <INDENT> nd.annotations.add_new(name = '!color', value = '#0000FF') <N... | Associate value ranges with colors. | 625941d69c8ee82313fbb9b5 |
def test_pitchtools_NamedPitch___cmp___05(): <NEW_LINE> <INDENT> pitch_1, pitch_2 = NamedPitch('fss', 4), NamedPitch('gff', 4) <NEW_LINE> assert not pitch_1 == pitch_2 <NEW_LINE> assert pitch_1 != pitch_2 <NEW_LINE> assert not pitch_1 > pitch_2 <NEW_LINE> assert not pitch_1 >= pitch_2 <NEW_LINE> assert pitch... | Pitches typographically crossed compare unequally.
| 625941d6b7558d58953c5151 |
def list_lib(self, repo): <NEW_LINE> <INDENT> if repo == "sbo": <NEW_LINE> <INDENT> if (os.path.isfile( self.meta.lib_path + "{0}_repo/SLACKBUILDS.TXT".format( repo))): <NEW_LINE> <INDENT> packages = Utils().read_file(self.meta.lib_path + "{0}_repo/" "SLACKBUILDS.TXT".format(repo)) <NEW_LINE> <DEDENT> <DEDENT> else: <N... | Return package lists
| 625941d65fc7496912cc3bbe |
def pudb_shell(_globals, _locals): <NEW_LINE> <INDENT> from pudb.shell import SetPropagatingDict <NEW_LINE> ns = SetPropagatingDict([_locals, _globals], _locals) <NEW_LINE> try: <NEW_LINE> <INDENT> import readline <NEW_LINE> import rlcompleter <NEW_LINE> HAVE_READLINE = True <NEW_LINE> <DEDENT> except ImportError: <NEW... | This example shell runs a classic Python shell. It is based on
run_classic_shell in pudb.shell. | 625941d626238365f5f0f0b1 |
def cap_reqs(self, use_membership=True): <NEW_LINE> <INDENT> twitchirc.log('debug', f'Sending CAP REQs. Membership: {use_membership}') <NEW_LINE> self.force_send(f'CAP REQ :twitch.tv/commands twitch.tv/tags' f'{" twitch.tv/membership" if use_membership else ""}\r\n') | Send CAP REQs.
:param use_membership: Send the membership capability.
:return: nothing. | 625941d6be8e80087fb20e80 |
def getMinFilterNum(self): <NEW_LINE> <INDENT> minFilter = self.gmechModel.minFilter.getInd(0)[0] <NEW_LINE> if minFilter is None: <NEW_LINE> <INDENT> raise RuntimeError("Minimum filter number unknown") <NEW_LINE> <DEDENT> return minFilter | Return the minimum filter number; raise RuntimeError if unavailable | 625941d6a79ad161976cc386 |
def update(self): <NEW_LINE> <INDENT> uptime_robot = UptimeRobot(self.api_key) <NEW_LINE> success, response = uptime_robot.get_monitors(response_times=1) <NEW_LINE> if success: <NEW_LINE> <INDENT> monitors = response.get('monitors') <NEW_LINE> self._log_unknown_monitors(monitors) <NEW_LINE> for monitor in monitors: <NE... | Update all monitors uptime and status.
| 625941d6cc40096d61595b90 |
def test_changeAllProjectVersions(self): <NEW_LINE> <INDENT> root = FilePath(self.mktemp()) <NEW_LINE> structure = { "README": "Hi this is 1.0.0.", "twisted": { "topfiles": { "README": "Hi this is 1.0.0"}, "_version.py": genVersion("twisted", 1, 0, 0) } } <NEW_LINE> self.createStructure(root, structure) <NEW_LINE> rele... | L{changeAllProjectVersions} changes the version numbers in the
_version.py
and README file. | 625941d699cbb53fe6792e26 |
def parse_user(self, response): <NEW_LINE> <INDENT> userItem = TweetUserItem() <NEW_LINE> selector = Selector(response) <NEW_LINE> verifiedAll = selector.xpath('body/div[@class="u"]/table//div[@class="ut"]') <NEW_LINE> verifiedSelector = verifiedAll.xpath('//img[@alt="V"]') <NEW_LINE> verifiedType = None <NEW_LINE> if ... | 抓取个人信息1 | 625941d6fb3f5b602dac38d5 |
def test_get_one_neighborhood(self): <NEW_LINE> <INDENT> for neighborhood in neighborhoods: <NEW_LINE> <INDENT> result, code = controller.get_one_neighborhood( neighborhood['id_neighborhood'] ) <NEW_LINE> self.assertEqual(code, 200) <NEW_LINE> self.assertEqual(result, neighborhood) <NEW_LINE> <DEDENT> result, code = co... | Testing get one neighborhood with or without statistics | 625941d62c8b7c6e89b35a00 |
def start_ssh(self, attempt=0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.end_ssh() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if self.parameters['hostname'] == "_FAKE_REDPITAYA_": <NEW_LINE> <INDENT> self.logger.warning("(Re-)starting client in dummy mode...") <NEW_LINE> self.star... | Extablishes an ssh connection to the RedPitaya board
returns True if a successful connection has been established | 625941d6460517430c3943c1 |
def get_piece_block(value): <NEW_LINE> <INDENT> if value < 0: <NEW_LINE> <INDENT> block = weechat.color(',default') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> block = weechat.color(',' + PIECE_COLOR[weetris['256colors']][value]) <NEW_LINE> <DEDENT> return block + ' ' | Return a string with a single block of a piece
(spaces with background color). | 625941d6a934411ee37518d4 |
def export_gene_assembly(assembly, outfile): <NEW_LINE> <INDENT> with open(outfile, 'w') as out: <NEW_LINE> <INDENT> json.dump(assembly, out, indent=4, cls=CustomEncoder) | Saves GeneAssembly object as JSON file
Args:
assembly (:obj:GeneAssembly): gene assembly
outfile (str): output file name | 625941d6a8ecb033257d330c |
def maxProduct(self, nums): <NEW_LINE> <INDENT> l = len(nums) <NEW_LINE> if not nums and l < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if l == 1: <NEW_LINE> <INDENT> return nums[0] <NEW_LINE> <DEDENT> pmax, nmax, maxi = [0], [0], nums[0] <NEW_LINE> for i in range(0, l): <NEW_LINE> <INDENT> n = nums[i] <NEW_LI... | :type nums: List[int]
:rtype: int | 625941d6c4546d3d9de72c75 |
def dugast_u(num_types, num_tokens): <NEW_LINE> <INDENT> return (math.log(num_tokens) ** 2) / (math.log(num_tokens) - math.log(num_types)) | Calculate Dugast’s U (1978, 1979).
Used formula:
.. math::
U = rac{\log{N^2}}{\log{N} \; - \; \log{V}}
Parameters:
num_types (int): Absolute number of types.
num_tokens (int): Absolute number of tokens. | 625941d66aa9bd52df036fe5 |
@app.route('/extract', methods=['GET', 'POST']) <NEW_LINE> def extract_face_from_image(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> print(request.get_json()) <NEW_LINE> r = requests.post(face_extractor_service_endpoint, data=request.get_json()) <NEW_LINE> return Response(stream_with_context(r... | Routes to internal service endpoint
:return: | 625941d6bd1bec0571d90870 |
def testcase(self,config_file,cat_number,*src): <NEW_LINE> <INDENT> d= view_validation_v2.DataValidation(config_file) <NEW_LINE> d.read_query_file() <NEW_LINE> d.fare_type() <NEW_LINE> d.prepare_dbquerys() <NEW_LINE> d.set_excel_writer() <NEW_LINE> d.execute_dbquerys() <NEW_LINE> d.tbl_restrns_date(*src) <NEW_LINE> d.v... | Method which takes filename, cat_number and restrictions source are applied | 625941d623849d37ff7b32ce |
def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(DimensionsForm, self).clean() <NEW_LINE> if "number_of_quantities" in cleaned_data and "number_of_values" in cleaned_data: <NEW_LINE> <INDENT> if cleaned_data["number_of_quantities"] == 0 or cleaned_data["number_of_values"] == 0: <NEW_LINE> <INDENT> cleaned_data... | If one of the two dimensions is set to zero, the other is set to
zero, too. | 625941d65f7d997b87174cd9 |
def import_paths(self, paths): <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> manifest = IIIFPresentation.from_file_or_url(path) <NEW_LINE> <DEDENT> except IIIFException as err: <NEW_LINE> <INDENT> self.error_msg(str(err)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if manifest.type == ... | Import a list of paths - file or url, collection or manifest. | 625941d6cc0a2c11143dd0d1 |
def try_split(val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return val.split('.') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return val | Just try to split, if we fail, return the original value. | 625941d61f5feb6acb0c4d8d |
def __eq__(self, other): <NEW_LINE> <INDENT> return (self.x, self.y) == (other.x, other.y) | Compare 2 vectors for equality | 625941d6442bda511e8be656 |
def state_to_str(state, num_blocks): <NEW_LINE> <INDENT> s = "" <NEW_LINE> for r in range(4): <NEW_LINE> <INDENT> for c in range(num_blocks): <NEW_LINE> <INDENT> s += "%02x "%state[r][c] <NEW_LINE> <DEDENT> s += "\n" <NEW_LINE> <DEDENT> return s | Convert a Rijndael state into a human readable
string for debugging | 625941d615fb5d323cde0d52 |
def _check_displacement_args(from_arg, to_arg, caller): <NEW_LINE> <INDENT> import numpy <NEW_LINE> if isinstance(from_arg, numpy.ndarray): <NEW_LINE> <INDENT> from_arg = (from_arg, ) <NEW_LINE> <DEDENT> elif not (nest.is_iterable(from_arg) and len(from_arg) > 0): <NEW_LINE> <INDENT> raise nest.NESTError("%s: from_arg ... | Internal helper function to check arguments to Displacement
and Distance and make them lists of equal length. | 625941d6956e5f7376d710ac |
def test_bool_field(): <NEW_LINE> <INDENT> pass | >>> a = BooleanField(name='bool', id='field_bool')
>>> print a.html('Test')
<input checked class="checkbox" id="field_bool" name="bool" type="checkbox"></input>
>>> print a.validate('on')
(True, True)
>>> print a.validate('')
(True, False)
>>> print a.validate(None)
(True, False) | 625941d685dfad0860c3b09c |
def make_splits(number): <NEW_LINE> <INDENT> n_pos = len(number) - 1 <NEW_LINE> for x in itertools.product((True, False), repeat=n_pos): <NEW_LINE> <INDENT> res = [number[0]] <NEW_LINE> for i in range(n_pos): <NEW_LINE> <INDENT> if x[i]: <NEW_LINE> <INDENT> res[-1] += number[i+1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Splits a number into possible concatenations of digits.
Example:
number = '123'
return: [['123'], ['1', '23'], ['12', '3'], ['1', '2', '3']] | 625941d630dc7b7665901ba5 |
def clear_queue(self, queue): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.pipe.delete(queue) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> raise exceptions.PipelineError(exc) | Clears a queue by removing (deleting) the key,
which is the same as an empty list in Redis | 625941d68a349b6b435e83b4 |
def test_sequence_alphabets(self): <NEW_LINE> <INDENT> for nucleotide_seq in test_seqs: <NEW_LINE> <INDENT> if "U" in str(nucleotide_seq).upper(): <NEW_LINE> <INDENT> self.assertNotIsInstance(nucleotide_seq.alphabet, Alphabet.DNAAlphabet) <NEW_LINE> <DEDENT> if "T" in str(nucleotide_seq).upper(): <NEW_LINE> <INDENT> se... | Sanity test on the test sequence alphabets.
See also enhancement bug 2597. | 625941d6796e427e537b0808 |
def check_or_assign_domain(self, domain, force=False): <NEW_LINE> <INDENT> if self.domain is None: <NEW_LINE> <INDENT> self.domain = domain <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert self.domain == domain or self.domain in domain.ancestors, "Inconsistency between the domains in which variabl... | Variables do not know their domain until a Function or a Relation assign one to them on the basis
of their domain. | 625941d6c432627299f04e88 |
def test_from_temba__existing(self): <NEW_LINE> <INDENT> org = factories.Org() <NEW_LINE> poll = factories.Poll( org=org, flow_uuid='abc', rapidpro_name='old', name='custom', is_active=True) <NEW_LINE> flow = factories.TembaFlow(uuid='abc', name='new') <NEW_LINE> updated = Poll.objects.from_temba(org, flow) <NEW_LINE> ... | Fields on an existing Poll should be updated from RapidPro. | 625941d6adb09d7d5db6c9cf |
def test_scrubber_delete_handles_exception(self): <NEW_LINE> <INDENT> self.cleanup() <NEW_LINE> self.start_servers(delayed_delete=True, daemon=False, default_store='file') <NEW_LINE> self.assertEqual(self.api_server.default_store, 'file') <NEW_LINE> headers = { 'x-image-meta-name': 'test_image', 'x-image-meta-is_public... | Test that the scrubber handles the case where an
exception occurs when _delete() is called. The scrubber
should not write out queue files in this case. | 625941d6bde94217f3683030 |
@app.route('/users/log-out') <NEW_LINE> def log_out(): <NEW_LINE> <INDENT> del session['userid'] <NEW_LINE> flash("Logged out.") <NEW_LINE> return redirect('/') | Log user out | 625941d66fece00bbac2d981 |
def deleteAtIndex(self, index: int) -> None: <NEW_LINE> <INDENT> if 0 <= index <= len(self.linked_list) - 1: <NEW_LINE> <INDENT> return self.linked_list.pop(index) | Delete the index-th node in the linked list, if the index is valid. | 625941d64a966d76dd551251 |
def _jupyter_nbextension_paths(): <NEW_LINE> <INDENT> return [{ 'section': 'notebook', 'src': 'static', 'dest': 'ziviz', 'require': 'ziviz/extension' }] | Called by Jupyter Notebook Server to detect if it is a valid nbextension and
to install the widget
Returns
=======
section: The section of the Jupyter Notebook Server to change.
Must be 'notebook' for widget extensions
src: Source directory name to copy files from. Webpack outputs generated files
into this dir... | 625941d6d10714528d5fff26 |
def callback_localization(self, data): <NEW_LINE> <INDENT> self.acceleration = data.pose.linear_acceleration_vrf.y <NEW_LINE> self.localization_received = True | New Localization | 625941d64428ac0f6e5baa34 |
def update_ca_bundle(target=None, source=None, merge_files=None): <NEW_LINE> <INDENT> if target is None: <NEW_LINE> <INDENT> target = __salt__['config.get']('ca_bundle', None) <NEW_LINE> <DEDENT> if source is None: <NEW_LINE> <INDENT> source = __salt__['config.get']('ca_bundle_url', None) <NEW_LINE> <DEDENT> return sal... | Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*' http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it ... | 625941d6cdde0d52a9e53275 |
def mail_on_status_changed(event): <NEW_LINE> <INDENT> logger.info(u"+ StatusChanged : Mail alert") <NEW_LINE> if event.node.type_ == 'expensesheet': <NEW_LINE> <INDENT> wrapper = ExpenseMailStatusChangedWrapper(event) <NEW_LINE> <DEDENT> elif event.node_type in ('invoice', 'estimation', 'cancelinvoice'): <NEW_LINE> <I... | Dispatch the event, wrap it with a node specific wrapper and the send email
from it | 625941d6167d2b6e31218dd6 |
def _HandlePluginGPlus( self, input_line, plugin_id, params, output_stream): <NEW_LINE> <INDENT> filtered_params = {} <NEW_LINE> for name, value in params.items(): <NEW_LINE> <INDENT> if name in self._PLUSONE_ARGS: <NEW_LINE> <INDENT> filtered_params[name] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._war... | Handle a plugin tag for +1 button.
Args:
input_line: Current line number being processed.
plugin_id: The plugin ID.
params: The plugin params.
output_stream: Output Markdown file. | 625941d66e29344779a62851 |
def grid_neighbors( height, width ): <NEW_LINE> <INDENT> def func( coord ): <NEW_LINE> <INDENT> neighbor_list = [ ( coord[ 0 ], coord[ 1 ] + 1), ( coord[ 0 ], coord[ 1 ] - 1), ( coord[ 0 ] + 1, coord[ 1 ]), ( coord[ 0 ] - 1, coord[ 1 ])] <NEW_LINE> return [ c for c in neighbor_list if c != coord and c[0] >= 0 and c[0] ... | Calculate neighbors for a simple grid where
a movement can be made up, down, left, or right.
Arguments:
height - The height of the grid
width - The width of the grid
>>> neighbor = grid_neighbors( 10, 10 )
>>> neighbor( (0,0) )
[(0, 1), (1, 0)]
>>> neighbor( (1,1) )
[(1, 2), (1, 0), (2, 1), (0, 1)] | 625941d65166f23b2e1a539a |
def fit(self, train_env: PLEEnv, valid_env: PLEEnv): <NEW_LINE> <INDENT> pass | Fake training method
(just here for illustration purposes)
Parameters
----------
train_env : [type]
Environment used for training.
valid_env : [type]
Environment used for validation. | 625941d615fb5d323cde0d53 |
def get_queue_caller(self, queue_id, uuid): <NEW_LINE> <INDENT> callers = self._get_callers_namespace(queue_id=queue_id) <NEW_LINE> name = '%s:%s' % (callers, uuid) <NEW_LINE> res = self._session.hgetall(name) <NEW_LINE> try: <NEW_LINE> <INDENT> name = self._get_queue_namespace(queue_id=queue_id) <NEW_LINE> key = '%s:%... | Retrieve information about the given queue caller. | 625941d667a9b606de4a80f9 |
def getFlatPrice(self,payAtDoor=False): <NEW_LINE> <INDENT> if self.discountType is not DiscountCombo.DiscountType.flatPrice: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if payAtDoor: <NEW_LINE> <INDENT> return self.doorPrice <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.onlinePrice | Rather than embedding logic re: door pricing,
other code can call this method. | 625941d66fb2d068a760f2e1 |
def pack(self): <NEW_LINE> <INDENT> return (self._name, self._path, self._page, self._numpages, self._archive_type, self._date_added.timestamp()) | Return a tuple suitable for pickling. The bookmark can be fully
re-created using the values in the tuple. | 625941d626068e7796caef23 |
@pytest.mark.parametrize('func', [ Rule.get_rules_files, Rule.get_rules ]) <NEW_LINE> @pytest.mark.parametrize('status', [ None, 'all', 'enabled', 'disabled', 'random' ]) <NEW_LINE> @patch('wazuh.rule.glob', side_effect=rules_files) <NEW_LINE> @patch('wazuh.configuration.get_ossec_conf', return_value=rule_ossec_conf) <... | Tests getting rules using status filter | 625941d63346ee7daa2b2fad |
def Sdef(M0, M1, alpha): <NEW_LINE> <INDENT> return (1-alpha) * M0 + alpha * M1 | :math:`S(\alpha)`, as defined in the paper.
Parameters
----------
M0 : ndarray or matrix
A symmetric indefinite matrix to be shrunk.
M1 : ndarray or matrix
A positive definite target matrix.
alpha : float
A shrinking parameter.
Returns
-------
S(alpha) : float
The convex combination :math:`(1-\alpha) ... | 625941d650485f2cf553cfdb |
def add_prediction_op(self): <NEW_LINE> <INDENT> x = self.add_embedding() <NEW_LINE> dropout_rate = self.dropout_placeholder <NEW_LINE> cfg = self.config <NEW_LINE> initializer = tf.contrib.layers.xavier_initializer(); <NEW_LINE> W = tf.get_variable('W',shape=[cfg.n_window_features*cfg.embed_size,cfg.hidden_size],dtype... | Adds the 1-hidden-layer NN:
h = Relu(xW + b1)
h_drop = Dropout(h, dropout_rate)
pred = h_dropU + b2
Recall that we are not applying a softmax to pred. The softmax will instead be done in
the add_loss_op function, which improves efficiency because we can use
tf.nn.softmax_cross_entropy_with_logits
When cre... | 625941d66e29344779a62852 |
def shell(snippet, cwd=None, env=None): <NEW_LINE> <INDENT> out = [] <NEW_LINE> pid = Popen('%s 2>/dev/null' % snippet, close_fds=True, shell=True, stdout=PIPE, stderr=None, cwd=cwd, env=env) <NEW_LINE> while True: <NEW_LINE> <INDENT> code = pid.poll() <NEW_LINE> line = pid.stdout.readline() <NEW_LINE> if not line and ... | Helper invoking a shell command and returning its stdout broken down by lines as a list. The sub-process
exit code is also returned. Please note we only pipe stdout (stderr being redirected to /dev/null).
:type snippet: str
:param snippet: shell snippet, e.g "echo foo > /bar"
:type env: dict
:param env: optional envir... | 625941d6283ffb24f3c55b40 |
def get_voted_prediction(list_of_votes, xi): <NEW_LINE> <INDENT> voted_prediction = 0 <NEW_LINE> for m in range(len(list_of_votes[0])): <NEW_LINE> <INDENT> sign_prediction = get_sign_of_prediction(list_of_votes[0][m], xi) <NEW_LINE> correct_prediction_count = list_of_votes[1][m] <NEW_LINE> voted_prediction += correct_p... | Returns a prediction by using a weighted vote of every single hypothesized unit vector separating hyperplane.
:param list_of_votes: Contains:
[0] = all hypothesized unit vector separating hyperplanes
[1] = count of correct prediction for mth separating hyperplane
:param xi: i... | 625941d6d99f1b3c44c677cd |
def import_model(file_name: str): <NEW_LINE> <INDENT> model_object = exportCDSBML.export_CDSBML(file_name) <NEW_LINE> return model_object | imports the python model that has been generated from CD SBML | 625941d6d18da76e23532719 |
def load(self, path, ltype=1): <NEW_LINE> <INDENT> prefix = '' <NEW_LINE> if ltype == 0: <NEW_LINE> <INDENT> prefix = 'backbone.' <NEW_LINE> pretrained_dict = torch.load(path)['state_dict'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pretrained_dict = torch.load(path) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> prin... | @params path 参数模型位置
@ltype 0 读取预训练模型
1 读取参数模型 | 625941d6d4950a0f3b08c58e |
def pickup(object_name, arm_name, pick_pose, place_pose): <NEW_LINE> <INDENT> print("sending pickup") <NEW_LINE> rospy.wait_for_service('pick_place_routine') <NEW_LINE> try: <NEW_LINE> <INDENT> pick_place_routine = rospy.ServiceProxy('pick_place_routine', PickPlace) <NEW_LINE> resp = pick_place_routine(current_scene_nu... | Send a pickup request to the pick_place_routine service.
| 625941d691af0d3eaac9bc5c |
def p_lambda_expression(self, args): <NEW_LINE> <INDENT> return ast.Lambda(args[2], args[3]) | lambda_expression ::= ( __lambda__ formals body ) | 625941d6711fe17d825425aa |
def tokenize(text): <NEW_LINE> <INDENT> tokens = word_tokenize(text) <NEW_LINE> lemmatizer = WordNetLemmatizer() <NEW_LINE> clean_tokens = [] <NEW_LINE> for tok in tokens: <NEW_LINE> <INDENT> clean_tok = lemmatizer.lemmatize(tok).lower().strip() <NEW_LINE> clean_tokens.append(clean_tok) <NEW_LINE> <DEDENT> return clean... | This function case normalizes, tokenizes and lemmatizes a text
INPUT
text - string that needs processing
OUTPUT
clean_tokens - list of cleaned tokens | 625941d6d6c5a1020814428d |
def sendDroneState(self, drone_id): <NEW_LINE> <INDENT> if self.droneStates[drone_id]: <NEW_LINE> <INDENT> lastState = self.droneStates[drone_id][-1] <NEW_LINE> self.writeToServer({ 'type': 'drone_state', 'drone_state': { 'drone_id': lastState['drone_id'], 'longitude': lastState['longitude'], 'latitude': lastState['lat... | Important method. Send drone state to main server every DRONE_UPDATE_INTERVAL seconds.
We call reactor reactor.callLater() to recall the method on the set interval. | 625941d6cb5e8a47e48b7ce9 |
def gridder_to_C(gridder, R): <NEW_LINE> <INDENT> M = len(gridder) // (2 * R) <NEW_LINE> C = np.zeros((2 * R, M), dtype=float) <NEW_LINE> for r in range(0, 2 * R): <NEW_LINE> <INDENT> l = r - R + 1 <NEW_LINE> indx = np.arange(M) - 2 * M * l <NEW_LINE> indx[indx<0] = -indx[indx<0] - 1 <NEW_LINE> C[r, :] = gridder[indx] ... | Reformat gridder evaluated on the nu grid returned by make_evaluation_grids into the sampled C function
which has an index for the closest gridpoint and an index for the fractional distance from that gridpoint | 625941d63cc13d1c6d3c75bb |
def unfold(self): <NEW_LINE> <INDENT> return (self.request, self.response, self.session) | Unfolds the state object into a request, response and session.
| 625941d6a4f1c619b28b0277 |
def finalize(self, raise_warning=True): <NEW_LINE> <INDENT> return self._finalize(raise_warning, compile_only=False) | Constructs the SNodeTree and finalizes this builder.
Args:
raise_warning (bool): Raise warning or not. | 625941d6b830903b967e9b4b |
def authenticate(cls, auth_url=auth_url()): <NEW_LINE> <INDENT> return cls._v2_auth(auth_url) | Authenticate against the HP Cloud auth service. | 625941d6462c4b4f79d1d911 |
def __init__(self): <NEW_LINE> <INDENT> Datn.__init__(self) <NEW_LINE> self._epre = self.__preset_conf() | Handling common process | 625941d65fc7496912cc3bbf |
def test_increases_count(preambled_worker, raw_data_without_pump, raw_data_with_pump): <NEW_LINE> <INDENT> initial_count = preambled_worker.count <NEW_LINE> preambled_worker.compute_signals(raw_data_with_pump) <NEW_LINE> preambled_worker.compute_signals(raw_data_without_pump) <NEW_LINE> assert preambled_worker.count ==... | Ensure that the measurement count increases with a full set of data.
| 625941d6091ae3566866719d |
def register(): <NEW_LINE> <INDENT> bpy.types.NodeSocket.to_socket_id = to_socket_id <NEW_LINE> bpy.types.NodeSocket.get_node_tree = get_node_tree <NEW_LINE> bpy.types.NodeSocket.get_socket_index = get_socket_index <NEW_LINE> bpy.types.NodeSocket.is_mtlx_node_socket = BoolProperty( default = False, get = is_mtlx_node_s... | Blender's register. Extends bpy.types classes with new properties and funcs. | 625941d6cad5886f8bd2721a |
def test_validate_params_extra_chars_instruction(monkeypatch): <NEW_LINE> <INDENT> import itertools <NEW_LINE> prefixes = ["BTO", "STC", "B", "C", "S", "T", "/"] <NEW_LINE> extra_char_prefix = ["".join(x) for x in itertools.permutations(prefixes, 2)] <NEW_LINE> for prefix in extra_char_prefix: <NEW_LINE> <INDENT> monke... | Permutation of BTO and STC with an extra character return False | 625941d64e696a04525c968d |
def test_is_sobol_saltelli_consistent_in_k(self): <NEW_LINE> <INDENT> dm_dict = sobol_saltelli.create(self.n, self.k, "srs", self.params_seed) <NEW_LINE> for key in dm_dict: <NEW_LINE> <INDENT> self.assertEqual(dm_dict[key].shape[1], self.k) <NEW_LINE> <DEDENT> dm_dict = sobol_saltelli.create(self.n, self.k, "lhs", sel... | Is the matrix in the Sobol'-Saltelli design each has n columns? | 625941d6d268445f265b50b0 |
def translate_ordinals(text): <NEW_LINE> <INDENT> for key, rep in ordinal_trans.items(): <NEW_LINE> <INDENT> text = re.sub(" {0}".format(key), " {0}".format(rep), text) <NEW_LINE> text = re.sub("^{0} ".format(key), "{0} ".format(rep), text) <NEW_LINE> text = re.sub(" {0}$".format(key), " {0}".format(rep), text) <NEW_LI... | Translate ordinal digit strings up two twelve(fth) | 625941d621bff66bcd684b92 |
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: <NEW_LINE> <INDENT> pass | put solution here | 625941d666656f66f7cbc3ed |
def initialize_flux(N): <NEW_LINE> <INDENT> return np.ones(N) | A function that produces an initial flux guess. | 625941d67cff6e4e81117bc7 |
def load_ipython_extension(ip): <NEW_LINE> <INDENT> ip.register_magics(HelloWorldMagics) | Load the extension in IPython. | 625941d6d8ef3951e324377f |
def parse_helix_ids(self, value): <NEW_LINE> <INDENT> pattern = re.compile(r"[,\[\]]") <NEW_LINE> tokens = pattern.split(value) <NEW_LINE> helix_ids = [] <NEW_LINE> for s in tokens: <NEW_LINE> <INDENT> if "-" in s: <NEW_LINE> <INDENT> ids = self.parse_id_range(s) <NEW_LINE> for id in ids: <NEW_LINE> <INDENT> helix_ids.... | Parse a list of helix IDs. | 625941d6442bda511e8be657 |
def __init__(self, xknx, name, group_address_temperature=None, group_address_target_temperature=None, group_address_target_temperature_state=None, group_address_setpoint_shift=None, group_address_setpoint_shift_state=None, setpoint_shift_step=DEFAULT_SETPOINT_SHIFT_STEP, setpoint_shift_max=DEFAULT_SETPOINT_SHIFT_MAX, s... | Initialize Climate class. | 625941d6e5267d203edcdedc |
def _add_objective(roi_name, obj_type, is_constraint=False, plan=None, plan_opt=0): <NEW_LINE> <INDENT> if plan is None: <NEW_LINE> <INDENT> plan = lib.get_current_plan() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with CompositeAction('Add Optimization Function'): <NEW_LINE> <INDENT> retval_1 = plan.PlanOptimizations... | Private function used to add an optimization objective.
Args:
roi_name (str): the name of the ROI for which to add the optimization objective
obj_type (str): the type of the optimization objective
is_constraint (bool): whether or not the objective is a constraint
plan (RayStation plan object, optional)... | 625941d60a366e3fb873ea5d |
def on_event(self, kind, event): <NEW_LINE> <INDENT> pass | Called before any of the event callbacks. | 625941d6ab23a570cc2503c5 |
def test_join_team_with_an_email_not_registered(self): <NEW_LINE> <INDENT> response = self.request_join_team(email='paul@notregistered.com') <NEW_LINE> self.assertEqual(response.status_code, 403) | Tests the permission denied when an user tries to join a team with
an email not registered in his/her account | 625941d6925a0f43d254a0ba |
def first_notes_and_song(): <NEW_LINE> <INDENT> time.sleep(2) <NEW_LINE> port = 'sim' <NEW_LINE> hal = new_create.Create(port) <NEW_LINE> hal.toSafeMode() <NEW_LINE> hal.playNote(31, 255) <NEW_LINE> time.sleep(5.0) <NEW_LINE> hal.playNote(110, 1) <NEW_LINE> time.sleep(1.0) <NEW_LINE> song = [(60, 8), (64, 8), (67, 8), ... | Demonstrates the playNote and playSong methods. | 625941d68c3a8732951585fd |
def do_POST(self, *args): <NEW_LINE> <INDENT> message, response = RequestEventManager.callEvent(self.path, method="POST") <NEW_LINE> self.send_response(response) <NEW_LINE> self.send_header('Content-type','text/html') <NEW_LINE> self.end_headers() <NEW_LINE> self.wfile.write(bytes(message, "utf8")) | Handles POST requests | 625941d682261d6c526ab6e3 |
def updateFieldCache(self, nids): <NEW_LINE> <INDENT> snids = ids2str(nids) <NEW_LINE> r = [] <NEW_LINE> for (nid, mid, flds) in self._fieldData(snids): <NEW_LINE> <INDENT> fields = splitFields(flds) <NEW_LINE> model = self.models.get(mid) <NEW_LINE> r.append((stripHTML(fields[self.models.sortIdx(model)]), fieldChecksu... | Update field checksums and sort cache, after find&replace, etc. | 625941d6cdde0d52a9e53276 |
def save_one_to_mong_day(self,sid,start,end): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> day_bar=self.get_day_in_tushare(sid,start,end) <NEW_LINE> if day_bar.shape[0]!=0: <NEW_LINE> <INDENT> day_bar_mongo=json.loads(day_bar.T.to_json()).values() <NEW_LINE> self.col.insert_many(day_bar_mongo) <NEW_LINE> logger.info('s... | 保存一只股票的日线数据到mongodb | 625941d6a934411ee37518d5 |
def __init__(self, days_ahead, *args, **kwargs): <NEW_LINE> <INDENT> super (SpecialityChooseForm, self ).__init__(*args, **kwargs) <NEW_LINE> start_date = datetime.date.today() <NEW_LINE> end_date = start_date + datetime.timedelta(days=days_ahead) <NEW_LINE> doctor_id_list = Schedule.objects.filter( vdate__range=(start... | Переопределение метода: отображение специальностей только свободных
докторов на заданное время вперёд | 625941d6d164cc6175782f90 |
def test_triggerGroupCacherUpdate(self): <NEW_LINE> <INDENT> self.calledArgs = None <NEW_LINE> def killMethod(pid, sig): <NEW_LINE> <INDENT> self.calledArgs = (pid, sig) <NEW_LINE> <DEDENT> class StubConfig(object): <NEW_LINE> <INDENT> def __init__(self, runRootPath): <NEW_LINE> <INDENT> self.RunRoot = runRootPath <NEW... | Verify triggerGroupCacherUpdate can read a pidfile and send a SIGHUP | 625941d667a9b606de4a80fa |
def generate_y_dict(sample_dictionary, gene, tissue, y_base='data/Y/'): <NEW_LINE> <INDENT> y_files = os.listdir(y_base) <NEW_LINE> y_files = [y for y in y_files if y != '.empty'] <NEW_LINE> y_dict = {} <NEW_LINE> for tis in sample_dictionary.keys(): <NEW_LINE> <INDENT> if tis in tissue: <NEW_LINE> <INDENT> y_file = [y... | Generates a dictionary of tissue specific y vectors
Arguments:
:param sample_dictionary: tissues as keys and values are sample IDs
:param gene: the focus of the y vector of labels
:param tissue: a list of tissues to use to generate y_dict
:param y_base: where the Y matrices are stored
Output:
Dictionary with tissues ... | 625941d68e05c05ec3eea5b8 |
def __init__(self, shape=None, reward_type="score", episodic=False, deterministic=False, initial_state=None): <NEW_LINE> <INDENT> if initial_state is None: <NEW_LINE> <INDENT> self._initial_state = None <NEW_LINE> shape = tuple(shape if shape is not None else (4, 4)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._... | Initializes a new `TwentyFortyEight` game.
Args:
shape: Optional custom 2D shape of the game board. Defaults to `(4, 4)`.
If `initial_state` is supplied, the value of `shape` will be overridden
to match.
reward_type: One of "score" (default), "max", or "win_loss". "score" gives
the difference in the re... | 625941d6a05bb46b383eca62 |
def main(): <NEW_LINE> <INDENT> fp = open('random.txt','a') <NEW_LINE> name = 'random_v1.00' <NEW_LINE> usage = '模拟投掷骰子,并输出相应的点数' <NEW_LINE> now = datetime.now() <NEW_LINE> print('\n \n 当前操作的程序是:{} \n'.format(name), '', end='', file=fp) <NEW_LINE> print('该程序的功能为:{} \n'.format(usage), '', end='', file=fp) <NEW_LINE> pri... | 主函数 | 625941d6dd821e528d63b3ea |
def test_api_can_edit_non_existing_item(self): <NEW_LINE> <INDENT> item = {'name': 'sugar'} <NEW_LINE> self.test_shoppinglist() <NEW_LINE> res2 = self.client().put("/shoppinglists/1/items/1", headers=dict( Authorization="Bearer " + self.access_token), data=item) <NEW_LINE> self.assertIn("No such item", str(res2.data)) | Test API can edit a non existing item | 625941d629b78933be1e58eb |
def sum_nested_data(nested_data, *skip_keys): <NEW_LINE> <INDENT> summed_data = {} <NEW_LINE> def _sum(nested_data): <NEW_LINE> <INDENT> for k, v in nested_data.items(): <NEW_LINE> <INDENT> if not skip_keys or k not in skip_keys: <NEW_LINE> <INDENT> if _is_num(v): <NEW_LINE> <INDENT> summed_data[k] = summed_data.get(k,... | Sums nested data, grouped by innermost keys
args
- nested_data -- dict or array of dicts containing nested numerical
data; can be of any depth, and can contain scalars or arrays
- skip_keys -- keys to skip, effectively ignoring | 625941d601c39578d7e7507d |
def test_working_directory_already_exist(self, init_pwd): <NEW_LINE> <INDENT> sys.argv = [sys.argv[0]] <NEW_LINE> sys.argv.append('--clear') <NEW_LINE> sys.argv.extend(['--log-level', 'DEBUG']) <NEW_LINE> sys.argv.extend(['--profile', init_pwd + 'default.prof']) <NEW_LINE> sys.argv.extend(['--source', init_pwd + 'sourc... | Test where the working directory for the given program already exists, so we need to assign
a new timestamp. | 625941d6e8904600ed9f2171 |
def update_data_iuf(train_matrix): <NEW_LINE> <INDENT> iuf_map = {} <NEW_LINE> num_row = len(train_matrix) <NEW_LINE> num_col = len(train_matrix[0]) <NEW_LINE> for c_idx in range(num_col): <NEW_LINE> <INDENT> iuf = 0.0 <NEW_LINE> movie_id = c_idx + 1 <NEW_LINE> total_num_of_users = num_row <NEW_LINE> lst_rate = [] <NEW... | calculate the train matrix with iuf
:param train_matrix: python 2-d array
:return: void | 625941d61b99ca400220acf4 |
def copy_with_prompts_callback(self, event=None): <NEW_LINE> <INDENT> text = self.text <NEW_LINE> selection_indexes = ( self.text.index("sel.first linestart"), self.text.index("sel.last +1line linestart"), ) <NEW_LINE> if selection_indexes[0] is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> selected_text = self.... | Copy selected lines to the clipboard, with prompts.
This makes the copied text useful for doc-tests and interactive
shell code examples.
This always copies entire lines, even if only part of the first
and/or last lines is selected. | 625941d6d6c5a1020814428e |
def add_folder(self, folder, parent_folder='[Top Level]'): <NEW_LINE> <INDENT> url = "reader/add_folder" <NEW_LINE> payload = {"folder": folder, "parent_folder": parent_folder} <NEW_LINE> results = self._nb_post(url, payload=payload) <NEW_LINE> return results | Add a new folder. | 625941d697e22403b379d1dd |
def add_data(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self.specviz._widget.add_data(data) <NEW_LINE> self._flux_unit_controller.set_data(data) <NEW_LINE> for checkbox in self._synced_checkboxes: <NEW_LINE> <INDENT> checkbox.setEnabled(True) <NEW_LINE> <DEDENT> self._has_data = True <NEW_LINE> self.... | Called by a function outside the class in order to add data to cubeviz.
:param data:
:return: | 625941d60383005118ecf824 |
def get_message_author_name(self, message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info = self._slack.users.info(message.get('user')) <NEW_LINE> found = info.body.get('user').get('name') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> found = None <NEW_LINE> <DEDENT> return found | gets the author of a message
:type message: message
:param message: the Object representing the message | 625941d6dc8b845886cb5778 |
def getAction(self, gameState): <NEW_LINE> <INDENT> agentCount = gameState.getNumAgents() <NEW_LINE> def multiminimax(state, depth, agentIndex): <NEW_LINE> <INDENT> legalActions = state.getLegalActions(agentIndex) <NEW_LINE> if depth == 0 or len(legalActions) == 0: <NEW_LINE> <INDENT> return (None, self.evaluationFunct... | Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.g... | 625941d6be8e80087fb20e82 |
def splits2tree(splits, rooted=False): <NEW_LINE> <INDENT> tree = treelib1.Tree() <NEW_LINE> for split in splits: <NEW_LINE> <INDENT> _add_split_to_tree(tree, split, 1.0, rooted) <NEW_LINE> <DEDENT> _post_process_split_tree(tree) <NEW_LINE> return tree | Builds a tree from a set of splits
Silently reject splits that are in conflict. Process splits in order.
splits -- iterable of splits
rooted -- if True treat splits as rooted/polarized | 625941d650812a4eaa59c562 |
def add_mysterious_meat(): <NEW_LINE> <INDENT> items['mysterious meat'] = {'description': 'It is meat and it ' 'is mysterious', 'health': '???' } | Append the mysterious meat to the list of items | 625941d63317a56b86939e96 |
def crawl(path, TARGET_FILE_NUMBER): <NEW_LINE> <INDENT> batches = [] <NEW_LINE> in_a_batch = False <NEW_LINE> for root, dirs, files in os.walk(path, topdown=False): <NEW_LINE> <INDENT> if len(filter_python_files(files)) < 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not in_a_batch: <NEW_LINE> <INDENT> curren... | crawl a given file path, from the deepest node up, collecting and
organizing directories containing python files into `Batches` of less
than `TARGET_FILE_NUMBER` python files. | 625941d645492302aab5e508 |
def delete(self, arg, axis): <NEW_LINE> <INDENT> arg = self._axis2indices(arg, axis) <NEW_LINE> mask = np.ones(self.shape[axis], dtype=bool) <NEW_LINE> mask[arg] = False <NEW_LINE> if axis == 0: <NEW_LINE> <INDENT> return self[mask, :] <NEW_LINE> <DEDENT> elif axis == 1: <NEW_LINE> <INDENT> return self[:, mask] <NEW_LI... | Deletes arg from given axis.
:param arg: To be deleted. Can be string, integers, list of strings or integers, etc.
:param axis: Rows (0) or cols (1)
:return: Matrix instance with rows deleted. | 625941d685dfad0860c3b09d |
def __get_token_header(self): <NEW_LINE> <INDENT> des = self.get_token_des() <NEW_LINE> arr = (des, self.conf['systemType'], self.conf['Model'], self.conf['Release'], self.conf['DeviceId'], self.conf['versionCode'], self.conf['versionName'], self.conf['AppBuild'], self.conf['DeviceOS'], "0") <NEW_LINE> authorization = ... | 生成token头部
:return: | 625941d621bff66bcd684b93 |
def request(self, **request): <NEW_LINE> <INDENT> environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.input': StringIO(""), } <NEW_LINE> environ.update(self.default... | Similar to parent class, but returns the request object as soon as it
has created it. | 625941d6d4950a0f3b08c58f |
def contains_month(ngram, month_set): <NEW_LINE> <INDENT> for word in ngram[0].split(' '): <NEW_LINE> <INDENT> if word.lower() in month_set: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> return 0 | Identify if a n-gram has month, return 1 (has feature) 0 (no such feature)
:param ngram: a ngram
:param month_set: a set contains all months
:return: 1 (has feature) or 0 (no such feature) | 625941d66aa9bd52df036fe6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.