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["uuid_representation"] = options[k] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kwargs[k] = options[k] <NEW_LINE> <DEDENT> <DEDENT> return CodecOptions(**kwargs) | 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 not module: <NEW_LINE> <INDENT> raise ImportError('Unable to load module {}'.format(mfile)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 'message' in dir(module): <NEW_LINE> <INDENT> mclass = module.message() <NEW_LINE> mreg = mclass.registration <NEW_LINE> mclass.restoptions = options <NEW_LINE> if 'priority' in dir(mclass): <NEW_LINE> <INDENT> mpriority = mclass.priority <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mpriority = 100 <NEW_LINE> <DEDENT> if 'name' in dir(mclass): <NEW_LINE> <INDENT> mname = mclass.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mname = mfile <NEW_LINE> <DEDENT> if 'description' in dir(mclass): <NEW_LINE> <INDENT> mdescription = mclass.description <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mdescription = mfile <NEW_LINE> <DEDENT> if isinstance(mreg, list): <NEW_LINE> <INDENT> logger.info('[*] plugin {0} registered to receive messages from /{1}'.format(mfile, mreg)) <NEW_LINE> pluginList.append((mfile, mname, mdescription, mreg, mpriority, mclass)) | 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 known to man') <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> izi.types.length(1, 10)('') <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> izi.types.length(1, 10)('bacon is th') | 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 buf[ep_ptr+i].eq(v) <NEW_LINE> <DEDENT> ep_len = self.get_len_csr(epaddr) <NEW_LINE> yield from ep_len.write(ep_ptr + len(data)) <NEW_LINE> 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.glob('*.mp3')
[
Node('/opt/media/mp3/music1.mp3'),
Node('/opt/media/mp3/music2.mp3'),
]
:param pattern: a valid :py:mod:`fnmatch` pattern string
:param lazy: bool - if True returns an iterator, defaults to a flat :py:class:`list`
:returns: an iterator or a list of :py:class:`Node` | 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></li>') <NEW_LINE> self.assertContains(self.resp, '<li><a href="#" onclick="repair_search(2)" class="previous">2</a></li>') <NEW_LINE> self.assertContains(self.resp, '<a href="#" onclick="repair_search(2)" class="next">Next</a>') | 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 corresponding to the given compute node with
keys not present in the values['stats'] dictionary to
be deleted from the database. Set to False by default
:returns: Dictionary-like object containing the properties of the updated
compute node, including its corresponding service and statistics
Raises ComputeHostNotFound if compute node with the given ID doesn't exist. | 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], [0, 1, 0]]], dtype=np.int16) <NEW_LINE> filter_2 = np.array([[[0, 0, 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]]], dtype=np.int16) <NEW_LINE> return filter_0, filter_1, filter_2 | 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, x - 1, k, 59): <NEW_LINE> <INDENT> retval += ['top'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval += ['bottom'] <NEW_LINE> <DEDENT> if hand_will_win_play(n + 1, x, k, False) >= hand_will_win_play_scry_bottom( n, x, k, 59): <NEW_LINE> <INDENT> retval += ['top'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval += ['bottom'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> retval += ['mulligan'] <NEW_LINE> <DEDENT> return retval | 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> <DEDENT> else: <NEW_LINE> <INDENT> buf = self.anno_dict[bp_id] <NEW_LINE> buf[bp_id].lnum = lnum <NEW_LINE> buf.update(bp_id) | 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 Exception('Could not fetch STH') <NEW_LINE> <DEDENT> o = json.loads(s.decode('UTF-8')) <NEW_LINE> c.close() <NEW_LINE> return o | 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)) <NEW_LINE> person.chas = self.chas <NEW_LINE> try: <NEW_LINE> <INDENT> person.load() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.log.warning("Failed to load personality: [{}] - Exception upon 'load()'!".format(person.name), exc_info=e) <NEW_LINE> return False <NEW_LINE> <DEDENT> self._person.append(person) <NEW_LINE> self.log.debug("Successfully loaded personality: [{}]!".format(person.name)) <NEW_LINE> return True | 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: BasePersonality
:return: True for success, False for failure
:rtype: bool | 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_LINE> <DEDENT> try: <NEW_LINE> <INDENT> subset.append(float(row['Shoe Size'].replace(",", "."))) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> subset.append(float(row['Height'].replace(",", "."))) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> if len(subset) == 3: <NEW_LINE> <INDENT> genders.append(subset[0]) <NEW_LINE> shoe_sizes.append(subset[1]) <NEW_LINE> heights.append(subset[2]) <NEW_LINE> <DEDENT> <DEDENT> return genders, shoe_sizes, heights | 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(parameter_guess) <NEW_LINE> params_full[which_vars] = params <NEW_LINE> out = objectiveFunction(params_full) <NEW_LINE> return out <NEW_LINE> <DEDENT> parameter_guess_mod = parameter_guess[which_vars] <NEW_LINE> t0 = time() <NEW_LINE> OUTPUT = fmin(objectiveFunctionMod, parameter_guess_mod, full_output=1, maxiter=5000, maxfun=10000, disp=verbose, **kwargs) <NEW_LINE> t1 = time() <NEW_LINE> xopt = OUTPUT[0] <NEW_LINE> fopt = OUTPUT[1] <NEW_LINE> optiter = OUTPUT[2] <NEW_LINE> funcalls = OUTPUT[3] <NEW_LINE> warnflag = OUTPUT[4] <NEW_LINE> if warnflag != 0: <NEW_LINE> <INDENT> warnings.warn("Minimization failed! xopt=" + str(xopt) + ', fopt=' + str(fopt) + ', optiter=' + str(optiter) +', funcalls=' + str(funcalls) + ', warnflag=' + str(warnflag)) <NEW_LINE> <DEDENT> xopt_full = copy(parameter_guess) <NEW_LINE> xopt_full[which_vars] = xopt <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print("Time to estimate is " + str(t1-t0) + " seconds.") <NEW_LINE> <DEDENT> return xopt_full | 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.
parameter_guess : [float]
A starting point for the Nelder-Mead algorithm, which must be a valid
input for objectiveFunction.
which_vars : np.array or None
Array of booleans indicating which parameters should be estimated. When
not provided, estimation is performed on all parameters.
verbose : boolean
A flag for the amount of output to print.
Returns
-------
xopt : [float]
The values that minimize objectiveFunction. | 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 = counter + 1 <NEW_LINE> <DEDENT> <DEDENT> return port_name | 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["products"].append(product.jsonize()) <NEW_LINE> <DEDENT> print("products = %s\n" %(products)) <NEW_LINE> session.close() | 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(':', '') <NEW_LINE> length_date = len(date) <NEW_LINE> if date.count('W') == 1 and length_date == 8: <NEW_LINE> <INDENT> date = date.replace('W', '') <NEW_LINE> date_pattern = "%Y%W%w" <NEW_LINE> year = int(date[0:4]) <NEW_LINE> week = int(date[4:6]) - 1 <NEW_LINE> day = int(date[6]) <NEW_LINE> if day == 7: <NEW_LINE> <INDENT> day = 0 <NEW_LINE> <DEDENT> date = "%04d%02d%1d" % (year, week, day) <NEW_LINE> <DEDENT> elif length_date == 7 and date.isdigit() and value.count('-') != 2: <NEW_LINE> <INDENT> date_pattern = "%Y%j" <NEW_LINE> <DEDENT> elif length_date == 8 and date.isdigit(): <NEW_LINE> <INDENT> date_pattern = "%Y%m%d" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Wrong or incomplete ISO8601:2004 date format") <NEW_LINE> <DEDENT> if time.count('+') == 1 and '+' in time[-6:]: <NEW_LINE> <INDENT> (time, tz) = time.rsplit('+') <NEW_LINE> delta = -1 <NEW_LINE> <DEDENT> elif time.count('-') == 1 and '-' in time[-6:]: <NEW_LINE> <INDENT> (time, tz) = time.rsplit('-') <NEW_LINE> delta = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> delta = 0 <NEW_LINE> <DEDENT> if delta: <NEW_LINE> <INDENT> while len(tz) < 3: <NEW_LINE> <INDENT> tz += '0' <NEW_LINE> <DEDENT> delta = delta * (int(tz[0:2]) * 60 * 60 + int(tz[2:]) * 60) <NEW_LINE> <DEDENT> ms = 0 <NEW_LINE> if '.' in time: <NEW_LINE> <INDENT> (time, ms) = time.split(".") <NEW_LINE> ms = float('0.' + ms.strip()) <NEW_LINE> <DEDENT> length_time = len(time) <NEW_LINE> if length_time == 6 and time.isdigit(): <NEW_LINE> <INDENT> time_pattern = "%H%M%S" <NEW_LINE> <DEDENT> elif length_time == 4 and time.isdigit(): <NEW_LINE> <INDENT> time_pattern = "%H%M" <NEW_LINE> <DEDENT> elif length_time == 2 and time.isdigit(): <NEW_LINE> <INDENT> time_pattern = "%H" <NEW_LINE> <DEDENT> elif length_time == 0: <NEW_LINE> <INDENT> time_pattern = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Wrong or incomplete ISO8601:2004 time format") <NEW_LINE> <DEDENT> dt = datetime.datetime.strptime(date + 'T' + time, date_pattern + 'T' + time_pattern) <NEW_LINE> return dt + datetime.timedelta(seconds=float(delta) + ms) | 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_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> <DEDENT> '''spiteful_cc''' <NEW_LINE> if strategy_name == 'spiteful_cc': <NEW_LINE> <INDENT> if len(my_history) <= 1: <NEW_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> elif 'b' not in their_history: <NEW_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> <DEDENT> <DEDENT> '''winner12''' <NEW_LINE> if strategy_name == 'winner12': <NEW_LINE> <INDENT> betrayed = False <NEW_LINE> if countB(their_history) >= 2: <NEW_LINE> <INDENT> betrayed = True <NEW_LINE> <DEDENT> if len(my_history) < 2: <NEW_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> elif not betrayed: <NEW_LINE> <INDENT> if their_history[-1] == my_history[-1]: <NEW_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> if their_history[-1] != my_history[-1]: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> <DEDENT> <DEDENT> elif betrayed: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> <DEDENT> <DEDENT> '''gradual''' <NEW_LINE> if strategy_name == 'gradual': <NEW_LINE> <INDENT> num = 0 <NEW_LINE> if len(their_history) >= 1: <NEW_LINE> <INDENT> if their_history[-1] == 'b': <NEW_LINE> <INDENT> num = countB(their_history) <NEW_LINE> <DEDENT> <DEDENT> if len(their_history) >= 2: <NEW_LINE> <INDENT> if their_history[-2] + their_history[-1] == 'cc': <NEW_LINE> <INDENT> num = 0 <NEW_LINE> <DEDENT> <DEDENT> if num == 0: <NEW_LINE> <INDENT> return 'c' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> num -= 1 <NEW_LINE> <DEDENT> <DEDENT> '''spiteful''' <NEW_LINE> if strategy_name == 'spiteful': <NEW_LINE> <INDENT> if 'b' in their_history: <NEW_LINE> <INDENT> return 'b' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'c' | 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 (sz_fragment <= 0x100000)) or (sz_fragment % 0x100000 == 0)) <NEW_LINE> if is_segment and (sz_fragment == len(decoded_fragment)): <NEW_LINE> <INDENT> if self.m_currentBuffer: <NEW_LINE> <INDENT> self.m_currentBuffer += decoded_fragment <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.m_currentBuffer = decoded_fragment <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.m_currentBuffer: <NEW_LINE> <INDENT> self.__analyse_io_buffer(self.m_currentBuffer) <NEW_LINE> del self.m_currentBuffer <NEW_LINE> self.m_currentBuffer = None <NEW_LINE> <DEDENT> self.__analyse_io_buffer(decoded_fragment) | 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) and (QuotedPath[-1] == ord(' ') or QuotedPath[-1] == ord('.')): <NEW_LINE> <INDENT> QuotedPath = QuotedPath[:-1] + b"%b%03d" % (Globals.quoting_char, QuotedPath[-1]) <NEW_LINE> <DEDENT> if not Globals.escape_dos_devices: <NEW_LINE> <INDENT> return QuotedPath <NEW_LINE> <DEDENT> <DEDENT> if not re.search(br"^aux(\..*)*$|^prn(\..*)*$|^con(\..*)*$|^nul(\..*)*$|" br"^com[0-9](\..*)*$|^lpt[1-9]{1}(\..*)*$", QuotedPath, re.I): <NEW_LINE> <INDENT> return QuotedPath <NEW_LINE> <DEDENT> return b"%b%03d" % (Globals.quoting_char, QuotedPath[0]) + QuotedPath[1:] | 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_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="failed to create temporary content file: %s" % to_native(err), exception=traceback.format_exc()) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> checksum_src = None <NEW_LINE> checksum_dest = None <NEW_LINE> if not os.path.exists(tmpsrc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> module.fail_json(msg="Source %s does not exist" % (tmpsrc)) <NEW_LINE> <DEDENT> if not os.access(tmpsrc, os.R_OK): <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="Source %s not readable" % (tmpsrc)) <NEW_LINE> <DEDENT> checksum_src = module.sha1(tmpsrc) <NEW_LINE> if os.path.exists(dest): <NEW_LINE> <INDENT> if not os.access(dest, os.W_OK): <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="Destination %s not writable" % (dest)) <NEW_LINE> <DEDENT> if not os.access(dest, os.R_OK): <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="Destination %s not readable" % (dest)) <NEW_LINE> <DEDENT> checksum_dest = module.sha1(dest) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not os.access(os.path.dirname(dest), os.W_OK): <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="Destination dir %s not writable" % (os.path.dirname(dest))) <NEW_LINE> <DEDENT> <DEDENT> if checksum_src != checksum_dest: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shutil.copyfile(tmpsrc, dest) <NEW_LINE> changed = True <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> os.remove(tmpsrc) <NEW_LINE> module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(err)), exception=traceback.format_exc()) <NEW_LINE> <DEDENT> <DEDENT> os.remove(tmpsrc) <NEW_LINE> return changed | 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> <DEDENT> return text | 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_LINE> <INDENT> raise PopupException("You don't have the permissions to access" " job %s" % jobid) <NEW_LINE> <DEDENT> return view_func(request, *args, **kwargs) <NEW_LINE> <DEDENT> return wraps(view_func)(decorate) | 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_names.append(name) | 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> print_towers(towers) <NEW_LINE> return towers | 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> <DEDENT> elif cType == 'map' : <NEW_LINE> <INDENT> piclistFile = self.getCidPiclistFile(self.gid) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> self.log.writeToLog(self.errorCodes['0010'], [cType]) <NEW_LINE> <DEDENT> macPackId = self.projectConfig['CompTypes'][cType.capitalize()]['macroPackage'] <NEW_LINE> cvSep = macroConfig['Macros'][macPackId]['Illustrations']['chapterVerseSeperator'] <NEW_LINE> thisRef = '' <NEW_LINE> trueCid = cid <NEW_LINE> obj = {} <NEW_LINE> with codecs.open(piclistFile, "w", encoding='utf_8') as writeObject : <NEW_LINE> <INDENT> writeObject.write('% This is an auto-generated usfmTex piclist file for this project.\n') <NEW_LINE> writeObject.write('% Do not bother editing this file.\n\n') <NEW_LINE> for i in self.illustrationConfig[self.gid].keys() : <NEW_LINE> <INDENT> obj = self.illustrationConfig[self.gid][i] <NEW_LINE> thisRef = '' <NEW_LINE> if not self.tools.str2bool(obj['useThisIllustration']) : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> caption = '' <NEW_LINE> if self.illustrationConfig[self.gid][i]['bid'] == cid : <NEW_LINE> <INDENT> if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useCaptions']) and self.tools.str2bool(self.illustrationConfig[self.gid][i]['useThisCaption']) : <NEW_LINE> <INDENT> if obj['caption'] : <NEW_LINE> <INDENT> caption = obj['caption'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.illustrationConfig[self.gid][i]['bid'] == cid : <NEW_LINE> <INDENT> if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useCaptionReferences']) and self.tools.str2bool(self.illustrationConfig[self.gid][i]['useThisCaptionRef']) : <NEW_LINE> <INDENT> if obj['reference'] : <NEW_LINE> <INDENT> thisRef = obj['reference'] <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> thisRef = obj['chapter'] + cvSep + obj['verse'] <NEW_LINE> <DEDENT> <DEDENT> writeObject.write(obj['bid'] + ' ' + obj['chapter'] + '.' + obj['verse'] + ' |' + obj['fileName'] + '|' + obj['width'] + '|' + obj['position'] + '|' + obj['scale'] + '|' + obj['copyright'] + '|' + caption + '|' + thisRef + ' \n') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.log.writeToLog(self.errorCodes['0265'], [trueCid]) <NEW_LINE> return True | 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_projects: <NEW_LINE> <INDENT> elem = {'project': proj, 'experiments':self.api.get(f"{self.workspace}/{proj}")} <NEW_LINE> experiment.append(elem) <NEW_LINE> <DEDENT> self.experiments = experiment <NEW_LINE> <DEDENT> return self.experiments | 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_LINE> <INDENT> raise ValueError('Unable to determine plugin type (caget timed out)') <NEW_LINE> <DEDENT> type_ = type_.split(' ')[0] <NEW_LINE> try: <NEW_LINE> <INDENT> return _plugin_class[type_] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError('Unable to determine plugin type (PluginType={})' ''.format(type_)) | 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_time, toggle_apm_after_setting) | 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.assertContains(response, '<td class="field-release_date nowrap">') <NEW_LINE> self.assertContains(response, '<td class="action-checkbox">') | 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, u'test_role', default_permissions={ u'uri': u'com.example.', u'match': u'prefix', u'allow': { u'call': True, u'register': True, u'publish': True, u'subscribe': True, } } ) ) <NEW_LINE> self.session_factory = RouterSessionFactory(self.router_factory) | 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: <NEW_LINE> <INDENT> return contain_tree <NEW_LINE> <DEDENT> elif contain_tree == True: <NEW_LINE> <INDENT> return tree <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if tree.key[0] == name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | (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.sin(radlat) <NEW_LINE> magic = 1 - ee * magic * magic <NEW_LINE> sqrtmagic = math.sqrt(magic) <NEW_LINE> dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi) <NEW_LINE> dlng = (dlng * 180.0) / (a / sqrtmagic * math.cos(radlat) * pi) <NEW_LINE> mglat = g_lat + dlat <NEW_LINE> mglng = g_lng + dlng <NEW_LINE> w_lat = g_lat * 2 - mglat <NEW_LINE> w_lng = g_lng * 2 - mglng <NEW_LINE> return w_lat, w_lng | 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_ind is not None: <NEW_LINE> <INDENT> suffix_ind = len(f) - (len(suffix) + 1) <NEW_LINE> prefix = fname[:echo_ind] <NEW_LINE> trailing = fname[echo_ind+1:suffix_ind] <NEW_LINE> <DEDENT> return prefix, trailing, ftype | 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 filename after echo up to extension
ftype : str
file type for the acquired functional datasets | 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_LINE> if not user: <NEW_LINE> <INDENT> flash("No such user exists") <NEW_LINE> return redirect("/login") <NEW_LINE> <DEDENT> if not bcrypt.checkpw(password, user.password.encode('utf-8')): <NEW_LINE> <INDENT> flash("Incorrect password") <NEW_LINE> return redirect("/login") <NEW_LINE> <DEDENT> session["user_id"] = user.user_id <NEW_LINE> session["username"] = user.username <NEW_LINE> flash("Logged in") <NEW_LINE> <DEDENT> return redirect("/") | 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) -> vectord | 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.fmax(np.fmin(y_min, win_y_max), win_y_min) <NEW_LINE> y_max_clipped = np.fmax(np.fmin(y_max, win_y_max), win_y_min) <NEW_LINE> x_min_clipped = np.fmax(np.fmin(x_min, win_x_max), win_x_min) <NEW_LINE> x_max_clipped = np.fmax(np.fmin(x_max, win_x_max), win_x_min) <NEW_LINE> clipped = np_box_list.BoxList( np.hstack([y_min_clipped, x_min_clipped, y_max_clipped, x_max_clipped])) <NEW_LINE> clipped = _copy_extra_fields(clipped, boxlist) <NEW_LINE> if filter_nonoverlapping: <NEW_LINE> <INDENT> areas = area(clipped) <NEW_LINE> nonzero_area_indices = np.reshape( np.nonzero(np.greater(areas, 0.0)), [-1]).astype(np.int32) <NEW_LINE> clipped = gather(clipped, nonzero_area_indices) <NEW_LINE> <DEDENT> return clipped | 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_max, x_max] window to which the op
should clip boxes.
filter_nonoverlapping: whether to filter out boxes that do not overlap at
all with the window.
Returns:
a BoxList holding M_out boxes where M_out <= M_in | 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 servo, then
the position result will align well with the actual servo position, assuming
it is not stalled or slowed.
:raises TimeoutError: Connection timed out. | 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> elif isinstance(cond_val,int): <NEW_LINE> <INDENT> numpy_dtype=(cond_name,'i4') <NEW_LINE> <DEDENT> elif isinstance(cond_val,int): <NEW_LINE> <INDENT> numpy_dtype=(cond_name,'i8') <NEW_LINE> <DEDENT> elif isinstance(cond_val,float): <NEW_LINE> <INDENT> numpy_dtype=(cond_name,'f8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> numpy_dtype=(cond_name,'S',256) <NEW_LINE> <DEDENT> numpy_trial_condition_types.append(numpy_dtype) <NEW_LINE> class ConditionVariableDescription(object): <NEW_LINE> <INDENT> _numpyConditionVariableDescriptor=numpy_trial_condition_types <NEW_LINE> <DEDENT> <DEDENT> self.initializeConditionVariableTable(ConditionVariableDescription) | 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::
# Load a trial handler and
# create an associated table in the iohub data file
#
from psychopy.data import TrialHandler,importConditions
exp_conditions=importConditions('trial_conditions.xlsx')
trials = TrialHandler(exp_conditions,1)
# Inform the ioHub server about the TrialHandler
#
io.createTrialHandlerRecordTable(trials)
# Read a row of the trial handler for
# each trial of your experiment
#
for trial in trials:
# do whatever...
# During the trial, trial variable values can be updated
#
trial['TRIAL_START']=flip_time
# At the end of each trial, before getting
# the next trial handler row, send the trial
# variable states to iohub so they can be stored for future
# reference.
#
io.addTrialHandlerRecord(trial.values()) | 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> <INDENT> low = mid + 1 <NEW_LINE> <DEDENT> elif house < heaters[mid]: <NEW_LINE> <INDENT> high = mid - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> low = mid <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if low == 0: <NEW_LINE> <INDENT> radius = max(radius, heaters[low] - house) <NEW_LINE> <DEDENT> elif low == len(heaters): <NEW_LINE> <INDENT> radius = max(radius, house - heaters[-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> radius = max(radius, min (heaters[low] - house, house - heaters[low - 1] )) <NEW_LINE> <DEDENT> <DEDENT> return radius | :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> self.assertFalse(not_installed_packages, error_msg) | 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 += ')' <NEW_LINE> c.execute(newstr) <NEW_LINE> <DEDENT> conn.commit() | 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 pattern.index(symbol) + 1 < len(pattern): <NEW_LINE> <INDENT> return pattern[pattern.index(symbol) + 1] <NEW_LINE> <DEDENT> return pattern[0] | 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> <INDENT> mock = MagicMock(side_effect=[{"gid": 2}, {"gid": 2}]) <NEW_LINE> with patch.object(pw_user, "info", mock): <NEW_LINE> <INDENT> assert not pw_user.chgid("name", 1) <NEW_LINE> <DEDENT> <DEDENT> mock = MagicMock(return_value=None) <NEW_LINE> with patch.dict(pw_user.__salt__, {"cmd.run": mock}): <NEW_LINE> <INDENT> mock = MagicMock(side_effect=[{"gid": 1}, {"gid": 2}]) <NEW_LINE> with patch.object(pw_user, "info", mock): <NEW_LINE> <INDENT> assert pw_user.chgid("name", 1) | 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 in range(len(sum_tri)-2, -1, -1): <NEW_LINE> <INDENT> for j in range(len(sum_tri[i])): <NEW_LINE> <INDENT> sum_tri[i][j] = triangle[i][j] + min(sum_tri[i+1][j], sum_tri[i+1][j+1]) <NEW_LINE> <DEDENT> <DEDENT> return sum_tri[0][0] | :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) <NEW_LINE> return False <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("下载失败:" + path_s + " " + repr(e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | 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', xlim = (1e-4, 4), ax=ax) <NEW_LINE> return enrichment, rho, pval | 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 <NEW_LINE> os.chmod(filename, new_permissions) | 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.load_from_file("save.json") <NEW_LINE> self.run_and_check(engine, record) <NEW_LINE> del 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.sum(data != data, axis=0) == 0 <NEW_LINE> X = data[:, mask] <NEW_LINE> if data_y: <NEW_LINE> <INDENT> y = data_y <NEW_LINE> <DEDENT> <DEDENT> if data_y is not None: <NEW_LINE> <INDENT> return X, y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return X | 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> etag = response.collapse_body() <NEW_LINE> etag = '"%s"' % hashlib.md5.new(etag).hexdigest() <NEW_LINE> response.headers['ETag'] = etag <NEW_LINE> <DEDENT> <DEDENT> response.ETag = etag <NEW_LINE> if status >= 200 and status <= 299: <NEW_LINE> <INDENT> conditions = request.headers.elements('If-Match') or [] <NEW_LINE> conditions = [str(x) for x in conditions] <NEW_LINE> if conditions and not (conditions == ["*"] or etag in conditions): <NEW_LINE> <INDENT> return httperror( request, response, 412, description="If-Match failed: ETag %r did not match %r" % ( etag, conditions ) ) <NEW_LINE> <DEDENT> conditions = request.headers.elements('If-None-Match') or [] <NEW_LINE> conditions = [str(x) for x in conditions] <NEW_LINE> if conditions == ["*"] or etag in conditions: <NEW_LINE> <INDENT> if request.method in ("GET", "HEAD"): <NEW_LINE> <INDENT> return redirect(request, response, [], code=304) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return httperror( request, response, 412, description=( "If-None-Match failed: ETag %r matched %r" % ( etag, conditions ) ) ) | 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 feature is not designed for URL's which allow
methods other than GET. For example, if a POST to the same URL returns
no content, the automatic ETag will be incorrect, breaking a fundamental
use for entity tags in a possibly destructive fashion. Likewise, if you
raise 304 Not Modified, the response body will be empty, the ETag hash
will be incorrect, and your application will break.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 | 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> <DEDENT> return models.AnsiblePlay.objects.filter(metadata=metadata).last() | :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, Expr) else c for c in utils.to_list(subset)) <NEW_LINE> sel_col_names = [expr._get_field(c).name for c in subset] <NEW_LINE> <DEDENT> if method is not None and value is not None: <NEW_LINE> <INDENT> raise ValueError('The argument `method` is not compatible with `value`.') <NEW_LINE> <DEDENT> if method is None and value is None: <NEW_LINE> <INDENT> raise ValueError('You should supply at least one argument in `method` and `value`.') <NEW_LINE> <DEDENT> if method is not None and method not in ('backfill', 'bfill', 'pad', 'ffill'): <NEW_LINE> <INDENT> raise ValueError('Method value %s is illegal.' % str(method)) <NEW_LINE> <DEDENT> if method in ('backfill', 'bfill'): <NEW_LINE> <INDENT> sel_cols = list(reversed(sel_col_names)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sel_cols = sel_col_names <NEW_LINE> <DEDENT> if method is None: <NEW_LINE> <INDENT> for n in sel_col_names: <NEW_LINE> <INDENT> e = col_dict[n] <NEW_LINE> col_dict[n] = e.isnull().ifelse(value, e).rename(n) <NEW_LINE> <DEDENT> return expr.select(list(col_dict.values())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> names = list(col_dict.keys()) <NEW_LINE> typs = list(c.dtype.name for c in col_dict.values()) <NEW_LINE> @output(names, typs) <NEW_LINE> def mapper(row): <NEW_LINE> <INDENT> last_valid = None <NEW_LINE> update_dict = dict() <NEW_LINE> try: <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> def isnan(v): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return np.isnan(v) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> isnan = lambda v: False <NEW_LINE> <DEDENT> for n in sel_cols: <NEW_LINE> <INDENT> old_val = getattr(row, n) <NEW_LINE> if old_val is None or isnan(old_val): <NEW_LINE> <INDENT> if last_valid is not None: <NEW_LINE> <INDENT> update_dict[n] = last_valid <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> last_valid = old_val <NEW_LINE> <DEDENT> <DEDENT> yield row.replace(**update_dict) <NEW_LINE> <DEDENT> return expr.map_reduce(mapper) | 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] = int(host_port[1]) <NEW_LINE> return host_port | 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> self.team_2_name = team_2_name <NEW_LINE> self.team_2_url = team_2_url <NEW_LINE> self.map_name = map_name <NEW_LINE> self.event_name = event_name <NEW_LINE> self.event_url = event_url | 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_2 of the match
:param map_name: map name of the match
:param event_name: event name of the match
:param event_url: url of the event of the match | 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 enumerate(image_list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print("parsing", image_index, image, "\n") <NEW_LINE> if not tf.gfile.Exists(image): <NEW_LINE> <INDENT> tf.logging.fatal('File does not exist %s', image) <NEW_LINE> <DEDENT> with tf.gfile.FastGFile(image, 'rb') as f: <NEW_LINE> <INDENT> image_data = f.read() <NEW_LINE> predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) <NEW_LINE> predictions = np.squeeze(predictions) <NEW_LINE> feature_tensor = sess.graph.get_tensor_by_name('pool_3:0') <NEW_LINE> feature_set = sess.run(feature_tensor, {'DecodeJpeg/contents:0': image_data}) <NEW_LINE> feature_vector = np.squeeze(feature_set) <NEW_LINE> outfile_name = os.path.basename(image) + ".npz" <NEW_LINE> out_path = os.path.join(output_dir, outfile_name) <NEW_LINE> np.savetxt(out_path, feature_vector, delimiter=',') <NEW_LINE> node_lookup = NodeLookup() <NEW_LINE> top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1] <NEW_LINE> for node_id in top_k: <NEW_LINE> <INDENT> human_string = node_lookup.id_to_string(node_id) <NEW_LINE> score = predictions[node_id] <NEW_LINE> print("results for", image) <NEW_LINE> print('%s (score = %.5f)' % (human_string, score)) <NEW_LINE> print("\n") <NEW_LINE> image_to_labels[image].append( { "labels": human_string, "score": str(score) } ) <NEW_LINE> <DEDENT> <DEDENT> proc = psutil.Process() <NEW_LINE> open_files = proc.open_files() <NEW_LINE> for open_file in open_files: <NEW_LINE> <INDENT> file_handler = getattr(open_file, "fd") <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('could not process image index',image_index,'image', image) <NEW_LINE> print(e) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return image_to_labels | 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> background.paste(foreground, box) <NEW_LINE> return background | 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_LINE> if self.lead_time is not None: <NEW_LINE> <INDENT> final_txt = final_txt + ", total lead_time:%.1f" % self.lead_time <NEW_LINE> <DEDENT> return final_txt | 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 '\n\n'.join(chunked) | @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(key, str(val))) <NEW_LINE> <DEDENT> f.write("#Reference groups (aref)\n") <NEW_LINE> for t, txt in enumerate(identical_ref): <NEW_LINE> <INDENT> f.write("\t# {} --> {:<30}\n".format(t, txt)) <NEW_LINE> <DEDENT> for targets in props['targets']: <NEW_LINE> <INDENT> f.write("#Target groups (atarget) for {}\n".format(targets)) <NEW_LINE> for t, txt in enumerate(identical_target[targets]): <NEW_LINE> <INDENT> f.write("\t# {} --> {:<30}\n".format(t, txt)) <NEW_LINE> <DEDENT> <DEDENT> f.write("#*** means that the binding event reached the end of the simulation\n") <NEW_LINE> f.write("#aref \t atarget \t Resid ref \t Resid target \t Starting time (ps) \t Ending time (ps) \t Duration (ps) \t Mean target-ref COM distance (nm)\n") <NEW_LINE> for targets in props['targets']: <NEW_LINE> <INDENT> f.write("#TARGET GROUP: {}\n".format(targets)) <NEW_LINE> event = events[targets] <NEW_LINE> for ev in event: <NEW_LINE> <INDENT> f.write("{:<5} {:<5} {:<5} {:<5} {:<10.0f} {:<10.0f} {:<10.0f} {:<10.2f}".format(ev.aref, ev.atarget, ev.rref, ev.rtarget, ev.tmin, ev.tmax, ev.duration, ev.anchor_dist)) <NEW_LINE> if ev.alive: <NEW_LINE> <INDENT> f.write(" ***") <NEW_LINE> <DEDENT> f.write("\n") <NEW_LINE> <DEDENT> <DEDENT> f.close() | 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, lr, optimizer, lrsch, momentum, weight_decay, pretrained, size_input, num_classes, backbone ) <NEW_LINE> self.logger_train = Logger( 'Train', ['loss', 'loss_gmm', 'loss_bce', 'loss_att', 'loss_stn' ], [ 'topk', 'gmm'], self.plotter ) <NEW_LINE> self.logger_val = Logger( 'Val ', ['loss', 'loss_gmm', 'loss_bce', 'loss_att', 'loss_stn' ], [ 'topk', 'gmm'], self.plotter ) | 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[name] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> log.error("Can't insert %s->%s into %s (%s???) ??", ID, destTypes.IDsByName[name], idTable.shape, type(ID)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _convert(ID, meta): <NEW_LINE> <INDENT> return idTable[ID], meta <NEW_LINE> <DEDENT> return _convert | :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=%(id)s""", info) <NEW_LINE> chats = cur.fetchall() <NEW_LINE> cur.close() <NEW_LINE> conn.close() <NEW_LINE> print(chats) <NEW_LINE> return flask.jsonify(chats) | :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(diff * params[i]) <NEW_LINE> grad[i] = term_1[i] + term_2[i] <NEW_LINE> <DEDENT> return grad | 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.