code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _parse_codec_options(options: Any) -> CodecOptions: <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k in set(options) & { "document_class", "tz_aware", "uuidrepresentation", "unicode_decode_error_handler", "tzinfo", "type_registry", }: <NEW_LINE> <INDENT> if k == "uuidrepresentation": <NEW_LINE> <INDENT> kwargs["uui... | Parse BSON codec options. | 625941bd3346ee7daa2b2c75 |
def registerPlugins(): <NEW_LINE> <INDENT> plugin_manager = pynsive.PluginManager() <NEW_LINE> if os.path.exists('plugins'): <NEW_LINE> <INDENT> modules = pynsive.list_modules('plugins') <NEW_LINE> for mfile in modules: <NEW_LINE> <INDENT> module = pynsive.import_module(mfile) <NEW_LINE> reload(module) <NEW_LINE> if no... | walk the ./plugins directory
and register modules in pluginList
as a tuple: (mfile, mname, mdescription, mreg, mpriority, mclass) | 625941bd66656f66f7cbc0b6 |
def test_length(): <NEW_LINE> <INDENT> assert izi.types.length(1, 10)('bacon') == 'bacon' <NEW_LINE> assert izi.types.length(1, 10)(42) == '42' <NEW_LINE> assert '42' in izi.types.length(1, 42).__doc__ <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> izi.types.length(1, 10)('bacon is the greatest food kno... | Tests that izi's length type successfully handles a length range | 625941bd5fc7496912cc388a |
def to_serializable(self): <NEW_LINE> <INDENT> return {'token_to_idx': self._token_to_idx, 'pad_token': self.pad_token} | returns a dictionary that can be serialized | 625941bdcad5886f8bd26ee6 |
@api_view(http_method_names=['GET']) <NEW_LINE> def get_box(request: Request, box_pk: int) -> Response: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Response(food_boxes()[box_pk]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return Response(ERROR_MESSAGE_404, status=HTTP_404_NOT_FOUND) | Бокс с едой. | 625941bde5267d203edcdbab |
def version_satisfies(module, requirement): <NEW_LINE> <INDENT> return Version(module.__version__) >= Version(requirement) | Perform a version check. This code could be smarter...
| 625941bdd10714528d5ffbec |
def set_data(self, epaddr, data): <NEW_LINE> <INDENT> assert isinstance(data, (list, tuple)) <NEW_LINE> self.ep_print(epaddr, "Set: %r", data) <NEW_LINE> ep_ptr = yield from self.get_ptr_csr(epaddr).read() <NEW_LINE> buf = self.get_module(epaddr, "buf") <NEW_LINE> for i, v in enumerate(data): <NEW_LINE> <INDENT> yield ... | Set an endpoints buffer to given data to be sent. | 625941bd6fece00bbac2d648 |
def glob(self, pattern, lazy=False): <NEW_LINE> <INDENT> def iterator(): <NEW_LINE> <INDENT> for filename in self.walk(lazy=lazy): <NEW_LINE> <INDENT> if fnmatch(filename, pattern): <NEW_LINE> <INDENT> yield self.new(filename) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return lazy and iterator() or list(iterator()) | searches for globs recursively in all the children node of the
current node returning a respective [python`Node`] instance
for that given.
Under the hood it applies the given ``pattern`` into :py:func:`fnmatch.fnmatch`
::
>>> from plant import Node
>>>
>>> mp3_node = Node('/opt/media/mp3')
>>> mp3_node.g... | 625941bd0c0af96317bb80f4 |
def test_admin_005(self): <NEW_LINE> <INDENT> r=self.obj.post(data=add_supplier(phone=15616624736,id=None,row=5),row=5) <NEW_LINE> print(r.text) | 添加供应商信息 | 625941bd4e4d5625662d42e7 |
def test_html(self): <NEW_LINE> <INDENT> self.assertContains(self.resp, '<table') <NEW_LINE> self.assertContains(self.resp, '<a href="/consertos/1/">') <NEW_LINE> self.assertContains(self.resp, '<div class="pagination pagination-centered"') <NEW_LINE> self.assertContains(self.resp, '<li class="disabled"><span>1</span><... | HTML deve conter uma tabela com lista de consertos | 625941bd73bcbd0ca4b2bf82 |
def _fire_freezing_deferred(_): <NEW_LINE> <INDENT> escrows = state.input.getFreezingDeferred() <NEW_LINE> escrows.addErrback(DeferredLogger.error, msg='Freezing error: ') <NEW_LINE> escrows.callback(None) <NEW_LINE> log.debug('Fired freezing deferred.') <NEW_LINE> return escrows | Signal the state that no further input peers will be accepted,
i.e., the set of assigned escrow addresses will not change anymore. | 625941bde1aae11d1e749bc1 |
def compute_node_update(context, compute_id, values, prune_stats=False): <NEW_LINE> <INDENT> return IMPL.compute_node_update(context, compute_id, values, prune_stats) | Set the given properties on a compute node and update it.
:param context: The security context
:param compute_id: ID of the compute node
:param values: Dictionary containing compute node properties to be updated
:param prune_stats: If set to True, forces the compute node statistics
entries correspo... | 625941bd460517430c394098 |
def Sharpness_Edge_Filter(): <NEW_LINE> <INDENT> filter_0 = np.array([[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [-7, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]], dtype=np.int16) <NEW_LINE> filter_1 = np.array([[[0, 1, 0], [0, 1, 0], [0, 1, 0]], [[0, 1, 0], [0, -7, 0], [0, 1, 0]], [[0, 1, 0], [0, 1, 0], [... | Sharpness_Edge Filter
边缘锐化 滤波
:return: | 625941bdbde94217f3682d00 |
def contains(self, **kwargs): <NEW_LINE> <INDENT> return self.where_like('%{}%', **kwargs) | eg. contains(a='abc') 相当于 LIKE '%abc%' | 625941bd91f36d47f21ac3fb |
@require_http_methods(["GET"]) <NEW_LINE> def get_roles(request): <NEW_LINE> <INDENT> data = chef.get_roles() <NEW_LINE> return HttpResponse(json.dumps(data), content_type="application/json") | Returns all nodes in the repo | 625941bd5f7d997b871749a1 |
def hasCycle(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> pi = pj = head <NEW_LINE> while pj.next and pj.next.next: <NEW_LINE> <INDENT> pi, pj = pi.next, pj.next.next <NEW_LINE> if pi == pj: return True <NEW_LINE> <DEDENT> return False | :type head: ListNode
:rtype: bool | 625941bdeab8aa0e5d26da6a |
def mpe_backprop(self): <NEW_LINE> <INDENT> self._layers[-1].set_log_derivative(0.0) <NEW_LINE> for layer in self.top_down_layers(): <NEW_LINE> <INDENT> layer.mpe_backprop() | WRITEME | 625941bdd10714528d5ffbed |
@check50.check(exists) <NEW_LINE> def withspaces(): <NEW_LINE> <INDENT> check50.run("python3 vigenere.py baz").stdin("hello, world!").stdout("ciphertext:\s*iekmo, vprke!\n", "ciphertext: iekmo, vprke!\n").exit(0) | encrypts "hello, world!" as "iekmo, vprke!" using "baz" as keyword | 625941bd56ac1b37e62640e0 |
def should_i_keep_draw(n, x, k): <NEW_LINE> <INDENT> retval = [n, k] <NEW_LINE> if hand_will_win_play(n, x, k, False) >= level_3_mull_odds_play(n, x, k): <NEW_LINE> <INDENT> retval += ['keep'] <NEW_LINE> if n < 7: <NEW_LINE> <INDENT> if hand_will_win_play(n + 1, x - k, k + 1, False) >= hand_will_win_play_scry_bottom( n... | Given a hand, determines whether the hand should be kept and if so how to scry
:param int n: Cards in hand
:param int x: SSGs in deck
:param int k: SSGs in hand
:return list: Returns a list with n and k as well as "keep" or "mulligan" and "top"/"bottom" twice | 625941bdf9cc0f698b14050a |
def add_bp(self, bp_id, pathname, lnum): <NEW_LINE> <INDENT> if not isinstance(lnum, int) or lnum <= 0: <NEW_LINE> <INDENT> raise ValueError('"lnum" must be strictly positive: %s' % lnum) <NEW_LINE> <DEDENT> if not bp_id in self.anno_dict.keys(): <NEW_LINE> <INDENT> self.add_anno(bp_id, pathname, lnum) <NEW_LINE> <DEDE... | Add the breakpoint to the global list and to the buffer annotation list. | 625941bd4527f215b584c366 |
def get_sth(url): <NEW_LINE> <INDENT> dnsname, path = parse_url(url) <NEW_LINE> c = create_new_https_connection(dnsname) <NEW_LINE> c.request('GET', build_urlpath(path, 'get-sth')) <NEW_LINE> r = c.getresponse() <NEW_LINE> status = r.status <NEW_LINE> s = r.read() <NEW_LINE> if status != 200: <NEW_LINE> <INDENT> raise ... | get_sth fetches a STH from a log and returns the Python object of the JSON response from the log
:param url:
:return: the Python object representing the log JSON response | 625941bd76d4e153a657ea3c |
def load_personality(self, person): <NEW_LINE> <INDENT> if not isinstance(person, BasePersonality): <NEW_LINE> <INDENT> self.log.warning("Object [{}] is not a valid personalty! Must subclass BasePersonality!") <NEW_LINE> return False <NEW_LINE> <DEDENT> self.log.debug("Loading personality: [{}]...".format(person.name))... | Loads a given personality, and adds it to the collection.
The personality MUST inherit 'BasePersonality',
or else the operation will fail.
We also call 'load()' for the personality to be added.
If this method fails, then we will fail and refuse to add it.
:param person: Personality to add
:type person: BasePersonali... | 625941bd6aa9bd52df036caf |
def perform(self) -> None: <NEW_LINE> <INDENT> if self.item.consumable: <NEW_LINE> <INDENT> self.item.consumable.activate(self) | 아이템 능력 발동, 내용에 맞는 행동을 한다. | 625941bda17c0f6771cbdf5f |
def load_attributes(full_data): <NEW_LINE> <INDENT> genders = [] <NEW_LINE> shoe_sizes = [] <NEW_LINE> heights = [] <NEW_LINE> for row in full_data: <NEW_LINE> <INDENT> subset = [] <NEW_LINE> gender = clean_gender(row['Gender'].lower()) <NEW_LINE> if gender is not None: <NEW_LINE> <INDENT> subset.append(gender) <NEW_LI... | Load the gender, shoe size and height data | 625941bd50485f2cf553cca5 |
def minimizeNelderMead(objectiveFunction, parameter_guess, verbose=False, which_vars=None, **kwargs): <NEW_LINE> <INDENT> if which_vars is None: <NEW_LINE> <INDENT> which_vars = np.ones(len(parameter_guess),dtype=bool) <NEW_LINE> <DEDENT> def objectiveFunctionMod(params): <NEW_LINE> <INDENT> params_full = copy(paramete... | Minimizes the objective function using the Nelder-Mead simplex algorithm,
starting from an initial parameter guess.
Parameters
----------
objectiveFunction : function
The function to be minimized. It should take only a single argument, which
should be a list representing the parameters to be estimated.
parame... | 625941bd26068e7796caebe6 |
def clearFilters(self): <NEW_LINE> <INDENT> self._filters = [] <NEW_LINE> return self | Clear all filters on this C{Reads} instance.
@return: C{self}. | 625941bd9f2886367277a79c |
def _get_port_name(self, port): <NEW_LINE> <INDENT> port_name = "port-{}".format(port) <NEW_LINE> counter = 1 <NEW_LINE> for port_entry in self.service_json['spec']['ports']: <NEW_LINE> <INDENT> if port_entry['name'] == port_name: <NEW_LINE> <INDENT> port_name = "port-{}-{}".format(port, counter) <NEW_LINE> counter = c... | Gets the port name to use in the service | 625941bd5166f23b2e1a5065 |
def func_return_jsonised_products(): <NEW_LINE> <INDENT> dao = DAO() <NEW_LINE> session = dao.get_session() <NEW_LINE> product_table = dao.get_table("products") <NEW_LINE> products = { "products" : [] } <NEW_LINE> for product in session.query(Product).order_by(product_table.c.rodd_id): <NEW_LINE> <INDENT> products["pro... | return a product that has been jsonised | 625941bd2ae34c7f2600d03e |
def parse_iso_8601(value): <NEW_LINE> <INDENT> value = value.replace('Z', '') <NEW_LINE> try: <NEW_LINE> <INDENT> (date, time) = value.split("T") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> date = value <NEW_LINE> time = "" <NEW_LINE> <DEDENT> date = date.replace('-', '') <NEW_LINE> time = time.replace(':', '') <NE... | Parses an ISO8601:2004 date time string and returns a datetime object in
UTC.
>>> d = parse_iso_8601('2016-09-26T23:45:43+12:00')
>>> d.isoformat()
'2016-09-26T11:45:43'
>>> d = parse_iso_8601('2016-09-26T23:45:43.001Z')
>>> d.isoformat()
'2016-09-26T23:45:43.001000' | 625941bd7b180e01f3dc4710 |
def __init__(self, service, commit): <NEW_LINE> <INDENT> self.service = service <NEW_LINE> self.commit = commit | Initialise a ShowRenderer. | 625941bd3d592f4c4ed1cf81 |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _almathswig.new_TransformAndVelocity6D(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(self) -> TransformAndVelocity6D
__init__(self, Transform pT, Velocity6D pV) -> TransformAndVelocity6D | 625941bdb57a9660fec3378d |
def move(my_history, their_history, my_score, their_score): <NEW_LINE> <INDENT> if strategy_name == 'tft_spiteful': <NEW_LINE> <INDENT> if 'bb' in their_history: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> <DEDENT> elif len(their_history) >= 1: <NEW_LINE> <INDENT> return their_history[-1] <NEW_LINE> <DEDENT> else: <NEW_L... | tft_spiteful | 625941bd15baa723493c3e80 |
def __init__(self, simulation, parameters): <NEW_LINE> <INDENT> super().__init__(simulation, parameters) <NEW_LINE> self._tiType = "SN" | Constructor for the NonReturnItem class | 625941bd5166f23b2e1a5066 |
def append_io_buffer(self, a_fragment, sz_fragment=0): <NEW_LINE> <INDENT> decoded_fragment = _decode_octal_escape_sequence(a_fragment) <NEW_LINE> is_segment = ( ((sz_fragment % 0x100 == 0) and (sz_fragment <= 0x1000)) or ((sz_fragment % 0x1000 == 0) and (sz_fragment <= 0x10000)) or ((sz_fragment % 0x10000 == 0) and (s... | This receives all read() and write() buffers displayed by strace or ltrace,
decodes them and tries to rebuild a complete logical message if it seems to be truncated.
It then analyses the logical pieces. | 625941bd4428ac0f6e5ba6fe |
def containerView(*args, **kwargs): <NEW_LINE> <INDENT> pass | A container view defines the layout information for the published attributes of a particular container.
Returns: None | 625941bd3eb6a72ae02ec3e2 |
def quote(path): <NEW_LINE> <INDENT> QuotedPath = Globals.chars_to_quote_regexp.sub(_quote_single, path) <NEW_LINE> if not Globals.escape_dos_devices and not Globals.escape_trailing_spaces: <NEW_LINE> <INDENT> return QuotedPath <NEW_LINE> <DEDENT> if Globals.escape_trailing_spaces: <NEW_LINE> <INDENT> if len(QuotedPath... | Return quoted version of given path
Any characters quoted will be replaced by the quoting char and
the ascii number of the character. For instance, "10:11:12"
would go to "10;05811;05812" if ":" were quoted and ";" were
the quoting character. | 625941bd71ff763f4b549594 |
def write_file(module, dest, content): <NEW_LINE> <INDENT> changed = False <NEW_LINE> fd, tmpsrc = tempfile.mkstemp(text=False) <NEW_LINE> f = os.fdopen(fd, 'wb') <NEW_LINE> try: <NEW_LINE> <INDENT> f.write(content) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f.close() <NEW... | Write content to destination file dest, only if the content
has changed. | 625941bd5e10d32532c5ee34 |
def build_content(self): <NEW_LINE> <INDENT> text = "" <NEW_LINE> for label in self.labels: <NEW_LINE> <INDENT> index = self.labels.index(label) <NEW_LINE> label = label.decode('utf-8') <NEW_LINE> value = self.values[index] <NEW_LINE> text += "%(label)s: %(value)s \n" % {'label': label, 'value': value} <NEW_LINE> <DEDE... | Builds simple 'label: value' string | 625941bdb57a9660fec3378e |
def level_desc(level): <NEW_LINE> <INDENT> return "{key} ({steps}, {actions}, {features})".format(**level) | Short, readable level and its parameters string. | 625941bd9c8ee82313fbb681 |
def check_job_permission(view_func): <NEW_LINE> <INDENT> def decorate(request, *args, **kwargs): <NEW_LINE> <INDENT> jobid = kwargs['jobid'] <NEW_LINE> job = Job.from_id(jt=request.jt, jobid=jobid) <NEW_LINE> if not conf.SHARE_JOBS.get() and not request.user.is_superuser and job.user != request.user.username: <NEW... | Ensure that the user has access to the job.
Assumes that the wrapped function takes a 'jobid' param. | 625941bddc8b845886cb5440 |
def add_varlen_feature(self, name, index, max_len, dim, embedding_dim=8, hashing=False, dtype='int32'): <NEW_LINE> <INDENT> feat = ListSparseFeature(name=name, index=index, max_len=max_len, dim=dim, embedding_dim=embedding_dim, hashing=hashing, dtype=dtype) <NEW_LINE> self.meta_dict[name] = feat <NEW_LINE> self.varlen_... | Add a list sparse feature whose length is not fixed | 625941bd293b9510aa2c31a5 |
def initialize_towers(num_disks, source, target, middle): <NEW_LINE> <INDENT> towers = {source: [], target: [], middle: []} <NEW_LINE> for i in range(num_disks): <NEW_LINE> <INDENT> towers[source].append(DISK * (i * 2 + 1)) <NEW_LINE> towers[target].append("") <NEW_LINE> towers[middle].append("") <NEW_LINE> <DEDENT> pr... | function initialize_towers
parameters: initial height, plus names of source, target, middle towers
(all strings)
returns: towers, a dictionary with key = name of tower and
value = a list of disks (all strings) | 625941bdb7558d58953c4e26 |
def pew(target): <NEW_LINE> <INDENT> pass | Evaporates the target. | 625941bd67a9b606de4a7dc8 |
def createPiclistFile (self, cid) : <NEW_LINE> <INDENT> self.proj_config.getMacroConfig() <NEW_LINE> macroConfig = self.proj_config.macroConfig <NEW_LINE> cType = self.projectConfig['Groups'][self.gid]['cType'] <NEW_LINE> if cType == 'usfm' : <NEW_LINE> <INDENT> piclistFile = self.getCidPiclistFile(cid) <NEW_LINE> <DED... | Look in the cid for ig data. Extract it from the cid and
use it to create a piclist file for this specific cid. If
there is no ig data no piclist file will be made. | 625941bd10dbd63aa1bd2ab3 |
def get_all_experiments(self, project=None): <NEW_LINE> <INDENT> if project is not None: <NEW_LINE> <INDENT> self.experiments = self.api.get(f"{self.workspace}/{project}") <NEW_LINE> print("fetching experiments") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> experiment = [] <NEW_LINE> for proj in self.available_project... | Fetches all experiments for a given project
Parameters
----------
project : STR, optional
The default is None.
Returns
-------
COMET EXPERIMENT OBJ | 625941bd283ffb24f3c55811 |
def get_areadetector_plugin_class(prefix, timeout=2.0): <NEW_LINE> <INDENT> cls = plugin_from_pvname(prefix) <NEW_LINE> if cls is not None: <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> type_rbv = prefix + 'PluginType_RBV' <NEW_LINE> type_ = epics.caget(type_rbv, timeout=timeout) <NEW_LINE> if type_ is None: <NEW_... | Get an areadetector plugin class by supplying its PV prefix
Uses `plugin_from_pvname` first, but falls back on using epics channel
access to determine the plugin type.
Returns
-------
plugin : Plugin
The plugin class
Raises
------
ValueError
If the plugin type can't be determined | 625941bd7047854f462a1319 |
def incomplete_translate(self): <NEW_LINE> <INDENT> return self._type('Translate', False) | Return a QS of translate tasks that are not deleted or completed. | 625941bdcb5e8a47e48b79ba |
def ensure_network_preference(log, ad, network_preference, voice_or_data=None, max_wait_time=MAX_WAIT_TIME_NW_SELECTION, toggle_apm_after_setting=False): <NEW_LINE> <INDENT> return ensure_network_preference_for_subscription( log, ad, ad.droid.subscriptionGetDefaultSubId(), network_preference, voice_or_data, max_wait_ti... | Ensure that current rat is within the device's preferred network rats.
| 625941bd656771135c3eb779 |
def enable_status_led(self): <NEW_LINE> <INDENT> self.ipcon.send_request(self, BrickDC.FUNCTION_ENABLE_STATUS_LED, (), '', '') | Enables the status LED.
The status LED is the blue LED next to the USB connector. If enabled is is
on and it flickers if data is transfered. If disabled it is always off.
The default state is enabled.
.. versionadded:: 2.3.1$nbsp;(Firmware) | 625941bd30bbd722463cbcd0 |
def wc(filename): <NEW_LINE> <INDENT> fr = open(filename, "r") <NEW_LINE> data = fr.read() <NEW_LINE> fr.close() <NEW_LINE> wordCount = 0 <NEW_LINE> lines = data.split("\n") <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> words = line.split() <NEW_LINE> wordCount += len(words) <NEW_LINE> <DEDENT> return wordCount | Returns the number of words in file filename | 625941bd6fece00bbac2d649 |
def test_changelist_field_classes(self): <NEW_LINE> <INDENT> Podcast.objects.create(name="Django Dose", release_date=datetime.date.today()) <NEW_LINE> response = self.client.get(reverse("admin:admin_views_podcast_changelist")) <NEW_LINE> self.assertContains(response, '<th class="field-name">') <NEW_LINE> self.assertCon... | Cells of the change list table should contain the field name in their
class attribute. | 625941bd0fa83653e4656ec9 |
def setUp(self): <NEW_LINE> <INDENT> self.router_factory = RouterFactory() <NEW_LINE> self.realm = RouterRealm(None, {u'name': u'realm1'}) <NEW_LINE> self.router_factory.start_realm(self.realm) <NEW_LINE> self.router = self.router_factory.get(u'realm1') <NEW_LINE> self.router.add_role( RouterRoleStaticAuth( self.router... | Setup router and router session factories. | 625941bd377c676e912720b6 |
def multipy_const(self, const): <NEW_LINE> <INDENT> for i in range(self.array): <NEW_LINE> <INDENT> for j in range(self.array[i]): <NEW_LINE> <INDENT> self.array[i][j] *= const <NEW_LINE> <DEDENT> <DEDENT> return self | Vynasobeni matice konstantou | 625941bd4c3428357757c237 |
def get_markup(gid): <NEW_LINE> <INDENT> url = "https://docs.google.com/feeds/download/documents/export/Export?id=%s&format=html" % gid <NEW_LINE> return doc.url_fetch(url) | collect the raw markup for a google doc id | 625941bd63d6d428bbe443fc |
def _search_tree(tree, name): <NEW_LINE> <INDENT> if type(tree) == Tree: <NEW_LINE> <INDENT> if tree.root.key[0] == name: <NEW_LINE> <INDENT> return tree <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for child in tree.child: <NEW_LINE> <INDENT> contain_tree = _search_tree(child, name) <NEW_LINE> if type(contain_tree) =... | (Tree, unicode) -> object
If name is in the tree, return the subtree start from where name is
located in the tree. Return True or False if name is leaf or not in
the tree. | 625941bd45492302aab5e1cd |
def transformGCJtoWGS(g_lat, g_lng): <NEW_LINE> <INDENT> if out_of_china(g_lng, g_lat): <NEW_LINE> <INDENT> return g_lng, g_lat <NEW_LINE> <DEDENT> dlat = transformlat(g_lng - 105.0, g_lat - 35.0) <NEW_LINE> dlng = transformlng(g_lng - 105.0, g_lat - 35.0) <NEW_LINE> radlat = g_lat / 180.0 * pi <NEW_LINE> magic = math.... | GCJ02(火星坐标系)转GPS84
:param g_lat:火星坐标系纬度
:param g_lng:火星坐标系的经度
:return: | 625941bd0a50d4780f666d9d |
def afni_fname_parse(f, echo_ind=None): <NEW_LINE> <INDENT> fname = f.split('+')[0] <NEW_LINE> suffix = ''.join(f.split('+')[-1:]) <NEW_LINE> ftype = '+' + suffix.split('.')[0] <NEW_LINE> if echo_ind is None: <NEW_LINE> <INDENT> prefix = fname <NEW_LINE> trailing = '' <NEW_LINE> <DEDENT> elif echo_i... | Filename parser for AFNI file types (.BRIK/.HEAD).
For AFNI file types, the space (e.g., +tlrc) is considered
as the file type.
Parameters
----------
f : string
the filename represented as a string
Returns
-------
prefix : str
the prefix for each filename, up to the echo number
trailing : str
any part of ... | 625941bdd7e4931a7ee9de29 |
@app.route('/admin', methods=['POST']) <NEW_LINE> def login_process(): <NEW_LINE> <INDENT> if not session.get("user_id"): <NEW_LINE> <INDENT> username = request.form.get("username") <NEW_LINE> password = request.form.get("password").encode('utf-8') <NEW_LINE> user = User.query.filter_by(username=username).first() <NEW_... | Login the admin. | 625941be50812a4eaa59c231 |
def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) | Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Instagram.) | 625941bd7c178a314d6ef368 |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _egglib_binding.new_vectord(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(std::vector<(double)> self) -> vectord
__init__(std::vector<(double)> self, vectord arg2) -> vectord
__init__(std::vector<(double)> self, std::vector< double >::size_type size) -> vectord
__init__(std::vector<(double)> self, std::vector< double >::size_type size, std::vector< double >::value_type const & value... | 625941bedc8b845886cb5441 |
def clip_to_window(boxlist, window, filter_nonoverlapping=True): <NEW_LINE> <INDENT> y_min, x_min, y_max, x_max = np.array_split(boxlist.get(), 4, axis=1) <NEW_LINE> win_y_min = window[0] <NEW_LINE> win_x_min = window[1] <NEW_LINE> win_y_max = window[2] <NEW_LINE> win_x_max = window[3] <NEW_LINE> y_min_clipped = np.fma... | Clip bounding boxes to a window.
This op clips input bounding boxes (represented by bounding box
corners) to a window, optionally filtering out boxes that do not
overlap at all with the window.
Args:
boxlist: BoxList holding M_in boxes
window: a numpy array of shape [4] representing the
[y_min, x_min, y... | 625941be38b623060ff0acfc |
def get_position(self, channel: int) -> float: <NEW_LINE> <INDENT> self._check_channel(channel) <NEW_LINE> with self._conn_lock: <NEW_LINE> <INDENT> self.send_cmd(bytes((self.SerialCommands.GET_POSITION, channel))) <NEW_LINE> data = self._read(2) <NEW_LINE> <DEDENT> return (data[0] << 8 | data[1]) / 4 | Get the current position of the device on the specified channel
The result is returned in a measure of quarter-microseconds, which mirrors
the Target parameter of setTarget.
This is not reading the true servo position, but the last target position sent
to the servo. If the Speed is set to below the top speed of the ser... | 625941be8a43f66fc4b53f75 |
def createTrialHandlerRecordTable(self, trials): <NEW_LINE> <INDENT> trial=trials.trialList[0] <NEW_LINE> numpy_trial_condition_types=[] <NEW_LINE> for cond_name,cond_val in trial.items(): <NEW_LINE> <INDENT> if isinstance(cond_val,basestring): <NEW_LINE> <INDENT> numpy_dtype=(cond_name,'S',256) <NEW_LINE> <DEDENT> eli... | Create a condition variable table in the ioHub data file based on
the a psychopy TrialHandler. By doing so, the iohub data file
can contain the DV and IV values used for each trial of an experiment
session, along with all the iohub device events recorded by iohub
during the session. Example psychopy code usage::
#... | 625941bed53ae8145f87a181 |
def findRadius(self, houses, heaters): <NEW_LINE> <INDENT> heaters = sorted(heaters) <NEW_LINE> radius = 0 <NEW_LINE> for house in houses: <NEW_LINE> <INDENT> low, high = 0, len(heaters) - 1 <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = low + (high - low) / 2 <NEW_LINE> if house > heaters[mid]: <NEW_LINE> <IN... | :type houses: List[int]
:type heaters: List[int]
:rtype: int | 625941be56b00c62f0f14565 |
def test_correctness_of_installed_rpm_packages(self): <NEW_LINE> <INDENT> not_installed_packages = get_not_installed_rpm_packages() <NEW_LINE> error_msg = linesep + 'List of not installed packages: ' <NEW_LINE> for package in not_installed_packages: <NEW_LINE> <INDENT> error_msg += linesep + package <NEW_LINE> <DEDENT>... | Checks if all rpm packages from PMDK library are installed. | 625941becad5886f8bd26ee7 |
def writeData(idx, results, conn, name): <NEW_LINE> <INDENT> c = conn.cursor() <NEW_LINE> text = 'INSERT INTO '+name+' VALUES(' <NEW_LINE> for i in xrange(len(results)): <NEW_LINE> <INDENT> newstr = text+str(idx[i]) <NEW_LINE> for j in results[i]: <NEW_LINE> <INDENT> newstr +=', '+str(j) <NEW_LINE> <DEDENT> newstr += '... | this function writes to the SQL database the new data derived from fitData
the format is as follow:
RMSE of fit, shotnumber, time, params (with peak val, offset, width) | 625941be097d151d1a222d69 |
def rotor(symbol, n, reverse=False): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return symbol <NEW_LINE> <DEDENT> for pattern in ROTOR_DICT[n]: <NEW_LINE> <INDENT> if symbol.upper() in pattern: <NEW_LINE> <INDENT> if reverse: <NEW_LINE> <INDENT> return pattern[pattern.index(symbol) - 1] <NEW_LINE> <DEDENT> if p... | implement the basic logic for rotor of machine
:param symbol: char from ALPHABET
:param n: number of rotor
:param reverse: if router going reverse
:return: ciphered char | 625941bea17c0f6771cbdf60 |
def test_chgid(): <NEW_LINE> <INDENT> mock = MagicMock(return_value={"gid": 1}) <NEW_LINE> with patch.object(pw_user, "info", mock): <NEW_LINE> <INDENT> assert pw_user.chgid("name", 1) <NEW_LINE> <DEDENT> mock = MagicMock(return_value=None) <NEW_LINE> with patch.dict(pw_user.__salt__, {"cmd.run": mock}): <NEW_LINE> <IN... | Test if group id given is same as previous id | 625941be0383005118ecf4f1 |
def __init__(self, first=0, second=1): <NEW_LINE> <INDENT> super().__init__(first) <NEW_LINE> self._prev = second - first | Create a new fibonacci progression.
first the first term of the progression (default 0)
second the second term of the progression (default 1) | 625941be15baa723493c3e81 |
def minimumTotal(self, triangle): <NEW_LINE> <INDENT> if len(triangle) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if len(triangle) == 1: <NEW_LINE> <INDENT> return triangle[0][0] <NEW_LINE> <DEDENT> sum_tri = [[0] * i for i in range(1, len(triangle))] <NEW_LINE> sum_tri.append(triangle[-1]) <NEW_LINE> for i... | :type triangle: List[List[int]]
:rtype: int | 625941be82261d6c526ab3a9 |
def saveImg(self,url,path_s,img_type=""): <NEW_LINE> <INDENT> if url[:4]!="http": <NEW_LINE> <INDENT> url="https:"+url <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> urlretrieve(url,self.home+path_s+img_type) <NEW_LINE> <DEDENT> except FileNotFoundError as fnf: <NEW_LINE> <INDENT> print("存储错误:"+path_s+" "+fnf.strerror) <... | url path img_type | 625941bed53ae8145f87a182 |
def fitness_scatter(region, s, associations, reference, annotate_protective=True, fname = None, running_avg=True, ax=None): <NEW_LINE> <INDENT> enrichment, rho, pval = scatter_vs_entropy(region, s, associations, reference, fname=fname, annotate_protective=annotate_protective, running_avg=True, xlabel='fitness cost', xl... | scatter intrapatient fitness estimates of amino acid mutations vs cross-sectional entropy | 625941be99cbb53fe6792af4 |
def push_to(self, other_storage): <NEW_LINE> <INDENT> raise NotImplementedError | Push local blobs to another storage. | 625941be7d43ff24873a2bab |
def make_executable(filename): <NEW_LINE> <INDENT> import stat <NEW_LINE> if sys.platform.startswith('java'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not os.access(filename, os.X_OK): <NEW_LINE> <INDENT> st = os.stat(filename) <NEW_LINE> new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IEXEC | stat.S_IXGRP... | Makes sure that the file is executable. | 625941be30dc7b7665901877 |
def test_save_to_file(self): <NEW_LINE> <INDENT> engine = cityflow.Engine(config_file=self.config_file, thread_num=4) <NEW_LINE> self.run_steps(engine, self.period) <NEW_LINE> engine.snapshot().dump("save.json") <NEW_LINE> self.run_steps(engine, self.period) <NEW_LINE> record = self.get_record(engine) <NEW_LINE> engine... | Disk IO test | 625941beaad79263cf39094a |
def get_media_attribute_types(self): <NEW_LINE> <INDENT> if not self.db_is_open: <NEW_LINE> <INDENT> LOG.debug("database is closed") <NEW_LINE> <DEDENT> return [] | Return a list of all Attribute types associated with Media and MediaRef
instances in the database. | 625941be63f4b57ef000102d |
def __init__(self, path=None): <NEW_LINE> <INDENT> self._is_dir = None <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> self.path = path | Ctor for LocalDestinationPath
:param LocalDestinationPath self: this
:param str path: path | 625941be55399d3f055885c1 |
def test_all_instruction_program(self): <NEW_LINE> <INDENT> pass | Test against a program that covers all instructions to flex architecture
simulation. | 625941beec188e330fd5a6b2 |
def getKey(self, field): <NEW_LINE> <INDENT> return os.environ.get(ENV_VAR_NAME) | :return: Symmetric encryption key as string or None if not available | 625941bed58c6744b4257b6e |
def ignore_imputer(data, data_y=None, ignore_object=True): <NEW_LINE> <INDENT> if ignore_object: <NEW_LINE> <INDENT> mask = np.sum(data != data, axis=1) == 0 <NEW_LINE> X = data[mask] <NEW_LINE> if data_y is not None: <NEW_LINE> <INDENT> y = data_y[mask] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> mask = np.... | A function for making the dataset without objects (or features) with mmissing values.
----------
:param data: dataset
:param data_y: target (optional)
:param ignore_object: if true objects with missing values will be ignored, otherwise features will be ignored
:return: X or X, y (if data_y will be) | 625941bea219f33f3462887b |
def validate_etags(request, response, autotags=False): <NEW_LINE> <INDENT> if hasattr(response, "ETag"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> status = response.status <NEW_LINE> etag = response.headers.get('ETag') <NEW_LINE> if (not etag) and autotags: <NEW_LINE> <INDENT> if status == 200: <NEW_LINE> <INDENT>... | Validate the current ETag against If-Match, If-None-Match headers.
If autotags is True, an ETag response-header value will be provided
from an MD5 hash of the response body (unless some other code has
already provided an ETag header). If False (the default), the ETag
will not be automatic.
WARNING: the autotags featu... | 625941bea05bb46b383ec732 |
def simple_playbook_executor(playbook, metadata, options=None, env=None, **kwargs): <NEW_LINE> <INDENT> with generate_playbook(playbook) as playbook_filename: <NEW_LINE> <INDENT> completed_process = ansible_playbook_callback( playbook=playbook_filename, metadata=metadata, options=options, env=env, **kwargs) <NEW_LINE> ... | :rtype: django_ansible.models.AnsiblePlay | 625941bebf627c535bc130dc |
def fillna(expr, value=None, method=None, subset=None): <NEW_LINE> <INDENT> col_dict = OrderedDict([(c, expr._get_field(c)) for c in expr.schema.names]) <NEW_LINE> if subset is None: <NEW_LINE> <INDENT> sel_col_names = expr.schema.names <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subset = (c.copy() if isinstance(c, E... | Fill NA/NaN values using the specified method
:param DataFrame expr: input DataFrame
:param method: can be ‘backfill’, ‘bfill’, ‘pad’, ‘ffill’ or None
:param value: value to fill into
:param subset: Labels along other axis to consider.
:return: DataFrame | 625941be5f7d997b871749a2 |
def get_location(self): <NEW_LINE> <INDENT> return self.location | Get location dictionary, latitude and longitude
usage:
dictionary = get_location()
:return location: a dictionary with latitude and longitude | 625941be66673b3332b91f9e |
def parse_host_port(h, proto): <NEW_LINE> <INDENT> host_port = h.split(":", 1) <NEW_LINE> if len(host_port) == 1: <NEW_LINE> <INDENT> if proto.lower() == 'http': return (h, 80) <NEW_LINE> if proto.lower() == 'https': return (h, 443) <NEW_LINE> return (h, 443) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> host_port[1] =... | Parses strings in the form host[:port] | 625941be8a349b6b435e8081 |
def __init__(self, match_date, match_date_url, team_1_name, team_1_url, team_2_name, team_2_url, map_name, event_name, event_url): <NEW_LINE> <INDENT> self.match_date = match_date <NEW_LINE> self.match_date_url = match_date_url <NEW_LINE> self.team_1_name = team_1_name <NEW_LINE> self.team_1_url = team_1_url <NEW_LINE>... | Initialize an instance of Match with all of its attributes
:param match_date: date of the match
:param match_date_url: url of the date of the match
:param team_1_name: name of team_1 of the match
:param team_1_url: url of team_1 of the match
:param team_2_name: name of team_2 of the match
:param team_2_url: url of team... | 625941bee1aae11d1e749bc3 |
def run_inference_on_images(image_list, output_dir): <NEW_LINE> <INDENT> image_to_labels = defaultdict(list) <NEW_LINE> create_graph() <NEW_LINE> with tf.Session() as sess: <NEW_LINE> <INDENT> softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') <NEW_LINE> print(image_list) <NEW_LINE> for image_index, image in e... | Runs inference on an image list.
Args:
image_list: a list of images.
output_dir: the directory in which image vectors will be saved
Returns:
image_to_labels: a dictionary with image file keys and predicted
text label values | 625941be4428ac0f6e5ba6ff |
def paste_in_middle(background, foreground): <NEW_LINE> <INDENT> x1 = round((background.size[0] - foreground.size[0]) / 2) <NEW_LINE> y1 = round((background.size[1] - foreground.size[1]) / 2) <NEW_LINE> x2 = x1 + foreground.size[0] <NEW_LINE> y2 = y1 + foreground.size[1] <NEW_LINE> box = (x1, y1, x2, y2) <NEW_LINE> bac... | The function will past the foreground image on the middle of the background image.
:param background: The bottom image. Must be larger than the foreground image.
:param foreground: The top image. Must be smaller than the background image.
:return: The new merged image. | 625941beeab8aa0e5d26da6b |
def leakyrelu_forward(x): <NEW_LINE> <INDENT> out = None <NEW_LINE> pos_out = np.maximum(0, x) <NEW_LINE> neg_out = -np.maximum(-0.01*x, 0) <NEW_LINE> out = pos_out + neg_out <NEW_LINE> cache = x <NEW_LINE> return out, cache | Computes the forward pass for a layer of LeakyReLU units.
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: out itself | 625941be5f7d997b871749a3 |
def assembly_step_summary(self): <NEW_LINE> <INDENT> plan = "\n ".join( "%s-%s: %s" % (start, end, str(quote)) for (start, end), quote in sorted(self.assembly_plan.items()) ) <NEW_LINE> title = "Ordering plan (%s):" % self.source.name <NEW_LINE> final_txt = "%s:\n %s\nPrice:%.02f" % (title, plan, self.price) <NEW_LIN... | Return a print-friendly, simple string of the ordering plan. | 625941be0a366e3fb873e726 |
def chunk_text(self,text): <NEW_LINE> <INDENT> sentences = self.theMontyLingua.split_sentences(text) <NEW_LINE> tokenized = map(self.theMontyLingua.tokenize,sentences) <NEW_LINE> tagged = map(self.theMontyLingua.tag_tokenized,tokenized) <NEW_LINE> chunked = map(self.theMontyLingua.chunk_tagged,tagged) <NEW_LINE> return... | @sig public String chunk_text(String text) | 625941be97e22403b379cea7 |
def on_hover(self, _window, _event, hover): <NEW_LINE> <INDENT> self.hover = hover | Starts/Stops the notification timer on a mouse in/out event | 625941bef9cc0f698b14050c |
def write_events_STD(events, props, sel, name, identical_ref, identical_target): <NEW_LINE> <INDENT> f = open(name + "_btimes_STD.sfu", 'w') <NEW_LINE> f.write("#Binding residence time (ps) from (nonpolar) H-H contacts\n") <NEW_LINE> for key, val in props.items(): <NEW_LINE> <INDENT> f.write("#{:<10} {:<20}\n".format... | Writes a file describing all the STD events (when Hs are distinguishable).
The output includes atom indices, residue indices, and chemical position of the reference and target groups
as well as initial time, final time, duration, and distance to the anchor for each event. | 625941be4527f215b584c368 |
def divideby(divis, divid): <NEW_LINE> <INDENT> return divid/divis | Note the order of the arguments! Returns divid / divis.
Designed for implementation using partial. | 625941be462c4b4f79d1d5de |
def create(self, arch, num_output_channels, num_input_channels, loss, lr, optimizer, lrsch, momentum=0.9, weight_decay=5e-4, pretrained=False, size_input=388, num_classes=8, backbone='preactresnet' ): <NEW_LINE> <INDENT> super(AttentionGMMSTNNeuralNet, self).create( arch, num_output_channels, num_input_channels, loss, ... | Create
Args:
-arch (string): architecture
-num_output_channels,
-num_input_channels,
-loss (string):
-lr (float): learning rate
-optimizer (string) :
-lrsch (string): scheduler learning rate
-pretrained (bool)
- | 625941bea8ecb033257d2fdd |
def blocktypeConverter(destTypes, sourceTypes): <NEW_LINE> <INDENT> idTable = numpy.arange(0, id_limit, dtype=numpy.uint16) <NEW_LINE> for name, ID in sourceTypes.IDsByName.iteritems(): <NEW_LINE> <INDENT> if name in destTypes.IDsByName: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> idTable[ID] = destTypes.IDsByName[nam... | :param destTypes:
:type destTypes: BlockTypeSet
:param sourceTypes:
:type sourceTypes: BlockTypeSet
:return:
:rtype: | 625941bebde94217f3682d02 |
def __init__(self): <NEW_LINE> <INDENT> self.Definition = None <NEW_LINE> self.RequestId = None | :param Definition: 自适应转码模板唯一标识。
:type Definition: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | 625941be097d151d1a222d6a |
def fr2old_path(fr: FileResource) -> Path: <NEW_LINE> <INDENT> name = '-'.join( util.sanitize_fname(component) for component in get_components(fr) ) <NEW_LINE> return self.config['old_dir'] / name | Returns a path to a copy of the data _as it is on the server_ | 625941be50485f2cf553cca7 |
def get_message_groups(user, token_info): <NEW_LINE> <INDENT> username = token_info['username'] <NEW_LINE> id = token_info['id'] <NEW_LINE> info = {'id': id} <NEW_LINE> print(info) <NEW_LINE> cur, conn = connect_to_db() <NEW_LINE> cur.execute("""SELECT * FROM message_groups WHERE user1=%(id)s OR user2=%(id)s OR user3=%... | :return: | 625941be627d3e7fe0d68d5c |
def grad_rastrigin(params, diff): <NEW_LINE> <INDENT> d = int(len(params)) <NEW_LINE> term_1 = np.zeros_like(params) <NEW_LINE> term_2 = np.zeros_like(params) <NEW_LINE> grad = np.zeros_like(params) <NEW_LINE> for i in range(d): <NEW_LINE> <INDENT> term_1[i] = 2 * params[i] <NEW_LINE> term_2[i] = 10 * diff * np.sin(dif... | Gradient of Rastrigin function.
Args:
params(np.array): 1d numpy array of function arguments
diff(float): difficulty parameter, controls wiggliness of the function
Returns:
grad(np.array): 1d numpy array of Rastrigin function derivatives for each
argument, evaluated at `params` and `diff` | 625941be5e10d32532c5ee35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.