code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def compute_output(self): <NEW_LINE> <INDENT> x,y=self.input_nodes <NEW_LINE> self.output_value=np.dot(x.output_value,y.output_value) <NEW_LINE> return self.output_value | 计算并返回Multiplication operation 值
:return: | 625941c0a17c0f6771cbdfc1 |
def get_tags(self, **kwargs): <NEW_LINE> <INDENT> tags = iterate_all( 'Tags', self.connection.describe_tags, **kwargs ) <NEW_LINE> return dict((tag['Key'], tag['Value']) for tag in tags) | Returns tag list for selected instance of EFS | 625941c0e1aae11d1e749c24 |
@app.route('/list', methods=['GET']) <NEW_LINE> def list_stories(): <NEW_LINE> <INDENT> db = get_db() <NEW_LINE> query = """SELECT * FROM app""" <NEW_LINE> cur = db.execute(query) <NEW_LINE> stories = cur.fetchall() <NEW_LINE> return render_template('list.html', entries=stories) | Show stories | 625941c0aad79263cf3909ac |
def add_server(params): <NEW_LINE> <INDENT> db = api.common.get_conn() <NEW_LINE> validate(server_schema, params) <NEW_LINE> if isinstance(params["port"], str): <NEW_LINE> <INDENT> params["port"] = int(params["port"]) <NEW_LINE> <DEDENT> if isinstance(params.get("server_number"), str): <NEW_LINE> <INDENT> params["serve... | Add a shell server to the pool of servers. First server is
automatically assigned server_number 1 (yes, 1-based numbering)
if not otherwise specified.
Args:
params: A dict containing:
host
port
username
password
server_number
Returns:
The sid. | 625941c05e10d32532c5ee96 |
def check_existence_by_id( self, resource_id, api_version, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/{resourceId}' <NEW_LINE> path_format_arguments = { 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True) } <NEW_LINE> url = self._client.format_url(... | Checks by ID whether a resource exists.
:param resource_id: The fully qualified ID of the resource, including
the resource name and resource type. Use the format,
/subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}
:type resource_id: str
:param api... | 625941c07cff6e4e811178f4 |
def _third_party_auth_context(request, redirect_to): <NEW_LINE> <INDENT> context = { "currentProvider": None, "providers": [], "secondaryProviders": [], "finishAuthUrl": None, "errorMessage": None, } <NEW_LINE> if third_party_auth.is_enabled(): <NEW_LINE> <INDENT> for enabled in third_party_auth.provider.Registry.accep... | Context for third party auth providers and the currently running pipeline.
Arguments:
request (HttpRequest): The request, used to determine if a pipeline
is currently running.
redirect_to: The URL to send the user to following successful
authentication.
Returns:
dict | 625941c0f9cc0f698b14056c |
def open(idstr): <NEW_LINE> <INDENT> contact = profile.blist.contact_for_idstr(idstr) <NEW_LINE> if contact is not None: <NEW_LINE> <INDENT> return begin_conversation(contact) | Opens an IM window (or raises an existing one) for a buddy id string. | 625941c0442bda511e8be38a |
def get_properties(self): <NEW_LINE> <INDENT> return RevisionProperties(self._rev_id, self._repo, self) | Get the RevisionProperties for this revision. | 625941c091f36d47f21ac45f |
def fit(self, X, y=None): <NEW_LINE> <INDENT> mask = _get_mask(X, self.missing_values) <NEW_LINE> X = X[~mask] <NEW_LINE> if self.strategy == 'most_frequent': <NEW_LINE> <INDENT> modes = pd.Series(X).mode() <NEW_LINE> <DEDENT> elif self.strategy == 'constant': <NEW_LINE> <INDENT> modes = np.array([self.fill_value]) <NE... | Get the most frequent value.
Parameters
----------
X : np.ndarray or pd.Series
Training data.
y : Passthrough for ``Pipeline`` compatibility.
Returns
-------
self: CategoricalImputer | 625941c0f548e778e58cd4eb |
def compile_funcs(self, feed_shapes): <NEW_LINE> <INDENT> self.node_to_compiled_func = {} <NEW_LINE> for node in self.node_to_shape_map: <NEW_LINE> <INDENT> if node in feed_shapes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> shape = self.node_to_shape_map[node] <NEW_LINE> inputs = node.inputs <NEW_LINE> input_shap... | Compile tvm ops to native code.
Must be called after infer_shape(...) since op compilation requires
knowledge of tensor shapes.
Parameters
----------
feed_shapes: node->shapes mapping for feed_dict nodes. | 625941c0b545ff76a8913d85 |
def execute(self, lf_raw: str) -> int: <NEW_LINE> <INDENT> logical_form = re.sub(r"\(a:", r"(", lf_raw) <NEW_LINE> parse = semparse_util.lisp_to_nested_expression(logical_form) <NEW_LINE> if len(parse) < 2: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if parse[0] == "infer": <NEW_LINE> <INDENT> args = [self._exec_... | Very basic model for executing friction logical forms. For now returns answer index (or
-1 if no answer can be concluded) | 625941c0cc40096d615958c0 |
def get_email(obj): <NEW_LINE> <INDENT> pass | Return the subscriber's e-mail address. If not found,
return None, and the notification message will be skipped.
The `obj` parameter exists because subscriptions have no
awearness of their context; some of them (e.g. the Naaya
`AccountSubscription`) need to access the site in order to
find the email address. `obj` is ... | 625941c0cc0a2c11143dcdff |
def search(self, query=None, *args, **kwargs): <NEW_LINE> <INDENT> sqs = SearchQuerySet() <NEW_LINE> user = kwargs.get('user', None) <NEW_LINE> if hasattr(user, 'impersonated_user'): <NEW_LINE> <INDENT> if isinstance(user.impersonated_user, User): <NEW_LINE> <INDENT> user = user.impersonated_user <NEW_LINE> <DEDENT> <D... | Uses haystack to query events.
Returns a SearchQuerySet | 625941c0a934411ee3751601 |
def reopen_task(conn, task_id, start_date, end_date): <NEW_LINE> <INDENT> checker.date_validate(start_date) <NEW_LINE> checker.date_validate(end_date) <NEW_LINE> checker.date_compare(start_date, end_date) <NEW_LINE> with conn: <NEW_LINE> <INDENT> cursor = conn.execute(SQL_OPEN_TASK, ('opened', start_date, end_date, tas... | Переоткрывает задачу | 625941c0283ffb24f3c55872 |
def calc_sim_collector(self, key, values): <NEW_LINE> <INDENT> (rest1, rest2), common_ratings = key, values <NEW_LINE> common_ratings_list = list(common_ratings) <NEW_LINE> n_common = len(common_ratings_list) <NEW_LINE> if n_common==0: <NEW_LINE> <INDENT> rho=0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff1 = [] ... | Pick up the information from the previous yield as shown. Compute
the pearson correlation and yield the final information as in the
last line here. | 625941c0379a373c97cfaab2 |
def setup_widget(self, widgetns): <NEW_LINE> <INDENT> globs = self.globalns <NEW_LINE> globs['ctx'] = Context.from_request(globs['req']) <NEW_LINE> globs['auth_ctx'] = Context.from_request(globs['auth_req']) <NEW_LINE> for wp in self.dbsys.providers : <NEW_LINE> <INDENT> if widgetns in set(wp.get_widgets()) : <NEW_LINE... | (Insert | update) the IWidgetProvider in the global
namespace.
@param widgetns widget name.
@throws RuntimeError if a widget with requested name cannot
be found. | 625941c07d847024c06be228 |
def get_regional_data(country): <NEW_LINE> <INDENT> iso3 = country['iso3'] <NEW_LINE> level = country['regional_level'] <NEW_LINE> gid_level = 'GID_{}'.format(level) <NEW_LINE> path_output = os.path.join(DATA_INTERMEDIATE, iso3, 'regional_data_uba.csv') <NEW_LINE> path_country = os.path.join(DATA_INTERMEDIATE, iso3, 'n... | Extract regional data including luminosity and population.
Parameters
----------
country : string
Three digit ISO country code. | 625941c063f4b57ef000108d |
def update(self, start: int, end: int, iteration: int, **kwargs) -> None: <NEW_LINE> <INDENT> value = self(**kwargs) <NEW_LINE> if isinstance(value, torch.Tensor): <NEW_LINE> <INDENT> value = value.cpu() <NEW_LINE> <DEDENT> self.values[start:end, iteration] = value.squeeze() | Update the internal value table of the metric | 625941c0b830903b967e987c |
def evaluate(self, trials, games, xoro, testNet = False, goodNet = 0): <NEW_LINE> <INDENT> if testNet: <NEW_LINE> <INDENT> answers = Game.run(1,trials, games, self, xoro, True, goodNet) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> answers = Game.run(1,trials,games,self, xoro) <NEW_LINE> <DEDENT> return answers | Tests the network and returns the results | 625941c0d8ef3951e32434ac |
def newfiles(self, user=None, start=None, end=None, reverse=False, step=None, total=None): <NEW_LINE> <INDENT> for event in self.logevents(logtype="upload", user=user, start=start, end=end, reverse=reverse, step=step, total=total): <NEW_LINE> <INDENT> filepage = pywikibot.FilePage(event.title()) <NEW_LINE> date = event... | Yield information about newly uploaded files.
Yields a tuple of FilePage, Timestamp, user(unicode), comment(unicode).
N.B. the API does not provide direct access to Special:Newimages, so
this is derived from the "upload" log events instead. | 625941c08a43f66fc4b53fd6 |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.secret: <NEW_LINE> <INDENT> self.secret = heliosutils.random_string(12) <NEW_LINE> self.election.append_log("Trustee %s added" % self.name) <NEW_LINE> <DEDENT> super(Trustee, self).save(*args, **kwargs) | override this just to get a hook | 625941c07047854f462a137b |
def setOpacity(self, newOpacity, operation='', log=None): <NEW_LINE> <INDENT> if operation in ['', '=']: <NEW_LINE> <INDENT> self.opacity = newOpacity <NEW_LINE> <DEDENT> elif operation in ['+']: <NEW_LINE> <INDENT> self.opacity += newOpacity <NEW_LINE> <DEDENT> elif operation in ['-']: <NEW_LINE> <INDENT> self.opacity... | Hard setter for opacity, allows the suppression of log messages and calls the update method
| 625941c023e79379d52ee4d5 |
def nextSpace(row, col, vertical): <NEW_LINE> <INDENT> if vertical is True: <NEW_LINE> <INDENT> return (row + 1), col <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return row, (col + 1) | Returns the position of the next space, whether its vertical or horizontal | 625941c0a79ad161976cc0b4 |
def sparse_apply_adadelta(var, accum, accum_update, lr, rho, epsilon, grad, indices, use_locking=False, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> if use_locking is None: <NEW_LINE> <INDENT> use_locking = False <NEW_LINE> ... | var: Should be from a Variable().
Args:
var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`.
accum: A mutable `Tensor`. Must have the s... | 625941c055399d3f05588622 |
def javascript_tag(content): <NEW_LINE> <INDENT> return content_tag("script", javascript_cdata_section(content), type="text/javascript") | Returns a JavaScript tag with the ``content`` inside.
Example::
>>> javascript_tag("alert('All is good')"
'<script type="text/javascript">alert('All is good')</script>' | 625941c0287bf620b61d39d4 |
def _initialize_protocols(self): <NEW_LINE> <INDENT> self._default_protocol = self.process_class.get_default_protocol() <NEW_LINE> self._protocols = self.process_class.get_available_protocols() | Initialize the protocols class attribute by parsing them from the configuration file. | 625941c0dc8b845886cb54a3 |
def unique_conn_id(self): <NEW_LINE> <INDENT> next_id = self._next_conn_id <NEW_LINE> self._next_conn_id += 1 <NEW_LINE> return next_id | Generate a new unique connection id.
See :meth:`AbstractDeviceAdapter.unique_conn_id`.
Returns:
int: A new, unique integer suitable for use as a conn_id. | 625941c0cad5886f8bd26f49 |
def do_restart(request): <NEW_LINE> <INDENT> if request.user.is_staff: <NEW_LINE> <INDENT> reload_method = get_auto_reload_method() <NEW_LINE> reload_log = get_auto_reload_log() <NEW_LINE> reload_time = get_auto_reload_time() <NEW_LINE> command = "echo no script" <NEW_LINE> if reload_method == 'test': <NEW_LINE> <INDEN... | * "test" for a django instance (this do a touch over settings.py for reload)
* "apache"
* "httpd"
* "wsgi"
* "restart_script <script_path_name>" | 625941c0fff4ab517eb2f3a9 |
def test_convert_project(self): <NEW_LINE> <INDENT> result = convert_project(self.session, 'hf2') <NEW_LINE> assert_equals(result, {'id':3, 'type':'Project'}) <NEW_LINE> assert_raises(GrenadeValidationError, convert_project, self.session, 'mm4') | Test that the project converter transforms the supplied test data correctly.
.. versionadded:: v00_03_00
.. versionchanged:: 0.11.0
Update to use nose asserts statements. | 625941c0eab8aa0e5d26dac6 |
def set_roles(self): <NEW_LINE> <INDENT> self.roles = [ Role.objects.create(type='security'), Role.objects.create(type='audit', rid=15), Role.objects.create(type='data') ] | Add custom roles to self. | 625941c076d4e153a657ea9f |
def pc_noutput_items_var(self): <NEW_LINE> <INDENT> return _filter_swig.interp_fir_filter_scc_sptr_pc_noutput_items_var(self) | pc_noutput_items_var(interp_fir_filter_scc_sptr self) -> float | 625941c08a349b6b435e80e3 |
def sarsa(env, gamma, n_episode, alpha): <NEW_LINE> <INDENT> n_action = env.action_space.n <NEW_LINE> Q = defaultdict(lambda: torch.zeros(n_action)) <NEW_LINE> for episode in range(n_episode): <NEW_LINE> <INDENT> state = env.reset() <NEW_LINE> is_done = False <NEW_LINE> action = epsilon_greedy_policy(state, Q) <NEW_LIN... | Obtain the optimal policy with on-policy SARSA algorithm
@param env: OpenAI Gym environment
@param gamma: discount factor
@param n_episode: number of episodes
@return: the optimal Q-function, and the optimal policy | 625941c066656f66f7cbc119 |
def test_dtypes(self): <NEW_LINE> <INDENT> for dtype in self.supported_dtypes: <NEW_LINE> <INDENT> result = extrema.local_maxima(self.image.astype(dtype)) <NEW_LINE> assert result.dtype == np.bool <NEW_LINE> assert_equal(result, self.expected_default) | Test results with default configuration for all supported dtypes. | 625941c0796e427e537b0533 |
def _compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None): <NEW_LINE> <INDENT> if taxes and taxes[0].company_id.tax_calculation_rounding_method[:7] == 'swedish': <NEW_LINE> <INDENT> if not precision: <NEW_LINE> <INDENT> precision = self.pool.get('decimal.precision' ).precision... | Using swedish rounding we want to keep standard global precision
so we add precision to do global computation | 625941c07d43ff24873a2c0e |
def loc_pref(r_loc, s_loc, loc_fidelity=0, n_reg=1): <NEW_LINE> <INDENT> loc_pref = 0 <NEW_LINE> if loc_fidelity > 0: <NEW_LINE> <INDENT> rreg = region(r_loc, n_reg=n_reg) <NEW_LINE> sreg = region(s_loc, n_reg=n_reg) <NEW_LINE> loc_pref = math.exp(-np.abs(rreg - sreg)) <NEW_LINE> <DEDENT> if loc_fidelity > 1: <NEW_LINE... | returns the location-based preference between a requester and supplier
for a commodity | 625941c0d18da76e23532443 |
def test_pass(self): <NEW_LINE> <INDENT> with raises(NotImplementedError): <NEW_LINE> <INDENT> mol.occupied_per_atom(self.bas) | Contains atom Z=37, which is not implemented | 625941c07cff6e4e811178f5 |
def mark_regions_image(self, image, stats): <NEW_LINE> <INDENT> return image | Creates a new image with computed stats
takes as input
image: a list of pixels in a region
stats: stats regarding location and area
returns: image marked with center and area | 625941c0ac7a0e7691ed4040 |
def __getstate__(self): <NEW_LINE> <INDENT> state = super(ExecComp, self).__getstate__() <NEW_LINE> state['codes'] = None <NEW_LINE> return state | Return dict representing this container's state. | 625941c08e05c05ec3eea2e2 |
def _load(self) -> None: <NEW_LINE> <INDENT> with open(self._filename, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> if '#' in line: <NEW_LINE> <INDENT> line, _ = line.split('#', 1) <NEW_LINE> <DEDENT> if '=' in line: <NEW_LINE> <INDENT> key, val = map(lambda s: s.strip() , line.split('=', 1)) <NEW_... | Load the config file. | 625941c04f88993c3716bfd9 |
def set_mode(self, on_done, **kwargs): <NEW_LINE> <INDENT> mode = util.input_choice(kwargs, 'mode', ['latching', 'momentary_a', 'momentary_b', 'momentary_c']) <NEW_LINE> if mode is None: <NEW_LINE> <INDENT> LOG.error("Invalid mode.") <NEW_LINE> on_done(False, 'Invalid mode.', None) <NEW_LINE> return <NEW_LINE> <DEDENT>... | Set momentary seconds.
Set the momentary mode
Args:
kwargs: Key=value pairs of the flags to change.
on_done: Finished callback. This is called when the command has
completed. Signature is: on_done(success, msg, data) | 625941c0097d151d1a222dcb |
def talk_to(self, person): <NEW_LINE> <INDENT> if type(person) != str: <NEW_LINE> <INDENT> print('Person has to be a string.') <NEW_LINE> <DEDENT> elif person in [character.name for character in self.place.characters.values()]: <NEW_LINE> <INDENT> current_person = self.place.characters[person] <NEW_LINE> print(current_... | Talk to person if person is at player's current place.
>>> john = Character('John', 'Have to run for lecture!')
>>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [john], [])
>>> me = Player('player', sather_gate)
>>> me.talk_to(john)
Person has to be a string.
>>> me.talk_to('John')
John says: Have to r... | 625941c0d7e4931a7ee9de8c |
def _test(self): <NEW_LINE> <INDENT> pass | These tests are not useful as documentation, but are here to ensure
everything works as expected. The following was broken, now fixed.
>>> from fipy import *
>>> mesh = SphericalUniformGrid1D(nx=3., dx=1.)
>>> var = CellVariable(mesh=mesh)
>>> var.constrain(0., where=mesh.facesRight)
>>> DiffusionT... | 625941c0d6c5a10208143fb8 |
def set_direction(self, direction): <NEW_LINE> <INDENT> if type(direction) is not int: <NEW_LINE> <INDENT> raise HacInvalidTypeException( "Projectile.set_direction " "requires an int from the Constants module as" "direction." ) <NEW_LINE> <DEDENT> self.model = self.directional_model(direction) <NEW_LINE> self.animation... | Set the direction of a projectile
This method will set a UnidirectionalActuator with the direction.
It will also take care of updating the model and animation for the given
direction if they are specified.
:param direction: A direction from the Constants module.
:type direction: int
Example::
fireball.set_direc... | 625941c0ff9c53063f47c164 |
def get_blob(self, format, compression=None, quality=None, factory=None): <NEW_LINE> <INDENT> blob = io.get_blob(self, format, compression, quality) <NEW_LINE> if factory: <NEW_LINE> <INDENT> blob = factory(blob) <NEW_LINE> <DEDENT> return blob | Return a blob representing an image
:param format: format of the output such as :term:`JPEG`
:type format: ``str``
:param compression: compression supported by format
:type compression: :class:`pystacia.lazyenum.EnumValue`
:param quality: output quality
:rtype: ``str`` (Python 2.x) / ``bytes`` (Python 3.x)
Returns bl... | 625941c0167d2b6e31218b05 |
def rowViewportPosition(self, p_int): <NEW_LINE> <INDENT> return 0 | rowViewportPosition(self, int) -> int | 625941c04c3428357757c299 |
def get_key_list(self) -> list: <NEW_LINE> <INDENT> return self.__key_column.list_value() | Get the list of key values. | 625941c03617ad0b5ed67e68 |
def RemoveTopologyCategory(self, topologyFullPath='', categoryName=''): <NEW_LINE> <INDENT> return self.generateAPIRequest( OrderedDict([('method_name', 'RemoveTopologyCategory'), ('topologyFullPath', topologyFullPath), ('categoryName', categoryName)])) | Removes a category from given topology.
:param str topologyFullPath: Specify the topology we want to remove the given category from.
:param str categoryName: Specify the category's name which we want to remove.
:rtype: str | 625941c082261d6c526ab40c |
@remoteserviceHandle('gate') <NEW_LINE> def get_role_list_811(data, player): <NEW_LINE> <INDENT> response = GuildRoleListProto() <NEW_LINE> m_g_id = player.guild.g_id <NEW_LINE> if m_g_id == 0: <NEW_LINE> <INDENT> response.result = False <NEW_LINE> response.message = "没有公会" <NEW_LINE> return response.SerializeToString(... | 角色列表 | 625941c056b00c62f0f145c8 |
def __init__(self): <NEW_LINE> <INDENT> self.host = "https://api.phaxio.com/v2" <NEW_LINE> self.api_client = None <NEW_LINE> self.temp_folder_path = None <NEW_LINE> self.api_key = {} <NEW_LINE> self.api_key_prefix = {} <NEW_LINE> self.username = "" <NEW_LINE> self.password = "" <NEW_LINE> self.logger = {} <NEW_LINE> se... | Constructor | 625941c097e22403b379cf09 |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkImagePython.itkImageD2_GetPointer(self) | GetPointer(self) -> itkImageD2 | 625941c07b180e01f3dc4771 |
def lock(name, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): <NEW_LINE> <INDENT> ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} <NEW_LINE> conn_kwargs = {'profile': profile, 'scheme... | Block state execution until you are able to get the lock (or hit the timeout) | 625941c015baa723493c3ee3 |
def test_case_04_legal_triangle(self): <NEW_LINE> <INDENT> self.__assert_not_equal_test_case([(4, 4, 8), (4, 5, 8)], 'NotATriangle') | Verify that the sides form a legal triangle (Triangle Inequality) R3.1 | 625941c024f1403a92600ad8 |
def test_get_resource(self): <NEW_LINE> <INDENT> print('(' + self.test_get_resource.__name__ + ')', self.test_get_resource.__doc__) <NEW_LINE> resource = self.connection.get_resource(VALID_RESOURCE_IDS[0]) <NEW_LINE> self.assertDictContainsSubset(resource, VALID_RESOURCES[0]) <NEW_LINE> resource = self.connection.get_r... | Test get_resource with id 1 and 4 | 625941c0d486a94d0b98e0b5 |
def peek(self): <NEW_LINE> <INDENT> if len(self.items) > 0: <NEW_LINE> <INDENT> return self.items[len(self.items)-1] <NEW_LINE> <DEDENT> return None | Return the data at the top of the stack | 625941c063b5f9789fde7055 |
def _extract_differences(self, replay): <NEW_LINE> <INDENT> if replay.double_time: <NEW_LINE> <INDENT> time_coefficient = 1000 * 2 / 3 <NEW_LINE> <DEDENT> elif replay.half_time: <NEW_LINE> <INDENT> time_coefficient = 1000 * 4 / 3 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time_coefficient = 1000 <NEW_LINE> <DEDENT> ... | Extract the time and position differences for each hit object.
Parameters
----------
replay : Replay
The replay to get differences for.
Returns
-------
differences : np.ndarray
An array of shape (len(hit_objects), 2) where the first column
is the time offset in milliseconds and the second column is the
... | 625941c029b78933be1e561f |
def complexidade_sentenca(texto): <NEW_LINE> <INDENT> sentencas = separa_sentencas(texto) <NEW_LINE> numero_frases = 0 <NEW_LINE> '''laço que lê as sentenças e cria um array de frases pra cada sentença''' <NEW_LINE> for sentenca in sentencas: <NEW_LINE> <INDENT> frases = separa_frases(sentenca) <NEW_LINE> '''var que va... | array recebendo lista de sentencas | 625941c0b57a9660fec337f1 |
def calc_normal_equation_fit(xvec, yvec): <NEW_LINE> <INDENT> xlen = len(xvec) <NEW_LINE> assert xlen >= 3 and len(yvec) == xlen, 'xvec and yvec should have the same length. However, len(xvec)=%i, len(yvec)=%i.' % (xlen,len(yvec)) <NEW_LINE> xvec = np.matrix(xvec) <NEW_LINE> xvec = xvec.transpose() <NEW_LINE> unitVec ... | Computes polynomial 1st degree fit
using normal equation. | 625941c0498bea3a759b9a1f |
def skip_block(self): <NEW_LINE> <INDENT> for line in self.config_fd: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if line == '}': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> raise SyntaxError('skipped block does not end with "}"') | skip configuration block
| 625941c0009cb60464c63323 |
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.display_menu() <NEW_LINE> choice = input("Enter an option: ") <NEW_LINE> action = self.choices.get(choice) <NEW_LINE> if action: <NEW_LINE> <INDENT> action() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("{0} is not a valid choice".format(cho... | Display the menu and repsond to choices. | 625941c0a8370b7717052810 |
def __init__( self, source_workdir: str, dest_workdir: str = "", prefix: dict = "mirror", ) -> None: <NEW_LINE> <INDENT> self.source_workdir = source_workdir <NEW_LINE> self.dest_prefix = prefix <NEW_LINE> self.stats = defaultdict(lambda: 0) <NEW_LINE> self._init_source_repo() <NEW_LINE> self.prior_dest_exists = False ... | Sets up and initializes the mirror session.
Args:
source_workdir (str): Absolute path to the source repo
dest_workdir (str): Absolute path to the destination
repo (optional); if not provided, the destination
working directory will be automatically created
prefix (str): The prefixof the... | 625941c094891a1f4081ba18 |
def predict(image_path, checkpoint_path, idx_to_class, top_k, gpu): <NEW_LINE> <INDENT> image = Image.open(image_path) <NEW_LINE> model = load_checkpoint(checkpoint_path) <NEW_LINE> image = process_image(image) <NEW_LINE> device = "cpu" <NEW_LINE> if (gpu): <NEW_LINE> <INDENT> device = "cuda" <NEW_LINE> <DEDENT> model.... | Predict the class (or classes) of an image using a trained deep learning model.
| 625941c0e64d504609d747b0 |
def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> sprite_sheet = SpriteSheet("player.png") <NEW_LINE> self.image = sprite_sheet.get_image(35, 420, 57, 90).convert() <NEW_LINE> self.x_speed = 0 <NEW_LINE> self.rect = self.image.get_rect() | Constructor function | 625941c026238365f5f0eddb |
def chars_cli(ngrams, weights): <NEW_LINE> <INDENT> with open(ngrams) as f: <NEW_LINE> <INDENT> CharacterModel(map(parse_ngram, f), weights).run_loop() | Start a character model prediction loop.
| 625941c0be383301e01b53fa |
def __import__(module_name, persist_value = True): <NEW_LINE> <INDENT> module = None <NEW_LINE> index = 1 <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> caller = sys._getframe(index) <NEW_LINE> if module_name in caller.f_globals.get("_globals", {}): <NEW_LINE> <INDENT> module = caller.f_globals["_g... | Importer function to be used in the process of importing
a module referred in inverted way.
The optional persist value may be used to control if the
globals/locals reference value must be set in the caller module
in case it has been retrieved from a parent caller (cache).
This function should be used in cases where the... | 625941c0cc40096d615958c1 |
def find_log_decorator(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = func(*args) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(func.__name__ + ' run failed') <NEW_LINE> raise Exception("Cannot find element by [... | 输出Exception的装饰器
:param func:
:return: | 625941c1099cdd3c635f0bcc |
def test_case4(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> po = login(self.driver,self.url) <NEW_LINE> po.open() <NEW_LINE> po.customer() <NEW_LINE> driver.find_element_by_xpath("//input[@name='devCode']").send_keys("867967025947526") <NEW_LINE> driver.find_element_by_xpath("//button[1]").click() <NEW_LI... | 查询设备号
验证查询的设备号是否与查询的一致
| 625941c0fb3f5b602dac3601 |
def scan_for_open_port(port, base_ip_address = None, range_start = 1, range_end = 254, connection_timeout_sec = 0.5, n_workers = 32): <NEW_LINE> <INDENT> if base_ip_address is None: <NEW_LINE> <INDENT> base_ip_address = get_own_ip() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ip_components = base_ip_address.split(".")... | Function used to check connections on a target port, across all ips (#.#.#.start -to- #.#.#.end) using
a base ip (if not provided, uses the ip of the host machine). Returns a list of ips which have
the target port open as well as the base IP address that was used
Inputs:
port -> (Integer) Port to be scanned
... | 625941c1e8904600ed9f1e9b |
def do_ecdsa_sign(G, priv, data, kinv_rp=None): <NEW_LINE> <INDENT> ec_key = _C.EC_KEY_new() <NEW_LINE> _check(_C.EC_KEY_set_group(ec_key, G.ecg)) <NEW_LINE> _check(_C.EC_KEY_set_private_key(ec_key, priv.bn)) <NEW_LINE> if kinv_rp is None: <NEW_LINE> <INDENT> ecdsa_sig = _C.ECDSA_do_sign(data, len(data), ec_key) <NEW_L... | A quick function to ECDSA sign a hash.
Args:
G (EcGroup): the group in which math is done.
priv (Bn): the secret key.
data (str): the string to sign.
kinv_rp (opaque): optional setup parameters.
Returns:
Bn, Bn: The (r, s) signature | 625941c10fa83653e4656f2c |
def test_coordinators_not_equals_each_other(self): <NEW_LINE> <INDENT> daemon_coord = coordinator.Coordinator(self.conf, self.fake_callback) <NEW_LINE> daemon_coord_2 = coordinator.Coordinator(self.conf, self.fake_callback) <NEW_LINE> daemon_coord._im_leader = mock.Mock(return_value=True) <NEW_LINE> daemon_coord_2._im_... | Test cases regarding the __init__ method of the Coordinator class
Test flow:
>>> Create two objects of the class;
>>> Mock method _im_leader to avoid infinite loop in the test;
>>> Test if an object is not equal to each other;
>>> Test if an object is equal to itself; | 625941c13317a56b86939bce |
def authorizeGCS(secretJsonFile): <NEW_LINE> <INDENT> FLOW = flow_from_clientsecrets(secretJsonFile, scope='https://www.googleapis.com/auth/devstorage.read_only') <NEW_LINE> storageFile = 'gcs.dat' <NEW_LINE> http = _authorizeCredentials(FLOW, storageFile) <NEW_LINE> return http | :type secretJsonFile: basestring
:rtype : httplib2.Http | 625941c14428ac0f6e5ba761 |
def apwidth(img, ap_uorder_interp, offsetlim=(-8, 8), ap_npix=10, method='max'): <NEW_LINE> <INDENT> img = np.array(img) <NEW_LINE> ap_width_max = offsetlim[1] - offsetlim[0] + 1 <NEW_LINE> assert 1 <= ap_npix <= ap_width_max <NEW_LINE> ofst, medsnr_lnsum = apoffset_snr(img, ap_uorder_interp, offsetlim=offsetlim) <NEW_... | automatically find ap_width for a given ap_npix | 625941c13617ad0b5ed67e69 |
def start_control(dB): <NEW_LINE> <INDENT> start_menu_display() <NEW_LINE> response = start_user_input() <NEW_LINE> try: <NEW_LINE> <INDENT> return startmenulogic[response](dB) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> print("You have input an invalid instruction. Please enter 1, 2, 3, or 4") <NEW_LINE> ... | Creates the control flow for the start menu. | 625941c199cbb53fe6792b57 |
@when_not('zookeeper.joined') <NEW_LINE> def wait_for_zkjoin(): <NEW_LINE> <INDENT> status_set('waiting', 'Waiting for Zookeeper to become joined') | Wait for Zookeeper | 625941c1c432627299f04bb5 |
def format_data_timestamp(self, msg): <NEW_LINE> <INDENT> self._format_msg = msg <NEW_LINE> return self._format_msg.timestamp | only get timestamp from msg | 625941c1507cdc57c6306c46 |
def validator(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler: <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def check_current_user( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: <NEW_LINE> <INDENT> def output_error(message_id: str, message: str) -> None: <NEW_LIN... | Decorate func. | 625941c11f5feb6acb0c4ac4 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941c126238365f5f0eddc |
def get_metric_schema(resource_root): <NEW_LINE> <INDENT> return call(resource_root.get, METRIC_SCHEMA_PATH, ApiMetricSchema, True) | Get the schema for all of the metrics.
@return: List of metric schema. | 625941c1d6c5a10208143fb9 |
def std(self) -> Union["Series", "DataFrame"]: <NEW_LINE> <INDENT> return super().std() | Calculate rolling standard deviation.
Returns
-------
Series or DataFrame
Returns the same object type as the caller of the rolling calculation.
See Also
--------
Series.rolling : Calling object with Series data.
DataFrame.rolling : Calling object with DataFrames.
Series.std : Equivalent method for Series.
DataFr... | 625941c17cff6e4e811178f6 |
@app.task <NEW_LINE> def create_repo(repository_url, dir_name, to_fetch, user): <NEW_LINE> <INDENT> pth = path.join(REPOS_PATH, dir_name) <NEW_LINE> flag = 0 <NEW_LINE> if not path.exists(pth): <NEW_LINE> <INDENT> rep = Repository() <NEW_LINE> try: <NEW_LINE> <INDENT> if not is_rep(repository_url): <NEW_LINE> <INDENT> ... | Check on valid state repository url and try download it into. | 625941c14428ac0f6e5ba762 |
def test_remove_fields(self): <NEW_LINE> <INDENT> fs = Fieldsets(self.fieldsets) <NEW_LINE> fields = ('ever_taken_arv', 'why_no_arv', 'why_no_arv_other') <NEW_LINE> fs.remove_fields(*fields, section=None) <NEW_LINE> self.assertTrue( fields[0] not in fs.fieldsets[0][1]['fields']) <NEW_LINE> self.assertTrue( fields[1] no... | Asserts removes fields from an existing section.
| 625941c1d268445f265b4ddf |
def uniq(values): <NEW_LINE> <INDENT> uniq_values = [] <NEW_LINE> visited = set() <NEW_LINE> for v in values: <NEW_LINE> <INDENT> if v not in visited: <NEW_LINE> <INDENT> visited.add(v) <NEW_LINE> uniq_values.append(v) <NEW_LINE> <DEDENT> <DEDENT> return uniq_values | Returns uniq values while preserving the order.
| 625941c1d58c6744b4257bd1 |
def _prefix_operator(self, operation: str, expr) -> ast.Call: <NEW_LINE> <INDENT> expr = self.to_python(expr) <NEW_LINE> return self.setlx_function(operation, [expr]) | Turns a prefix operator into a function call
The function translates the given expression and calls the function *operation*
with the translated expression as argument.
e.g. +/[1,2] -> sum([1,2])
Parameters
----------
operation : str
The name of the function
expr :
The Setlx-Expression that is translated and ... | 625941c1dd821e528d63b11b |
def logout(self): <NEW_LINE> <INDENT> if self.logined == True: <NEW_LINE> <INDENT> self.telnet.close() <NEW_LINE> self.logined = False <NEW_LINE> self.status = TELNET_NO_LOGIN <NEW_LINE> del self.telnet <NEW_LINE> self.telnet = None | 退出telent | 625941c1ad47b63b2c509ef1 |
def CAP_Update_FocusObject(self, context): <NEW_LINE> <INDENT> preferences = context.preferences <NEW_LINE> addon_prefs = preferences.addons['Capsule'].preferences <NEW_LINE> bpy.ops.object.select_all(action= 'DESELECT') <NEW_LINE> select_utils.SelectObject(self.object) <NEW_LINE> for area in bpy.context.screen.areas: ... | Focuses the camera to a particular object, ensuring the object is clearly within the camera frame. | 625941c1d53ae8145f87a1e4 |
def convertModel(keras_model): <NEW_LINE> <INDENT> return keras.estimator.model_to_estimator(keras_model) | 将keras的模型转为estimator
:param keras_model: keras模型
:return: estimator | 625941c1e5267d203edcdc10 |
def do_get_bindings(self): <NEW_LINE> <INDENT> greeting, err = run_fish_cmd(" __fish_config_interactive") <NEW_LINE> out, err = run_fish_cmd("__fish_config_interactive; bind") <NEW_LINE> out = out[len(greeting) :] <NEW_LINE> bindings = [] <NEW_LINE> command_to_binding = {} <NEW_LINE> binding_parser = BindingParser() <N... | Get key bindings | 625941c1a05bb46b383ec794 |
def hasPath(self, maze, start, destination): <NEW_LINE> <INDENT> maze_c = zip(*maze) <NEW_LINE> R, C = len(maze), len(maze[0]) <NEW_LINE> queue = collections.deque([tuple(start)]) <NEW_LINE> moves = [(0, 1), (0, -1), (1, 0), (-1, 0)] <NEW_LINE> visited = set() <NEW_LINE> while queue: <NEW_LINE> <INDENT> i, j = queue.po... | :type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: bool | 625941c18e7ae83300e4af3d |
def get(path): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kw): <NEW_LINE> <INDENT> return func(*args, **kw) <NEW_LINE> <DEDENT> wrapper.__method__ = 'GET' <NEW_LINE> wrapper.__route__ = path <NEW_LINE> return wrapper <NEW_LINE> <DEDENT> return dec... | drcorator @get('/path')
:param path:
:return: | 625941c1cc0a2c11143dce01 |
def mean_longitude(longitudes): <NEW_LINE> <INDENT> from scipy.stats import circmean <NEW_LINE> mean_longitude = circmean(np.array(longitudes), low=-180, high=180) <NEW_LINE> mean_longitude = _normalize_longitude(mean_longitude) <NEW_LINE> return mean_longitude | Compute sample mean longitude, assuming longitude in degrees from -180 to
180.
>>> lons = (-170.5, -178.3, 166)
>>> np.mean(lons) # doctest: +SKIP
-60.933
>>> mean_longitude(lons) # doctest: +ELLIPSIS
179.08509...
:type longitudes: :class:`~numpy.ndarray` (or list, ..)
:param longitudes: Geographical longitude valu... | 625941c107d97122c41787f7 |
def incr_float(self, key, amount=1.0): <NEW_LINE> <INDENT> if not isinstance(amount, float): <NEW_LINE> <INDENT> raise TypeException(u'类型错误') <NEW_LINE> <DEDENT> self.database.hincrbyfloat(self.cache_key, key, amount) | 增加指定值
:param key:
:param amount:
:return: | 625941c14e696a04525c93bd |
def execute_cec_command(self, command, new_line=True): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> self.cec_logger.debug('> %s', command.rstrip('\n ')) <NEW_LINE> self.cecclient.stdin.write(command) <NEW_LINE> if new_line: <NEW_LINE> <INDENT> self.cecclient.stdin.write('\n') <NEW_LINE> <DEDENT> self.cecclient.stdin.f... | write a command to stdin of cec-client | 625941c19b70327d1c4e0d45 |
def write(self, item): <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise Exception('Write to a pipe that was already closed') <NEW_LINE> <DEDENT> self.notFull.acquire() <NEW_LINE> self.mutex.acquire() <NEW_LINE> self.contents.append(item) <NEW_LINE> self.mutex.release() <NEW_LINE> self.notEmpty.release() | Blocking write | 625941c1379a373c97cfaab4 |
def endMyTurn(self): <NEW_LINE> <INDENT> global DEBUG <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> print("Ending my turn") | End my turn, yield to someone else | 625941c16e29344779a62585 |
def __init__(cls, *args, **_): <NEW_LINE> <INDENT> super().__init__(*args) | Initializer
It just calls the initializer in the base class with all keyword
arguments dropped. | 625941c1656771135c3eb7dd |
def directeur(self): <NEW_LINE> <INDENT> return copy.copy(self.vecteur) | retourne une copie du vecteur directeur | 625941c1711fe17d825422e1 |
def set_user_env(reg, parent=None): <NEW_LINE> <INDENT> reg = listdict2envdict(reg) <NEW_LINE> types = dict() <NEW_LINE> key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") <NEW_LINE> for name in reg: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x, types[name] = winreg.QueryValueEx(key, name) <NEW_LINE> <DED... | Set HKCU (current user) environment variables | 625941c1460517430c3940fb |
def __init__( self, **kwargs): <NEW_LINE> <INDENT> for argName, argVal in kwargs.items(): <NEW_LINE> <INDENT> if argName == 'maltparser_dir': <NEW_LINE> <INDENT> self.maltparser_dir = argVal <NEW_LINE> <DEDENT> elif argName == 'model_name': <NEW_LINE> <INDENT> self.model_name = argVal <NEW_LINE> <DEDENT> elif argName =... | Initializes MaltParser's wrapper.
Parameters
-----------
maltparser_dir : str
Directory that contains Maltparser jar file and model file;
This directory is also used for storing temporary files, so
writing should be allowed in it;
model_name : str
Name of the Maltparser's model;
maltparser_... | 625941c16fb2d068a760f00c |
def get_interfaces_counters(self): <NEW_LINE> <INDENT> counters = {} <NEW_LINE> interface_count = len(self.get_interfaces()) <NEW_LINE> command_counters = "show packet ports 1-{}".format(interface_count) <NEW_LINE> output_counter = self._send_command(command_counters) <NEW_LINE> raw_counters = textfsm_extractor(self, "... | Return interface counters and errors.
'tx_errors': int,
'rx_errors': int,
'tx_discards': int,
'rx_discards': int,
'tx_octets': int,
'rx_octets': int,
'tx_unicast_packets': int,
'rx_unicast_packets': int,
'tx_multicast_packets': int,
'rx_multicast_packets': int,
'tx_broadcast_packets': int,
'rx_broadcast_packets': int,
... | 625941c1ff9c53063f47c165 |
def csi_to_conky(match: re.Match) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> codes= [0 if _=='' else int(_) for _ in match.group(1).split(';')] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print('csi_to_conky called with no group match', file=sys.stderr) <NEW_LINE> return match.group(0) <NEW_LIN... | Converts the received ansi code to conky code ${color}
This function must be called as repl in re.sub(pattern, repl, string) for instance.
The pattern parameter must match the whole ANSI sequence, and capture one group which is the list of parametres between [ and m].
Example:
converted=re.sub('\[([0-9;]... | 625941c1a219f33f346288dd |
def read_info(): <NEW_LINE> <INDENT> scope = {} <NEW_LINE> version_file = os.path.join(THIS_DIR, "physt", "version.py") <NEW_LINE> with open(version_file, "r") as f: <NEW_LINE> <INDENT> exec(f.read(), scope) <NEW_LINE> <DEDENT> return scope | Single source of version number and other info.
Inspiration:
- https://packaging.python.org/guides/single-sourcing-package-version/
- https://github.com/psf/requests/blob/master/setup.py | 625941c1379a373c97cfaab5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.