code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_locs(self, locs): <NEW_LINE> <INDENT> self.locs = locs <NEW_LINE> if len(self.locs) > 0: <NEW_LINE> <INDENT> vmin, vmax = self.axis.get_view_interval() <NEW_LINE> d = abs(vmax - vmin) <NEW_LINE> if self._useOffset: <NEW_LINE> <INDENT> self._compute_offset() <NEW_LINE> <DEDENT> self._set_orderOfMagnitude(d) <NEW_LINE> self._set_format(vmin, vmax) | Set the locations of the ticks. | 625941c27cff6e4e8111792e |
def load_data_for_datacenter(self, datacenter): <NEW_LINE> <INDENT> if self.config.bulk_load == 'true': <NEW_LINE> <INDENT> nodes = self.inmemory_nodes <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index, nodes = self.consul_api.catalog.nodes(dc=datacenter) <NEW_LINE> <DEDENT> for node in nodes: <NEW_LINE> <INDENT> self.add_node_to_map(self.nodes_by_datacenter, datacenter, node) <NEW_LINE> self.load_data_for_node(node['Node'], datacenter) | processes all the nodes in a particular datacenter | 625941c27b25080760e39402 |
def add_vertex(self, vertex): <NEW_LINE> <INDENT> if isinstance(vertex, str) or isinstance(vertex, unicode): <NEW_LINE> <INDENT> return self.execute("ADDV", code=vertex) <NEW_LINE> <DEDENT> raise TypeError( 'Vertices should be a code or a list of codes. Got {}'.format( type(vertex) ) ) | Add a vertex to solver | 625941c273bcbd0ca4b2c01e |
def cech(S, R): <NEW_LINE> <INDENT> vr = dionysus.fill_rips(np.array(S), 2, R * 2) <NEW_LINE> vr_complex = [list(s) for s in vr if len(s) <= 3] <NEW_LINE> ch_complex = [] <NEW_LINE> for simplex in vr_complex: <NEW_LINE> <INDENT> s_points = [tuple(S[x]) for x in simplex] <NEW_LINE> mb = miniball.Miniball(s_points) <NEW_LINE> c = mb.center() <NEW_LINE> r = np.sqrt(mb.squared_radius()) <NEW_LINE> if r < R: <NEW_LINE> <INDENT> ch_complex.append(simplex) <NEW_LINE> <DEDENT> <DEDENT> result = defaultdict(list) <NEW_LINE> for s in ch_complex: <NEW_LINE> <INDENT> dim = len(s) - 1 <NEW_LINE> result[dim].append(tuple(s)) <NEW_LINE> <DEDENT> return result | Computes the cech complex for the given point cloud S with radius parameter R
:param S: list of points
:param R: radius parameter for the complex
:return: dictionary: dimension -> list of simplices (dionysus objects) | 625941c231939e2706e4ce15 |
def test_set_tuple(): <NEW_LINE> <INDENT> context = Context({'ctx1': 'ctxvalue1', 'ctx2': 'ctxvalue2', 'ctx3': 'ctxvalue3', 'set': { 'output': ('k1', 'k2', '{ctx3}', True, False, 44) }}) <NEW_LINE> pypyr.steps.set.run_step(context) <NEW_LINE> output = context['output'] <NEW_LINE> assert output[0] == 'k1' <NEW_LINE> assert output[1] == 'k2' <NEW_LINE> assert output[2] == 'ctxvalue3' <NEW_LINE> assert output[3] <NEW_LINE> assert not output[4] <NEW_LINE> assert output[5] == 44 | Simple tuple. | 625941c230bbd722463cbd6c |
def rreplace(s: str, old: str, new: str, occurrence: int) -> str: <NEW_LINE> <INDENT> li = s.rsplit(old, occurrence) <NEW_LINE> return new.join(li) | Replace first ocurrence from back of string.
:param s:
:param old:
:param new:
:param occurrence:
:return: | 625941c24527f215b584c401 |
def answer(self, answer): <NEW_LINE> <INDENT> self.__out__(str(answer)) | Anwer client
Answer something to the user
Input:
answer: str | 625941c2187af65679ca50c6 |
def import_voc_list(self, fname='HSK_Level_5.txt'): <NEW_LINE> <INDENT> hsk_data = pd.read_csv(fname) <NEW_LINE> for opt in [SCORE_ID, FAV_HDR_ID]: <NEW_LINE> <INDENT> if opt not in hsk_data.columns: <NEW_LINE> <INDENT> print('Create {} column as it didn\'t exist'.format(opt)) <NEW_LINE> hsk_data[opt] = 0 <NEW_LINE> <DEDENT> <DEDENT> self.voc_list = hsk_data | this function loads the vocabulary list from a given csv file
it expects the following format from the file :
'Order','HSK Level-Order','Word','Pronunciation','Definition','score'
It will return an array of array ignoring the first 2 columns | 625941c215fb5d323cde0ab5 |
def __init__(self, trans_model, ctx_dep, lex_fst, disambig_syms, opts): <NEW_LINE> <INDENT> super(TrainingGraphCompiler, self).__init__( trans_model, ctx_dep, lex_fst, disambig_syms, opts) <NEW_LINE> self._trans_model = trans_model <NEW_LINE> self._ctx_dep = ctx_dep <NEW_LINE> self._lex_fst = lex_fst | Args:
trans_model (TransitionModel): Transition model `H`.
ctx_dep (ContextDependency): Context dependency model `C`.
lex_fst (StdVectorFst): Lexicon `L`.
disambig_syms (List[int]): Disambiguation symbols.
opts (TrainingGraphCompilerOptions): Compiler options. | 625941c273bcbd0ca4b2c01f |
def histogram(self, axis, values, xmin, xmax, step, xlabel, ylabel): <NEW_LINE> <INDENT> gc_min, gc_max = 20, 80 <NEW_LINE> gc_step = 2 <NEW_LINE> axis.hist(values, bins=range(gc_min, gc_max, gc_step), color=(0.5, 0.5, 0.5)) <NEW_LINE> axis.set_xlabel('% GC') <NEW_LINE> axis.set_ylabel('# scaffolds (out of %d)' % len(values)) <NEW_LINE> axis.set_xlim([gc_min, gc_max]) <NEW_LINE> self.prettify(axis) | Create histogram.
Parameters
----------
axis : matplotlib.axis
Axis on which to render histogram.
values : iterable
Values from which to create histogram.
xmin : float
Minimum bin value.
xmax : float
Maximum bin value.
step : float
Size of bin.
xlabel : str
Label for x-axis.
ylabel : str
Label for y-axis. | 625941c28c0ade5d55d3e961 |
def test_message(self): <NEW_LINE> <INDENT> self.client.part('#framewirc', message='Leeroy Jenkins!') <NEW_LINE> expected = b'PART #framewirc :Leeroy Jenkins!\r\n' <NEW_LINE> self.client.connection.send.assert_called_with(expected) | If provided with a parting message, pass it on. | 625941c24a966d76dd550fb6 |
def test_cursor_dictionary_buf(self): <NEW_LINE> <INDENT> cur_pure = self.cnx_pure.cursor(dictionary=True, buffered=True) <NEW_LINE> cur_cext = self.cnx_cext.cursor(dictionary=True, buffered=True) <NEW_LINE> self._test_fetchone(cur_pure, cur_cext) <NEW_LINE> self._test_fetchmany(cur_pure, cur_cext) <NEW_LINE> self._test_fetch_fetchall(cur_pure, cur_cext) <NEW_LINE> cur_pure.close() <NEW_LINE> cur_cext.close() | Test results from cursor buffered are the same in pure or c-ext | 625941c296565a6dacc8f674 |
def set_recharge(self, recharge): <NEW_LINE> <INDENT> self.__recharge = recharge | It set the value of the attribute 'recharge'.
Represents the number of ms required to recharge the unit
for an attack.
Args:
recharge: the value of the recharge. | 625941c20fa83653e4656f64 |
def delete_group(self, context, group, volumes): <NEW_LINE> <INDENT> if not volume_utils.is_group_a_cg_snapshot_type(group): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> LOG.info("Deleting Group") <NEW_LINE> model_update = {'status': fields.GroupStatus.DELETED} <NEW_LINE> error_statuses = [fields.GroupStatus.ERROR, fields.GroupStatus.ERROR_DELETING] <NEW_LINE> volumes_model_update = [] <NEW_LINE> for volume in volumes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._delete_volume(volume['provider_id']) <NEW_LINE> update_item = {'id': volume['id'], 'status': 'deleted'} <NEW_LINE> volumes_model_update.append(update_item) <NEW_LINE> <DEDENT> except exception.VolumeBackendAPIException as err: <NEW_LINE> <INDENT> update_item = {'id': volume['id'], 'status': 'error_deleting'} <NEW_LINE> volumes_model_update.append(update_item) <NEW_LINE> if model_update['status'] not in error_statuses: <NEW_LINE> <INDENT> model_update['status'] = 'error_deleting' <NEW_LINE> <DEDENT> LOG.error("Failed to delete the volume %(vol)s of group. " "Exception: %(exception)s.", {'vol': volume['name'], 'exception': err}) <NEW_LINE> <DEDENT> <DEDENT> return model_update, volumes_model_update | Deletes a group.
:param context: the context of the caller.
:param group: the group object.
:param volumes: a list of volume objects in the group.
:returns: model_update, volumes_model_update
ScaleIO will delete the volumes of the CG. | 625941c2de87d2750b85fd39 |
def ocs_unlock (lock): <NEW_LINE> <INDENT> lock_bin = get_lock_library () <NEW_LINE> lock_id = c_int (int (lock)) <NEW_LINE> status = lock_bin.ocs_unlock (lock_id) <NEW_LINE> if (status != 0): <NEW_LINE> <INDENT> ocslog.log_error (status, "Failed to release {0} lock.".format (lock)) | Release an OCS system lock.
:param lock: The enumeration for the lock to release. | 625941c2e64d504609d747e8 |
def test_provision_gt_compensable(self): <NEW_LINE> <INDENT> p = Provision(self.vendor.id, provision_function="""(* 2 (.count sold_and_compensated))""") <NEW_LINE> self.assertTrue(p.has_provision, p) <NEW_LINE> self.assertEqual(Decimal("0.00"), p.provision_fix, p) <NEW_LINE> self.assertEqual(Decimal("-20.00"), p.provision, p) | Provision is higher than average item price -> compensation causes actually vendor to pay. | 625941c28c0ade5d55d3e962 |
def test_nodes(graph): <NEW_LINE> <INDENT> graph.add_node('blah') <NEW_LINE> graph.add_node('whamo') <NEW_LINE> graph.add_node('zeno') <NEW_LINE> assert sorted(graph.nodes()) == ['blah', 'whamo', 'zeno'] | Test nodes returns list of all nodes in graph. | 625941c28a349b6b435e811c |
def test_void_invoice(self): <NEW_LINE> <INDENT> pass | Test case for void_invoice
Voids the invoice specified by the invoice identifier parameter. | 625941c224f1403a92600b11 |
def GetDigestFromName(image_name): <NEW_LINE> <INDENT> tag_or_digest = GetDockerImageFromTagOrDigest(image_name) <NEW_LINE> if isinstance(tag_or_digest, docker_name.Digest): <NEW_LINE> <INDENT> return tag_or_digest <NEW_LINE> <DEDENT> def ResolveV2Tag(tag): <NEW_LINE> <INDENT> with v2_image.FromRegistry( basic_creds=CredentialProvider(), name=tag, transport=http.Http()) as v2_img: <NEW_LINE> <INDENT> if v2_img.exists(): <NEW_LINE> <INDENT> return v2_img.digest() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def ResolveV22Tag(tag): <NEW_LINE> <INDENT> with v2_2_image.FromRegistry( basic_creds=CredentialProvider(), name=tag, transport=http.Http(), accepted_mimes=v2_2_docker_http.SUPPORTED_MANIFEST_MIMES) as v2_2_img: <NEW_LINE> <INDENT> if v2_2_img.exists(): <NEW_LINE> <INDENT> return v2_2_img.digest() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def ResolveManifestListTag(tag): <NEW_LINE> <INDENT> with docker_image_list.FromRegistry( basic_creds=CredentialProvider(), name=tag, transport=http.Http()) as manifest_list: <NEW_LINE> <INDENT> if manifest_list.exists(): <NEW_LINE> <INDENT> return manifest_list.digest() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> sha256 = ( ResolveManifestListTag(tag_or_digest) or ResolveV22Tag(tag_or_digest) or ResolveV2Tag(tag_or_digest)) <NEW_LINE> if not sha256: <NEW_LINE> <INDENT> raise InvalidImageNameError( '[{0}] is not a valid name. Expected tag in the form "base:tag" or ' '"tag" or digest in the form "sha256:<digest>"'.format(image_name)) <NEW_LINE> <DEDENT> return docker_name.Digest('{registry}/{repository}@{sha256}'.format( registry=tag_or_digest.registry, repository=tag_or_digest.repository, sha256=sha256)) | Gets a digest object given a repository, tag or digest.
Args:
image_name: A docker image reference, possibly underqualified.
Returns:
a docker_name.Digest object.
Raises:
InvalidImageNameError: If no digest can be resolved. | 625941c2656771135c3eb815 |
def get_url(self): <NEW_LINE> <INDENT> return self._url | Get URL for this report | 625941c2dd821e528d63b153 |
def full_like( a: DNDarray, fill_value: Union[int, float], dtype: Type[datatype] = types.float32, split: Optional[int] = None, device: Optional[Device] = None, comm: Optional[Communication] = None, order: str = "C", ) -> DNDarray: <NEW_LINE> <INDENT> return __factory_like(a, dtype, split, full, device, comm, fill_value=fill_value, order=order) | Return a full :class:`~heat.core.dndarray.DNDarray` with the same shape and type as a given array.
Parameters
----------
a : DNDarray
The shape and data-type of ``a`` define these same attributes of the returned array.
fill_value : scalar
Fill value.
dtype : datatype, optional
Overrides the data type of the result.
split: int or None, optional
The axis along which the array is split and distributed; ``None`` means no distribution.
device : str or Device, optional
Specifies the :class:`~heat.core.devices.Device` the array shall be allocated on, defaults to globally set
default device.
comm: Communication, optional
Handle to the nodes holding distributed parts or copies of this array.
order: str, optional
Options: ``'C'`` or ``'F'``. Specifies the memory layout of the newly created array. Default is ``order='C'``,
meaning the array will be stored in row-major order (C-like). If ``order=‘F’``, the array will be stored in
column-major order (Fortran-like).
Raises
------
NotImplementedError
If order is one of the NumPy options ``'K'`` or ``'A'``.
Examples
--------
>>> x = ht.zeros((2, 3,))
>>> x
DNDarray([[0., 0., 0.],
[0., 0., 0.]], dtype=ht.float32, device=cpu:0, split=None)
>>> ht.full_like(x, 1.0)
DNDarray([[1., 1., 1.],
[1., 1., 1.]], dtype=ht.float32, device=cpu:0, split=None) | 625941c21d351010ab855ac5 |
def getCacheID(self, pycontext=None): <NEW_LINE> <INDENT> pass | getCacheID([, pycontext])
This will produce a hash of the all colorspace definitions, etc.
All external references, such as files used in FileTransforms, etc.,
will be incorporated into the cacheID. While the contents of the files
are not read, the file system is queried for relavent information
(mtime, inode) so that the :py:class:`PyOpenColorIO.Config`'s cacheID
will change when the underlying luts are updated.
If a context is not provided, the current Context will be used. If a
null context is provided, file references will not be taken into
account (this is essentially a hash of :py:method:`PyOpenColorIO.Config.serialize`).
:param pycontext: optional
:type pycontext: object
:return: hash of :py:class:`PyOpenColorIO.Config`
:rtype: string | 625941c201c39578d7e74de4 |
def __call__(self, obj): <NEW_LINE> <INDENT> if not self.pprint: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return repr(obj) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> stream = StringIO() <NEW_LINE> printer = pretty.RepresentationPrinter(stream, self.verbose, self.max_width, self.newline.encode(), singleton_pprinters=self.singleton_printers, type_pprinters=self.type_printers, deferred_pprinters=self.deferred_printers) <NEW_LINE> printer.pretty(obj) <NEW_LINE> printer.flush() <NEW_LINE> return stream.getvalue() | Compute the pretty representation of the object. | 625941c2d268445f265b4e17 |
def build(self,category): <NEW_LINE> <INDENT> sub_tree = '<li>'+str(category[0])+':'+category[1]+':'+str(category[2])+':'+str(1 == category[3]) <NEW_LINE> child_categories = self.get_direct_children(category[0]) <NEW_LINE> sub_sub_tree = '' <NEW_LINE> if child_categories: <NEW_LINE> <INDENT> for category in child_categories: <NEW_LINE> <INDENT> child_tree = self.build(category) <NEW_LINE> sub_sub_tree = sub_sub_tree + child_tree <NEW_LINE> <DEDENT> <DEDENT> sub_tree = sub_tree+'<ul>'+sub_sub_tree+'</ul>'+'</li>' <NEW_LINE> return sub_tree | Build the tree recursively. | 625941c20383005118ecf58d |
def splot(x, y, name='outplot', fmt='-k', xtitle=r'$r$', ytitle=r'$S(R)$'): <NEW_LINE> <INDENT> clf() <NEW_LINE> plot(x, y, fmt) <NEW_LINE> xscale('log') ; yscale('log') <NEW_LINE> xlabel(xtitle) ; ylabel(ytitle) <NEW_LINE> savefig(name+'.png') <NEW_LINE> close('all') | so far plots some quantity S(R) | 625941c260cbc95b062c64eb |
def isPowerOfTwo(self, n: int) -> bool: <NEW_LINE> <INDENT> if n <= 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return n & (n - 1) == 0 | Bit Manipulation
time O(1), space O(1) | 625941c215baa723493c3f1d |
def on_update_toggled(self, renderer, path): <NEW_LINE> <INDENT> iter = self.store.get_iter(path) <NEW_LINE> data = self.store.get_value(iter, LIST_UPDATE_DATA) <NEW_LINE> if data.groups: <NEW_LINE> <INDENT> self.toggle_from_items([item for group in data.groups for item in group.items]) <NEW_LINE> <DEDENT> elif data.group: <NEW_LINE> <INDENT> self.toggle_from_items(data.group.items) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.toggle_from_items([data.item]) | a toggle button in the listview was toggled | 625941c27d43ff24873a2c48 |
@register.function <NEW_LINE> @jinja2.contextfunction <NEW_LINE> def favorites_widget(context, addon, condensed=False): <NEW_LINE> <INDENT> c = dict(context.items()) <NEW_LINE> request = c['request'] <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> is_favorite = addon.id in request.amo_user.favorite_addons <NEW_LINE> faved_class = 'faved' if is_favorite else '' <NEW_LINE> unfaved_text = '' if condensed else _('Add to favorites') <NEW_LINE> faved_text = _('Favorite') if condensed else _('Remove from favorites') <NEW_LINE> add_url = reverse('collections.alter', args=[request.amo_user.username, 'favorites', 'add']) <NEW_LINE> remove_url = reverse('collections.alter', args=[request.amo_user.username, 'favorites', 'remove']) <NEW_LINE> c.update(locals()) <NEW_LINE> t = env.get_template('bandwagon/favorites_widget.html').render(c) <NEW_LINE> return jinja2.Markup(t) | Displays 'Add to Favorites' widget. | 625941c2851cf427c661a4ba |
def __init__(self, root_node): <NEW_LINE> <INDENT> self.root_node = root_node | :param root_node: The root node of the parse tree.
:type root_node: :class:`booleano.operations.core.OperationNode` | 625941c24428ac0f6e5ba79a |
def abort(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._state == CREATED: <NEW_LINE> <INDENT> log.debug("%s not started yet", self) <NEW_LINE> self._state = ABORTED <NEW_LINE> <DEDENT> elif self._state == RUNNING: <NEW_LINE> <INDENT> self._state = ABORTING <NEW_LINE> log.info("Aborting %s", self) <NEW_LINE> self._kill_process() <NEW_LINE> <DEDENT> elif self._state == ABORTING: <NEW_LINE> <INDENT> log.info("Retrying abort %s", self) <NEW_LINE> self._kill_process() <NEW_LINE> <DEDENT> elif self._state == TERMINATED: <NEW_LINE> <INDENT> log.debug("%s has terminated", self) <NEW_LINE> <DEDENT> elif self._state == ABORTED: <NEW_LINE> <INDENT> log.debug("%s was aborted", self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("Invalid state: %s" % self) | Attempt to terminate the child process from another thread.
Does not wait for the child process; the thread running this process
will wait for the process. The caller must not assume that the
operation was aborted when this returns.
May be invoked multiple times.
Raises:
OSError if killing the underlying process failed. | 625941c2566aa707497f4515 |
def getHelpAndVersionStatus(self): <NEW_LINE> <INDENT> helpflag = False <NEW_LINE> versionflag = False <NEW_LINE> for parameter in sys.argv[1:]: <NEW_LINE> <INDENT> if (parameter == "-?" or parameter == "--help"): <NEW_LINE> <INDENT> helpflag = True <NEW_LINE> <DEDENT> if (parameter == "-V" or parameter == "--version"): <NEW_LINE> <INDENT> versionflag = True <NEW_LINE> <DEDENT> <DEDENT> return helpflag, versionflag | function: get help and version information status
input : NA
output: helpflag, versionflag | 625941c299cbb53fe6792b90 |
def get_lookup_a_phone_number(self, phone_number, options=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.info('get_lookup_a_phone_number called.') <NEW_LINE> self.logger.info('Preparing query URL for get_lookup_a_phone_number.') <NEW_LINE> _query_builder = Configuration.base_uri <NEW_LINE> _query_builder += '/v1/lookups/phone/{phone_number}' <NEW_LINE> _query_builder = APIHelper.append_url_with_template_parameters(_query_builder, { 'phone_number': phone_number }) <NEW_LINE> _query_parameters = { 'options': options } <NEW_LINE> _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) <NEW_LINE> _query_url = APIHelper.clean_url(_query_builder) <NEW_LINE> self.logger.info('Preparing headers for get_lookup_a_phone_number.') <NEW_LINE> _headers = { 'accept': 'application/json', 'user-agent': 'messagemedia-lookups-python-sdk-1.0.0' } <NEW_LINE> self.logger.info('Preparing and executing request for get_lookup_a_phone_number.') <NEW_LINE> _request = self.http_client.get(_query_url, headers=_headers) <NEW_LINE> BasicAuth.apply(_request) <NEW_LINE> _context = self.execute_request(_request, name = 'get_lookup_a_phone_number') <NEW_LINE> self.logger.info('Validating response for get_lookup_a_phone_number.') <NEW_LINE> if _context.response.status_code == 404: <NEW_LINE> <INDENT> raise APIException('Number was invalid', _context) <NEW_LINE> <DEDENT> self.validate_response(_context) <NEW_LINE> return APIHelper.json_deserialize(_context.response.raw_body, LookupAPhoneNumberResponse.from_dictionary) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.error(e, exc_info = True) <NEW_LINE> raise | Does a GET request to /v1/lookups/phone/{phone_number}.
Use the Lookups API to find information about a phone number.
A request to the lookups API has the following format:
```/v1/lookups/phone/{phone_number}?options={carrier,type}```
The `{phone_number}` parameter is a required field and should be set
to the phone number to be looked up.
The options query parameter can also be used to request additional
information about the phone number.
By default, a request will only return the `country_code` and
`phone_number` properties in the response.
To request details about the the carrier, include `carrier` as a value
of the options parameter.
To request details about the type, include `type` as a value of the
options parameter. To pass multiple values
to the options parameter, use a comma separated list, i.e.
`carrier,type`.
A successful request to the lookups endpoint will return a response
body as follows:
```json
{
"country_code": "AU",
"phone_number": "+61491570156",
"type": "mobile",
"carrier": {
"name": "Telstra"
}
}
```
Each property in the response body is defined as follows:
- ```country_code``` ISO ALPHA 2 country code of the phone number
- ```phone_number``` E.164 formatted phone number
- ```type``` The type of number. This can be ```"mobile"``` or
```"landline"```
- ```carrier``` Holds information about the specific carrier (if
available)
- ```name``` The carrier's name as reported by the network
Args:
phone_number (string): The phone number to be looked up
options (string, optional): TODO: type description here. Example:
Returns:
LookupAPhoneNumberResponse: Response from the API.
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request. | 625941c24e4d5625662d4383 |
def create_classes(self): <NEW_LINE> <INDENT> classes_name = input('输入要创建的班级名称:').strip() <NEW_LINE> lesson_name = input('输入要关联的课程名称:').strip() <NEW_LINE> if classes_name in self.school_object.school_classes: <NEW_LINE> <INDENT> print('班级已经存在,将自动更新覆盖') <NEW_LINE> self.school_object.add_classes(classes_name,lesson_name) <NEW_LINE> print('已更新班级内容') <NEW_LINE> <DEDENT> elif lesson_name not in self.school_object.school_lesson: <NEW_LINE> <INDENT> print('课程%s不存在'%lesson_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.school_object.add_classes(classes_name,lesson_name) <NEW_LINE> print('已创建班级:%s'%classes_name) <NEW_LINE> <DEDENT> self.school_db.update({self.select_school:self.school_object}) | 创建班级,调用school类的add_classes来创建
:return: | 625941c2bf627c535bc13177 |
def main_loop(self): <NEW_LINE> <INDENT> while not self.done: <NEW_LINE> <INDENT> self.event_loop() <NEW_LINE> self.player.update(self.obstacles) <NEW_LINE> self.screen.fill(BACKGROUND_COLOR) <NEW_LINE> self.obstacles.draw(self.screen) <NEW_LINE> self.player.draw(self.screen) <NEW_LINE> pg.display.update() <NEW_LINE> self.clock.tick(self.fps) <NEW_LINE> self.display_fps() | Our main game loop; I bet you'd never have guessed. | 625941c23c8af77a43ae3747 |
def get_stipple_brush(color): <NEW_LINE> <INDENT> color = wx.Colour( (color.Red() + 1) * 1 // 4, (color.Green() + 1) * 1 // 4, (color.Blue() + 1) * 1 // 4, ) <NEW_LINE> rgb = color.GetRGB() <NEW_LINE> if rgb in stipple_brushes: <NEW_LINE> <INDENT> return stipple_brushes[rgb] <NEW_LINE> <DEDENT> image = wx.Image(16, 16, clear=True) <NEW_LINE> image.InitAlpha() <NEW_LINE> for x in range(image.GetWidth()): <NEW_LINE> <INDENT> for y in range(image.GetHeight()): <NEW_LINE> <INDENT> if False and (2 * x + y) % 16 < 12: <NEW_LINE> <INDENT> image.SetAlpha(x, y, wx.ALPHA_TRANSPARENT) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rgb = (color.Red(), color.Green(), color.Blue()) <NEW_LINE> image.SetRGB(x, y, *rgb) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> brush = wx.Brush(color) <NEW_LINE> brush.SetStipple(wx.Bitmap(image)) <NEW_LINE> stipple_brushes[rgb] = brush <NEW_LINE> return brush | Return the stipple bitmap for the given color. | 625941c21f037a2d8b9461a7 |
def update_xray_structure(self, x=None): <NEW_LINE> <INDENT> if not x: x = self.x <NEW_LINE> if self.refine_transformations: <NEW_LINE> <INDENT> self.ncs_restraints_group_list = nu.update_rot_tran( x=x, ncs_restraints_group_list=self.ncs_restraints_group_list) <NEW_LINE> x_ncs = nu.get_ncs_sites_cart(self).as_double() <NEW_LINE> x_asu = self.refinable_params_one_ncs_to_asu(x_ncs) <NEW_LINE> self.xray_structure.set_sites_cart( sites_cart = flex.vec3_double(x_asu)) <NEW_LINE> <DEDENT> elif self.refine_sites: <NEW_LINE> <INDENT> x_asu = self.refinable_params_one_ncs_to_asu(x) <NEW_LINE> self.xray_structure.set_sites_cart( sites_cart = flex.vec3_double(x_asu)) <NEW_LINE> <DEDENT> elif self.refine_u_iso: <NEW_LINE> <INDENT> x_asu = self.refinable_params_one_ncs_to_asu() <NEW_LINE> self.xray_structure.set_u_iso(values = x_asu) <NEW_LINE> <DEDENT> return self.xray_structure | Update xray_structure with refined parameters, then update
fmodel object with updated xray_structure. | 625941c266656f66f7cbc153 |
def test_decode_inputs_batch_sync(self): <NEW_LINE> <INDENT> response = inputs._decode_inputs_batch_sync({ "0x1": (TEST_CONTRACT_ABI, TEST_CONTRACT_PARAMETERS), "0x2": (TEST_CONTRACT_ABI, TEST_CONTRACT_EVENT_PARAMETERS) }) <NEW_LINE> print(response['0x2']) <NEW_LINE> self.assertSequenceEqual(response, { "0x1": TEST_CONTRACT_DECODED_PARAMETERS, "0x2": TEST_CONTRACT_DECODED_EVENT_PARAMETERS }) | Test decode inputs batch | 625941c229b78933be1e5658 |
def get_prefix(bot, message): <NEW_LINE> <INDENT> prefixes = ['?'] <NEW_LINE> if not message.guild: <NEW_LINE> <INDENT> return '?' <NEW_LINE> <DEDENT> return commands.when_mentioned_or(*prefixes)(bot, message) | A callable Prefix for our bot. This could be edited to allow per server prefixes. | 625941c263b5f9789fde708e |
def PlotError(pf, xx, tacc, vacc, command): <NEW_LINE> <INDENT> if command == 0: <NEW_LINE> <INDENT> xlabel = r"$N_{\rm features}$" <NEW_LINE> <DEDENT> elif command == 1: <NEW_LINE> <INDENT> xlabel = r"${\rm log}_{10}(C)$" <NEW_LINE> <DEDENT> ylabel = r"${\rm Error}$" <NEW_LINE> tlabel = r"${\rm Training}$" <NEW_LINE> vlabel = r"${\rm Validation}$" <NEW_LINE> left = 0.11 <NEW_LINE> right = 0.97 <NEW_LINE> bottom = 0.11 <NEW_LINE> top = 0.97 <NEW_LINE> fig_width_pt = 300. <NEW_LINE> inches_per_pt = 1. / 72.27 <NEW_LINE> fig_width = fig_width_pt * inches_per_pt <NEW_LINE> fig_height = fig_width <NEW_LINE> fig_size = [fig_width, fig_height] <NEW_LINE> params = {'backend': 'ps', 'axes.labelsize': 13, 'font.size': 12, 'legend.fontsize': 12, 'xtick.labelsize': 12, 'ytick.labelsize': 12, 'text.usetex': True, 'figure.figsize': fig_size} <NEW_LINE> py.rcParams.update(params) <NEW_LINE> fig = py.figure(1) <NEW_LINE> py.clf() <NEW_LINE> py.subplots_adjust(left=left, right=right, bottom=bottom, top=top, hspace=0., wspace=0.) <NEW_LINE> py.plot(xx, 1-tacc, "k-", label=tlabel) <NEW_LINE> py.plot(xx, 1-vacc, "r-", label=vlabel) <NEW_LINE> lg = py.legend(loc="best", fancybox=True) <NEW_LINE> lg.draw_frame(False) <NEW_LINE> py.xlabel(xlabel) <NEW_LINE> py.ylabel(ylabel) <NEW_LINE> py.savefig(pf) <NEW_LINE> py.close() <NEW_LINE> print("Error plot saved to " + pf) | Make a plot comparing the training and validation error as a function of the feature set size. | 625941c2377c676e91272152 |
def process_course_and_provider(html, step_detail): <NEW_LINE> <INDENT> body = html.find("div", {"class": "BodyPanel642"}) <NEW_LINE> if body: <NEW_LINE> <INDENT> contents = str(body) <NEW_LINE> if 'No Records Found' in contents: <NEW_LINE> <INDENT> print('No courses found') <NEW_LINE> return <NEW_LINE> <DEDENT> contents = contents.split('<hr class="hrdivider"/>') <NEW_LINE> for content in contents: <NEW_LINE> <INDENT> if 'learningprovider' not in content: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> content_html = beautify(content) <NEW_LINE> content_text_list = list(filter(None, content_html.get_text().split('\n'))) <NEW_LINE> if len(content_text_list) < 2: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> provider_url = content_html.find('a').get('href') <NEW_LINE> provider_detail = content_text_list[0] <NEW_LINE> campus = None <NEW_LINE> try: <NEW_LINE> <INDENT> campus_provider = provider_detail.split(' - ') <NEW_LINE> provider_name = campus_provider[0] <NEW_LINE> campus_name = '' if len(campus_provider) == 1 else campus_provider[1].strip() <NEW_LINE> if campus_name: <NEW_LINE> <INDENT> campus = Campus.objects.get( provider__primary_institution=provider_name, campus__iexact=campus_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> campus = Campus.objects.filter( provider__primary_institution=provider_name )[0] <NEW_LINE> <DEDENT> <DEDENT> except (Campus.DoesNotExist, IndexError): <NEW_LINE> <INDENT> campus = scrap_campus( provider_detail, 'http://ncap.careerhelp.org.za/' + provider_url) <NEW_LINE> <DEDENT> if len(content_text_list) > 2: <NEW_LINE> <INDENT> for course_detail in content_text_list[2:]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> saqa_id = course_detail[ course_detail.lower().find('saqa qualification id'): course_detail.find(',') ].split(':')[1].strip() <NEW_LINE> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> course = Course.objects.get( national_learners_records_database=saqa_id ) <NEW_LINE> <DEDENT> except Course.DoesNotExist: <NEW_LINE> <INDENT> course = get_course_detail_saqa(saqa_id) <NEW_LINE> <DEDENT> if not course: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if course.course_description == 'National Certificate: N1 Engineering Studies': <NEW_LINE> <INDENT> print(course) <NEW_LINE> <DEDENT> print('Add course {}'.format(course.course_description)) <NEW_LINE> if campus and not campus.courses.filter(id=course.id).exists(): <NEW_LINE> <INDENT> campus.courses.add(course) <NEW_LINE> <DEDENT> if not step_detail.course.filter(id=course.id).exists(): <NEW_LINE> <INDENT> step_detail.course.add(course) | Processing course and provider.
:param html: html that found
:type html: str
:param step_detail: step_detail to be used
:type step_detail: StepDetail | 625941c296565a6dacc8f675 |
def download_check_sum(self, checksum_type, origin_file_name): <NEW_LINE> <INDENT> checksum_url = origin_file_name + "." + checksum_type <NEW_LINE> try: <NEW_LINE> <INDENT> return download_string(checksum_url) <NEW_LINE> <DEDENT> except DownloadException: <NEW_LINE> <INDENT> return None | return pre calculated checksum value, only avaiable for remote repos | 625941c27c178a314d6ef405 |
@check_aware_dt('when') <NEW_LINE> def get_sunset_time(latitude_deg, longitude_deg, when): <NEW_LINE> <INDENT> return get_sunrise_sunset_transit(latitude_deg, longitude_deg, when)[1] | Wrapper for get_sunrise_sunset_transit that returns just the sunset time. | 625941c28da39b475bd64f1b |
def test_open_ru_ballance(self, ): <NEW_LINE> <INDENT> if self.report_type == 'open.ru': <NEW_LINE> <INDENT> (mid, aid) = self.make_money_and_account() <NEW_LINE> self.load_data_into_account(aid) <NEW_LINE> deals = self.get_deals() <NEW_LINE> repo_deals = self.get_repo_deals() <NEW_LINE> if self.open_ru_report_type == 'stock': <NEW_LINE> <INDENT> comm = self.open_ru_get_micex_commission(deals, repo_deals) <NEW_LINE> <DEDENT> elif self.open_ru_report_type == 'future': <NEW_LINE> <INDENT> atl = self.get_account_totally_line() <NEW_LINE> comm = self.open_ru_get_forts_comm(atl) <NEW_LINE> <DEDENT> ballance = sum([float(d.getAttribute('deal_sign')) * float(d.getAttribute('price')) * float(d.getAttribute('quantity')) for d in deals]) <NEW_LINE> ballance += sum([float(d.getAttribute('deal_sign')) * float(d.getAttribute('deal_price')) * float(d.getAttribute('quantity')) for d in repo_deals]) <NEW_LINE> ballance += 10000 - comm <NEW_LINE> accs = self.model.list_view_accounts().fetchall() <NEW_LINE> self.assertEqual(1, len(accs)) <NEW_LINE> self.assertAlmostEqual(ballance, accs[0]['current_money']) | rief check if ballance for deals matches for report and database
| 625941c2d268445f265b4e18 |
def SCNW(self, A1, k, coreset_size, is_scaled): <NEW_LINE> <INDENT> A, A3 = self.initializing_data(A1, k) <NEW_LINE> At = np.transpose(A) <NEW_LINE> AtA = np.dot(At, A) <NEW_LINE> num_of_samples = A.shape[0] <NEW_LINE> num_of_channels = A.shape[1] <NEW_LINE> i = np.int(np.floor(min(A.shape[0], coreset_size))) <NEW_LINE> ww = np.zeros((coreset_size, 1)) <NEW_LINE> Z = np.zeros((num_of_channels, num_of_channels)) <NEW_LINE> if is_scaled == 1: <NEW_LINE> <INDENT> epsi = np.power(k / num_of_samples, 1 / 2) <NEW_LINE> X_u = k * np.sqrt(1 / num_of_samples) * np.diag(np.ones(num_of_channels)) <NEW_LINE> X_l = -k * np.sqrt(1 / num_of_samples) * np.diag(np.ones(num_of_channels)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> epsi = np.power(k / coreset_size, 1 / 2) <NEW_LINE> X_u = k * np.diag(np.ones(num_of_channels)) <NEW_LINE> X_l = -k * np.diag(np.ones(num_of_channels)) <NEW_LINE> <DEDENT> delta_u = epsi + 2 * np.power(epsi, 2) <NEW_LINE> delta_l = epsi - 2 * np.power(epsi, 2) <NEW_LINE> j = 1 <NEW_LINE> ind = np.zeros(coreset_size, dtype=np.int) <NEW_LINE> while j < i + 1: <NEW_LINE> <INDENT> X_u = X_u + delta_u * AtA <NEW_LINE> X_l = X_l + delta_l * AtA <NEW_LINE> Z, jj, t = self.single_CNW_iteration(A, At, delta_u, delta_l, X_u, X_l, Z) <NEW_LINE> ww[j - 1] = t <NEW_LINE> ind[j - 1] = jj <NEW_LINE> j = j + 1 <NEW_LINE> <DEDENT> if is_scaled == 1: <NEW_LINE> <INDENT> sqrt_ww = np.sqrt( num_of_samples * epsi * ww / (coreset_size * k)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sqrt_ww = np.sqrt(epsi * ww / k) <NEW_LINE> <DEDENT> weights = sqrt_ww <NEW_LINE> SA0 = np.multiply(weights, A1[ind, :]) <NEW_LINE> return SA0, weights, ind | This function operates the CNW algorithm, exactly as elaborated in Feldman & Ras
inputs:
A: data matrix, n points, each of dimension d.
k: an algorithm parameter which determines the normalization neededand the error given the coreset size.
coreset_size: the maximal coreset size (number of lines inequal to zero) demanded for input.
output:
error: The error between the original data to the CNW coreset.
duration: the duration this CNW operation lasted | 625941c2cc40096d615958fa |
def download(url, target_directory, chunk_size=1024): <NEW_LINE> <INDENT> head_response = requests.head(url) <NEW_LINE> file_name = _derive_file_name(head_response, url) <NEW_LINE> file_path = os.path.join(target_directory, file_name) <NEW_LINE> response = requests.get(url, stream=True) <NEW_LINE> with open(file_path, 'wb') as downloaded_file: <NEW_LINE> <INDENT> for chunk in response.iter_content(chunk_size): <NEW_LINE> <INDENT> if chunk: <NEW_LINE> <INDENT> downloaded_file.write(chunk) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return file_path | Download data source from a remote host.
:param url: URL to the data source.
:param target_directory: import session's directory path to download the data source.
:param chunk_size: data stream's chunk size
:type url: string
:type target_directory: string
:type chunk_size: int
:return: path to the downloaded file
:rtype: string | 625941c25fdd1c0f98dc01dc |
def get(self, request, pk, format=None): <NEW_LINE> <INDENT> data = {} <NEW_LINE> tag = self.get_object(pk=pk) <NEW_LINE> serializer = BookmarkSerializer(tag.bookmark.all(), many=True) <NEW_LINE> data['bookmarks'] = serializer.data <NEW_LINE> data['tag'] = tag.tag <NEW_LINE> return Response(data, status=status.HTTP_200_OK) | Get all URL related to The Tag | 625941c2eab8aa0e5d26db01 |
def load_config(self): <NEW_LINE> <INDENT> dialog = QFileDialog(self) <NEW_LINE> filename = dialog.getOpenFileName( self, "Load settings", QDir.homePath(), "Enigma config (*.json)" )[0] <NEW_LINE> if filename: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__enigma_api.load_from(filename) <NEW_LINE> logging.info('Successfully loaded config from file "%s"', filename) <NEW_LINE> <DEDENT> except (FileNotFoundError, JSONDecodeError) as error: <NEW_LINE> <INDENT> QMessageBox.critical( self, "Load config", "Error retrieving data from " "selected file!\nError message:\n\n %s" % repr(error), ) <NEW_LINE> logging.error( 'Failed to load config from file "%s"', filename, exc_info=True ) <NEW_LINE> return <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> QMessageBox.critical( self, "Load config", "Following error occured during " "applying loaded settings:\n%s" % repr(error), ) <NEW_LINE> logging.error( "Unable to load config from file, keeping old settings...", exc_info=True, ) <NEW_LINE> return <NEW_LINE> <DEDENT> self.__rotors.generate_rotors() <NEW_LINE> self.__input_textbox.blockSignals(True) <NEW_LINE> self.refresh_gui() <NEW_LINE> self.__input_textbox.blockSignals(False) <NEW_LINE> self.__rotors.set_positions() <NEW_LINE> logging.info('Checkpoint set to "%s"', str(self.__enigma_api.positions())) <NEW_LINE> self.__enigma_api.set_checkpoint() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info("No load file selected...") | Loads EnigmaAPI settings from a config file and refershes GUI | 625941c2ff9c53063f47c19e |
def getLineStyles(self, row): <NEW_LINE> <INDENT> return {'color':wxToMatplotlibColor (self.GetCellBackgroundColour(row, 1)), 'linestyle': styleStrings[styleNames.index(self.GetCellValue(row, 2))], 'linewidth':int(self.GetCellValue(row, 3)), 'label':self.GetCellValue(row, 7) or ' '} | Get the line styles. If no legend label is specified, use a single
space. | 625941c2460517430c394133 |
def __init__(self, channel): <NEW_LINE> <INDENT> self.call = channel.unary_unary( '/comunicacion.Comunicando/call', request_serializer=comunicacion__pb2.llamada.SerializeToString, response_deserializer=comunicacion__pb2.llamada.FromString, ) | Constructor.
Args:
channel: A grpc.Channel. | 625941c2851cf427c661a4bb |
def scores_for_assignment(self, assignment): <NEW_LINE> <INDENT> content = [] <NEW_LINE> member = self.member[0].get() <NEW_LINE> for m in self.member: <NEW_LINE> <INDENT> member = m.get() <NEW_LINE> if member: <NEW_LINE> <INDENT> data, success = member.scores_for_assignment(assignment) <NEW_LINE> content.extend(data) <NEW_LINE> if success: <NEW_LINE> <INDENT> return content <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not member: <NEW_LINE> <INDENT> return [["Unknown-"+str(self.member[0]), 0, None, None, None]] <NEW_LINE> <DEDENT> return [[member.email[0], 0, None, None, None]] | Returns a list of lists containing score data
for the groups's final submission for ASSIGNMENT.
There is one element for each combination of
group member and score.
Ensures that each student only appears once in the list.
Format: [['STUDENT', 'SCORE', 'MESSAGE', 'GRADER', 'TAG']] | 625941c2a8370b771705284a |
def parse_row(column_names, row): <NEW_LINE> <INDENT> cell_values = [] <NEW_LINE> for cell in row.iter('%spara' %br): <NEW_LINE> <INDENT> emph_value = cell.find('%semphasis' %br) <NEW_LINE> if emph_value is not None: <NEW_LINE> <INDENT> if emph_value.text is not None: <NEW_LINE> <INDENT> cell_values.append(emph_value.text.strip().replace(u"\u200b", "")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell_values.append("") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if cell.text is not None: <NEW_LINE> <INDENT> cell_values.append(cell.text.strip().replace(u"\u200b", "")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell_values.append("") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> cell_values[3] = '' <NEW_LINE> cell_values.append('') <NEW_LINE> if '(Retired)' in cell_values[1]: <NEW_LINE> <INDENT> cell_values[4] = 'Retired' <NEW_LINE> cell_values[1] = cell_values[1].replace('(Retired)', '').strip() <NEW_LINE> <DEDENT> if ':' in cell_values[1]: <NEW_LINE> <INDENT> cell_values[3] = cell_values[1].split(':')[-1].strip() <NEW_LINE> cell_values[1] = cell_values[1].split(':')[0].strip() <NEW_LINE> <DEDENT> return {key : value for key, value in zip(column_names, cell_values)} | Parses the table's tbody tr row, row, for the DICOM Element data
Returns a list of dicts {header1 : val1, header2 : val2, ...} with each list an Element | 625941c22c8b7c6e89b3576b |
def get_inequality_constraint(self): <NEW_LINE> <INDENT> return casadi.SX() | Get the inequality constraint g(x) <= 0.0 | 625941c2711fe17d82542319 |
def get_date_hierarchy_drilldown(self, year_lookup, month_lookup): <NEW_LINE> <INDENT> today = timezone.now().date() <NEW_LINE> if year_lookup is None and month_lookup is None: <NEW_LINE> <INDENT> return ( datetime.date(y, 1, 1) for y in range(today.year - 2, today.year + 1) ) <NEW_LINE> <DEDENT> elif year_lookup is not None and month_lookup is None: <NEW_LINE> <INDENT> this_month = today.replace(day=1) <NEW_LINE> return ( month for month in ( datetime.date(int(year_lookup), month, 1) for month in range(1, 13) ) if month <= this_month ) <NEW_LINE> <DEDENT> elif year_lookup is not None and month_lookup is not None: <NEW_LINE> <INDENT> days_in_month = calendar.monthrange(year_lookup, month_lookup)[1] <NEW_LINE> return ( day for day in ( datetime.date(year_lookup, month_lookup, i + 1) for i in range(days_in_month) ) if day <= today ) | Drill-down only on past dates. | 625941c2b5575c28eb68dfa8 |
def blank(self, blank_wells=None, n_skip=3, n_av=5): <NEW_LINE> <INDENT> if not blank_wells: <NEW_LINE> <INDENT> return self._blank_by_early_timepoints( n_skip=n_skip, n_av=n_av) <NEW_LINE> <DEDENT> return self._blank_by_blank_wells( blank_wells, n_skip=n_skip, n_av=n_av) | Return a new timecourse that has been blanked.
If blank_wells is defined, all wells will be blanked
according to the mean measurements of n_av early timepoints
from the defined blanks.
Otherwise, each well will be blanked separately by subtracting
off the mean of n_av early timepoints (skipping the first n_skip).
Args:
blank_wells: the column IDs of blank wells.
n_skip: number of initial points to skip.
n_av: number of initial points to average on a per-well basis. | 625941c27c178a314d6ef406 |
def updateScript(dbconnection): <NEW_LINE> <INDENT> cursor = dbconnection.cursor() <NEW_LINE> cursor.execute("select rss, name, source from podcasts;") <NEW_LINE> rssArray = cursor.fetchall() <NEW_LINE> for rss in rssArray: <NEW_LINE> <INDENT> print("chekcing name " + str(rss[1])) <NEW_LINE> url = str(rss[0]) <NEW_LINE> name = str(rss[1]) <NEW_LINE> source = str(rss[2]) <NEW_LINE> rssArray = DatabaseInteract.rssCheck(name, source, url) <NEW_LINE> for item in rssArray: <NEW_LINE> <INDENT> if(DatabaseInteract.checkIfExists(dbconnection, item[0]) == False): <NEW_LINE> <INDENT> DatabaseInteract.insertClip(dbconnection, item[2], name, item[3], item[1], item[0]) | scans all rss feeds for new | 625941c23cc13d1c6d3c7325 |
def satellite_repos_cdn(rhel_ver, sat_ver): <NEW_LINE> <INDENT> repos_sat = (f'rhel-{rhel_ver}-server-satellite-maintenance-6-rpms,' f'rhel-{rhel_ver}-server-satellite-capsule-{sat_ver}-rpms,' f'rhel-{rhel_ver}-server-satellite-{sat_ver}-rpms,' f'rhel-{rhel_ver}-server-satellite-tools-{sat_ver}-rpms,' f'rhel-{rhel_ver}-server-ansible-2.9-rpms') <NEW_LINE> repos_rhel = (f'rhel-{rhel_ver}-server-rpms,' f'rhel-{rhel_ver}-server-optional-rpms,' f'rhel-{rhel_ver}-server-extras-rpms,' f'rhel-server-rhscl-{rhel_ver}-rpms') <NEW_LINE> return repos_sat + ',' + repos_rhel | Gather all required repos for installing released satellite from cdn.
:param rhel_ver: rhel version, such as 6, 7, 8.
:param sat_ver: satellite version, such as 6.8, 6.9
:return: A string with comma to separate repos. | 625941c2507cdc57c6306c80 |
def mktar(path, dest): <NEW_LINE> <INDENT> with tarfile.open(dest, "w:gz") as tar: <NEW_LINE> <INDENT> tar.add(path, arcname='./') | Creates a tar.gz from path and saves it to dest. | 625941c2009cb60464c6335d |
def get_activation_token_using_get_with_http_info(self, user_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['user_id'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for key, val in six.iteritems(params['kwargs']): <NEW_LINE> <INDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if ('user_id' not in params or params['user_id'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `user_id` when calling `get_activation_link_using_get`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> if 'user_id' in params: <NEW_LINE> <INDENT> path_params['userId'] = params['user_id'] <NEW_LINE> <DEDENT> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['text/plain']) <NEW_LINE> header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) <NEW_LINE> auth_settings = ['X-Authorization'] <NEW_LINE> activation_link = self.api_client.call_api( '/api/user/{userId}/activationLink', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='str', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) <NEW_LINE> return activation_link[activation_link.index(ACTIVATION_TOKEN_REGEX)+len(ACTIVATION_TOKEN_REGEX):] | getActivationLink # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api_pe.get_activation_link_using_get_with_http_info(user_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str user_id: userId (required)
:return: str
If the method is called asynchronously,
returns the request thread. | 625941c291af0d3eaac9b9c0 |
def __init__(self, id, title, dest_server, username, password): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.title = title <NEW_LINE> self.dest_server = dest_server <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> ZSyncer.__dict__['__init__'](self, id, title) | Initialize variables. | 625941c25f7d997b87174a3f |
def on_done(self, picked): <NEW_LINE> <INDENT> if picked == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> name = self.package_list[picked][0] <NEW_LINE> if self.disable_package(name): <NEW_LINE> <INDENT> on_complete = lambda: self.reenable_package(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> on_complete = None <NEW_LINE> <DEDENT> thread = PackageInstallerThread(self.manager, name, on_complete) <NEW_LINE> thread.start() <NEW_LINE> ThreadProgress(thread, 'Upgrading package %s' % name, 'Package %s successfully %s' % (name, self.completion_type)) | Quick panel user selection handler - disables a package, upgrades it,
then re-enables the package
:param picked:
An integer of the 0-based package name index from the presented
list. -1 means the user cancelled. | 625941c2a79ad161976cc0ef |
def CreateRouteTable(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateRouteTable", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateRouteTableResponse() <NEW_LINE> model._deserialize(response["Response"]) <NEW_LINE> return model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code = response["Response"]["Error"]["Code"] <NEW_LINE> message = response["Response"]["Error"]["Message"] <NEW_LINE> reqid = response["Response"]["RequestId"] <NEW_LINE> raise TencentCloudSDKException(code, message, reqid) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if isinstance(e, TencentCloudSDKException): <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TencentCloudSDKException(e.message, e.message) | 本接口(CreateRouteTable)用于创建路由表。
* 创建了VPC后,系统会创建一个默认路由表,所有新建的子网都会关联到默认路由表。默认情况下您可以直接使用默认路由表来管理您的路由策略。当您的路由策略较多时,您可以调用创建路由表接口创建更多路由表管理您的路由策略。
:param request: 调用CreateRouteTable所需参数的结构体。
:type request: :class:`tencentcloud.vpc.v20170312.models.CreateRouteTableRequest`
:rtype: :class:`tencentcloud.vpc.v20170312.models.CreateRouteTableResponse` | 625941c23346ee7daa2b2d14 |
def cursor_insert(self, value): <NEW_LINE> <INDENT> toMove = self.cursor.next <NEW_LINE> self.cursor.next = LinkedList.Node(value,self.cursor,self.cursor.next) <NEW_LINE> toMove.prior = self.cursor.next <NEW_LINE> self.cursor = self.cursor.next <NEW_LINE> self.length += 1 | inserts a new value after the cursor and sets the cursor to the
new node | 625941c2d10714528d5ffc8b |
def locales(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return contentful().locales(api_id) <NEW_LINE> <DEDENT> except HTTPError: <NEW_LINE> <INDENT> return [DEFAULT_LOCALE] | Returns the list of available locales. | 625941c2b5575c28eb68dfa9 |
def __call__(self, stdin=None, stdout=True, stderr=True): <NEW_LINE> <INDENT> if stdout: <NEW_LINE> <INDENT> stdout_arg = subprocess.PIPE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stdout_arg = open(os.devnull) <NEW_LINE> <DEDENT> if stderr: <NEW_LINE> <INDENT> stderr_arg = subprocess.PIPE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stderr_arg = open(os.devnull) <NEW_LINE> <DEDENT> child_process = subprocess.Popen(str(self), stdin=subprocess.PIPE, stdout=stdout_arg, stderr=stderr_arg, universal_newlines=True, shell=(sys.platform!="win32")) <NEW_LINE> stdout_str, stderr_str = child_process.communicate(stdin) <NEW_LINE> if not stdout: assert not stdout_str <NEW_LINE> if not stderr: assert not stderr_str <NEW_LINE> return_code = child_process.returncode <NEW_LINE> if return_code: <NEW_LINE> <INDENT> raise ApplicationError(return_code, str(self), stdout_str, stderr_str) <NEW_LINE> <DEDENT> return stdout_str, stderr_str | Execute the command and waits for it to finish, returns output.
Runs the command line tool and waits for it to finish. If it returns
a non-zero error level, an exception is raised. Otherwise two strings
are returned containing stdout and stderr.
The optional stdin argument should be a string of data which will be
passed to the tool as standard input.
The optional stdout and stderr argument are treated as a booleans, and
control if the output should be captured (True, default), or ignored
by sending it to /dev/null to avoid wasting memory (False). In the
later case empty string(s) are returned.
Default example usage:
from Bio.Emboss.Applications import WaterCommandline
water_cmd = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True,
asequence="a.fasta", bsequence="b.fasta")
print "About to run:
%s" % water_cmd
std_output, err_output = water_cmd()
This functionality is similar to subprocess.check_output() added in
Python 2.7. In general if you require more control over running the
command, use subprocess directly.
As of Biopython 1.56, when the program called returns a non-zero error
level, a custom ApplicationError exception is raised. This includes
any stdout and stderr strings captured as attributes of the exception
object, since they may be useful for diagnosing what went wrong.
| 625941c299fddb7c1c9de33c |
def _update(self, *items: Tuple[str, Union[int, str]]) -> Tuple[Union[int, str], ...]: <NEW_LINE> <INDENT> comments = dict(items) <NEW_LINE> comments.update(bootlegdisc="N") <NEW_LINE> comments.update(date=int(comments.get("date", 0))) <NEW_LINE> comments.update(deluxe="N") <NEW_LINE> comments.update(livedisc="N") <NEW_LINE> comments.update(livetrack=comments.get("titlesort", " N")[8]) <NEW_LINE> comments.update(mediaprovider=self._providers.get(comments.get("mediaprovider"))) <NEW_LINE> comments.update(origyear=int(comments.get("origyear", 0))) <NEW_LINE> comments.update(upc=comments.get("upc", "999999999999")) <NEW_LINE> return tuple(chain(*islice(zip(*sorted(comments.items(), key=itemgetter(0))), 1, 2))) | :param items:
:return: | 625941c27d43ff24873a2c49 |
def run(argv=None): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument( '--input', dest='input', required=False, help='Input file to read. This can be a local file or ' 'a file in a Google Storage Bucket.', default=input_file) <NEW_LINE> parser.add_argument('--output', dest='output', required=False, help='Output BQ table to write results to.', default='planning.yoy') <NEW_LINE> known_args, pipeline_args = parser.parse_known_args(argv) <NEW_LINE> data_ingestion = DataIngestion() <NEW_LINE> p = beam.Pipeline(options=PipelineOptions(pipeline_args)) <NEW_LINE> ( p | 'Read File from GCS' >> beam.io.ReadFromText(known_args.input, skip_header_lines=1) | 'Convert to Json' >> beam.ParDo(CsvToJson()) | 'Write to BigQuery' >> beam.io.Write( beam.io.WriteToBigQuery( 'planning.yoy', schema='fiscal:STRING,productgroup:STRING,market:STRING,state:STRING,' + 'region:STRING,department:STRING,channel:STRING,month:INTEGER,' + 'quarter:INTEGER,event:INTEGER,cost:FLOAT,kpi:FLOAT', create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE))) <NEW_LINE> p.run().wait_until_finish() | The main function which creates the pipeline and runs it. | 625941c263d6d428bbe44499 |
@salt.utils.decorators.path.which('sync') <NEW_LINE> @salt.utils.decorators.path.which('mkfs') <NEW_LINE> def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, force=False): <NEW_LINE> <INDENT> cmd = ['mkfs', '-t', str(fs_type)] <NEW_LINE> if inode_size is not None: <NEW_LINE> <INDENT> if fs_type[:3] == 'ext': <NEW_LINE> <INDENT> cmd.extend(['-i', str(inode_size)]) <NEW_LINE> <DEDENT> elif fs_type == 'xfs': <NEW_LINE> <INDENT> cmd.extend(['-i', 'size={0}'.format(inode_size)]) <NEW_LINE> <DEDENT> <DEDENT> if lazy_itable_init is not None: <NEW_LINE> <INDENT> if fs_type[:3] == 'ext': <NEW_LINE> <INDENT> cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) <NEW_LINE> <DEDENT> <DEDENT> if force: <NEW_LINE> <INDENT> if fs_type[:3] == 'ext': <NEW_LINE> <INDENT> cmd.append('-F') <NEW_LINE> <DEDENT> elif fs_type == 'xfs': <NEW_LINE> <INDENT> cmd.append('-f') <NEW_LINE> <DEDENT> <DEDENT> cmd.append(str(device)) <NEW_LINE> mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 <NEW_LINE> sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 <NEW_LINE> return all([mkfs_success, sync_success]) | Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1 | 625941c2097d151d1a222e05 |
def ui_setup(self): <NEW_LINE> <INDENT> self.setWindowTitle("Run Occam 1D") <NEW_LINE> self.resize(1920, 1080) <NEW_LINE> self.occam_widget = OccamWidget() <NEW_LINE> self.central_widget = self.setCentralWidget(self.occam_widget) <NEW_LINE> self.menu_bar = self.menuBar() <NEW_LINE> self.menu_help = self.menu_bar.addMenu('Help') <NEW_LINE> help_action = QtGui.QAction('help doc', self) <NEW_LINE> help_action.triggered.connect(self.display_help) <NEW_LINE> self.menu_help.addAction(help_action) <NEW_LINE> self.my_stream = MyStream() <NEW_LINE> self.my_stream.message.connect(self.occam_widget.normal_output) <NEW_LINE> sys.stdout = self.my_stream <NEW_LINE> QtCore.QMetaObject.connectSlotsByName(self) | setup the window layout | 625941c223e79379d52ee50f |
def batchnorm_backward(dout, cache): <NEW_LINE> <INDENT> dx, dgamma, dbeta = None, None, None <NEW_LINE> (x, x_norm, sample_mean, sample_var, gamma, beta, eps) = cache <NEW_LINE> n = x.shape[0] <NEW_LINE> dbeta = np.sum(dout, axis=0) <NEW_LINE> dgamma = np.sum(dout * x_norm, axis=0) <NEW_LINE> dxnorm = dout * gamma <NEW_LINE> divar = np.sum(dxnorm * (x - sample_mean), axis=0) <NEW_LINE> dsqrtvar = -divar / (sample_var + eps) <NEW_LINE> dvar = 0.5 * dsqrtvar / np.sqrt(sample_var + eps) <NEW_LINE> dsq = (1. / n) * np.ones(x.shape) * dvar <NEW_LINE> dxdiff2 = 2 * (x - sample_mean) * dsq <NEW_LINE> dxdiff1 = dxnorm / np.sqrt(sample_var + eps) <NEW_LINE> dmean = -np.sum(dxdiff1 + dxdiff2, axis=0) <NEW_LINE> dx2 = (1. / n) * np.ones(x.shape) * dmean <NEW_LINE> dx1 = dxdiff1 + dxdiff2 <NEW_LINE> dx = dx1 + dx2 <NEW_LINE> return dx, dgamma, dbeta | Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,) | 625941c2435de62698dfdbf6 |
def reverse_color(im): <NEW_LINE> <INDENT> assert im.mode=='L','必须为灰度图' <NEW_LINE> for i in range(im.height): <NEW_LINE> <INDENT> for j in range(im.width): <NEW_LINE> <INDENT> im[i, j] = 255 - im[i, j] <NEW_LINE> <DEDENT> <DEDENT> pass | 反色
:param im: 灰度图
:return: 灰度图 | 625941c291f36d47f21ac49a |
def project_export_limits(pulse_limit, ei_ratio,delta_inflow): <NEW_LINE> <INDENT> if ei_ratio.getStartTime() != pulse_limit.getStartTime(): <NEW_LINE> <INDENT> raise ValueError("EI limit and total export limit must have same start time") <NEW_LINE> <DEDENT> eilimit=ei_ratio*delta_inflow <NEW_LINE> tsmonth=month_numbers(pulse_limit) <NEW_LINE> is_april_may=(tsmonth==4)+(tsmonth==5) <NEW_LINE> limit=ts_where(is_april_may *(pulse_limit < eilimit) > 0., pulse_limit, eilimit) <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> writedss("out","/CALC/LIM/////",limit) <NEW_LINE> <DEDENT> even_allocation=limit/2. <NEW_LINE> cvp_min_pump=even_allocation*0. + CVP_MIN_PUMP <NEW_LINE> cvp_min_pump=ts_where(cvp_min_pump > limit, limit, cvp_min_pump) <NEW_LINE> cvp_limit=ts_where(even_allocation > cvp_min_pump, even_allocation, cvp_min_pump) <NEW_LINE> swp_limit=limit-cvp_limit <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> writedss("out","/CALC/EVENALLOC/////",even_allocation) <NEW_LINE> writedss("out","/CALC/CVPLIM/////",cvp_limit) <NEW_LINE> writedss("out","/CALC/SWPLIM/////",swp_limit) <NEW_LINE> writedss("out","/CALC/PULSELIM/////",pulse_limit) <NEW_LINE> writedss("out","/CALC/EILIM/////",eilimit) <NEW_LINE> <DEDENT> return swp_limit,cvp_limit | Refine export limits to include EI ratio and allocate
limits to CVP and SWP.
Arguments:
pulse_limit: the raw combined export limit from CALSIM
ei_ratio: the maximum E/I ratio calculated by CALSIM
delta_inflow: total inflow to the delta calculated by CALSIM
Output:
swp_limit,cvp_limit: Maximum pumping allowed during VAMP for
each of the individual projects. This routine
calculates maximum pumping, not actual pumping | 625941c2ec188e330fd5a74c |
def getPeriodicSpikes(firing_rate,time_step_sim,t_max): <NEW_LINE> <INDENT> isi_ms = 1000/firing_rate <NEW_LINE> nsteps = int(np.ceil(isi_ms/time_step_sim)) <NEW_LINE> spikes = np.arange(nsteps,t_max+nsteps,nsteps) <NEW_LINE> spiketrue = np.ones([len(spikes)]) <NEW_LINE> return spikes, spiketrue | Integer-based method for getting periodic spikes.
returns desired spike times in step numbers.
the reason for this method is that a clock with floats will
lead to skipped spikes due to rounding issues with floats in python. | 625941c256ac1b37e626417d |
def _process(self, packet, **kwargs): <NEW_LINE> <INDENT> if not packet.is_private(): <NEW_LINE> <INDENT> self._receive_callback(packet) <NEW_LINE> return False <NEW_LINE> <DEDENT> specification = packet.get("specification") <NEW_LINE> error_message = "Received packet is of unexpected type '{}', expected '{}'" <NEW_LINE> if specification == "ntp": <NEW_LINE> <INDENT> self._ntp.process(packet) <NEW_LINE> return False <NEW_LINE> <DEDENT> if self._id == 0: <NEW_LINE> <INDENT> if specification == "rssi_ground_station": <NEW_LINE> <INDENT> if self._buffer is not None: <NEW_LINE> <INDENT> self._buffer.put(packet) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> raise ValueError(error_message.format(specification, "rssi_ground_station")) <NEW_LINE> <DEDENT> if specification != "rssi_broadcast": <NEW_LINE> <INDENT> raise ValueError(error_message.format(specification, "rssi_broadcast")) <NEW_LINE> <DEDENT> return True | Process a `Packet` object `packet`. Returns whether or not `packet` is
an RSSI broadcast packet for further processing.
Classes that inherit this base class must extend this method. | 625941c2462c4b4f79d1d67a |
def _on_board(self, position): <NEW_LINE> <INDENT> (x, y) = position <NEW_LINE> return x >= 0 and y >= 0 and x < self.height and y < self.width | Args:
position: a tuple of (x, y)
Returns:
bool: returns True iff position is within the bounds of [0, self.size) | 625941c2e76e3b2f99f3a7b9 |
def test__get_tunable_no_conditionals(self): <NEW_LINE> <INDENT> init_params = { 'an_init_param': 'a_value' } <NEW_LINE> hyperparameters = { 'tunable': { 'this_is_not_conditional': { 'type': 'int', 'default': 1, 'range': [1, 10] } } } <NEW_LINE> tunable = MLBlock._get_tunable(hyperparameters, init_params) <NEW_LINE> expected = { 'this_is_not_conditional': { 'type': 'int', 'default': 1, 'range': [1, 10] } } <NEW_LINE> assert tunable == expected | If there are no conditionals, tunables are returned unmodified. | 625941c257b8e32f52483444 |
def sharpen_saturation(image: str or PillowImage, **kwargs) -> PillowImage: <NEW_LINE> <INDENT> if isinstance(image, str): <NEW_LINE> <INDENT> print('sharpen saturation isinstance') <NEW_LINE> image = Image.open(image).convert('RGB') <NEW_LINE> <DEDENT> print('sharpen saturation rest ofcode') <NEW_LINE> sharp_factor = 3 if 'sharp_factor' not in kwargs else kwargs['sharp_factor'] <NEW_LINE> color_factor = 3 if 'color_factor' not in kwargs else kwargs['color_factor'] <NEW_LINE> image = ImageEnhance.Sharpness(image).enhance(sharp_factor) <NEW_LINE> image = ImageEnhance.Color(image).enhance(color_factor) <NEW_LINE> return image | :param image: image to process on
:param kwargs: should contain sharp_factor: int, color_factor: int
:return: | 625941c26aa9bd52df036d4d |
def rotate_matrix_inplace(matrix: list, n: int) -> list: <NEW_LINE> <INDENT> last_index = n - 1 <NEW_LINE> for layer in range(n // 2): <NEW_LINE> <INDENT> layer_len = last_index - layer <NEW_LINE> for pos in range(layer, layer_len): <NEW_LINE> <INDENT> temp = matrix[layer][pos] <NEW_LINE> matrix[layer][pos] = matrix[pos][layer_len] <NEW_LINE> matrix[pos][layer_len] = matrix[layer_len][last_index - pos] <NEW_LINE> matrix[layer_len][last_index - pos] = matrix[last_index - pos][layer] <NEW_LINE> matrix[last_index - pos][layer] = temp <NEW_LINE> <DEDENT> <DEDENT> return matrix | Rotate an NxN matrix 90 degrees counterclockwise in place.
Runtime: O(n^2)
Memory: O(1) | 625941c23eb6a72ae02ec482 |
def inet_ntop(family, address): <NEW_LINE> <INDENT> if family == AF_INET: <NEW_LINE> <INDENT> return thirdparty.dns.ipv4.inet_ntoa(address) <NEW_LINE> <DEDENT> elif family == AF_INET6: <NEW_LINE> <INDENT> return thirdparty.dns.ipv6.inet_ntoa(address) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError | Convert the binary form of a network address into its textual form.
*family* is an ``int``, the address family.
*address* is a ``bytes``, the network address in binary form.
Raises ``NotImplementedError`` if the address family specified is not
implemented.
Returns a ``str``. | 625941c2796e427e537b056e |
def show(self, request, response, pathmatch): <NEW_LINE> <INDENT> tool_list = os.listdir("data/tools") <NEW_LINE> tools_html = "<ul>" <NEW_LINE> for tool_title in tool_list: <NEW_LINE> <INDENT> if tool_title != '.DS_Store': <NEW_LINE> <INDENT> with open("data/tools/" + tool_title, "r") as g: <NEW_LINE> <INDENT> tools_html += "<li class=tool-list-item><img src='%s' title='%s' id='tool-%s' border='0'></li>" % (g.read(), tool_title,tool_title) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> tools_html += "</ul>" <NEW_LINE> icon_list = os.listdir("data") <NEW_LINE> icons_html = "<ul>" <NEW_LINE> icons = [] <NEW_LINE> for icon_title in icon_list: <NEW_LINE> <INDENT> if icon_title != 'tools' and icon_title != '.DS_Store': <NEW_LINE> <INDENT> with open("data/"+icon_title, "r") as f: <NEW_LINE> <INDENT> side = "<a class=icon-list-item><img src='%s' title='%s'> %s </a> " % (f.read(), icon_title, icon_title) <NEW_LINE> icons.append(("#", "", "", side)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> icons_html += "</ul>" <NEW_LINE> response.send_template("iconeditor.tmpl", appendDict(request,{'icons': icons_html, 'tools' : tools_html, 'sidebar':icons})) | Show the editor. Provide list of saved icons. | 625941c2566aa707497f4516 |
@app.route("/get") <NEW_LINE> def get_bot_response(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> userText = request.args.get('msg') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> return str(bot.get_response(userText)) | try: es por si ocurre algun error.
:except Nos muestra el error de una forma mas detallada
:var userText: variable que trae lo que le introduscamos.
:return: retorna la respuesta del bot. | 625941c2be8e80087fb20bf0 |
def test_add_person_add_staff_to_living_space(self): <NEW_LINE> <INDENT> self.amity.create_room(["Maathai"], "LivingSpace") <NEW_LINE> person = self.amity.add_person("Robley", "Gori", "staff", "Y") <NEW_LINE> self.assertIn("Staff cannot be allocated a living space!", person) | Test that staff cannot be added to living space | 625941c2d8ef3951e32434e7 |
def cached(func): <NEW_LINE> <INDENT> def write_to_cache(fpath, data): <NEW_LINE> <INDENT> with open(fpath, 'wb') as fout: <NEW_LINE> <INDENT> pickle.dump(data, fout) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def wrapper(*func_args): <NEW_LINE> <INDENT> fname = '{}-{}-cache.pkl'.format(func.__name__, hash(repr(func_args))) <NEW_LINE> fpath = os.path.join(config.CACHE_DIR, fname) <NEW_LINE> try: <NEW_LINE> <INDENT> return pickle.load(open(fpath, 'rb')) <NEW_LINE> <DEDENT> except (IOError, EOFError): <NEW_LINE> <INDENT> return write_to_cache(fpath, func(*func_args)) <NEW_LINE> <DEDENT> <DEDENT> return wrapper | Decorator to cache function's return values to a file on disk.
Although it will cache functions that take arguments (e.g. cache f(2) and
f(3) separately), this is an experimental feature. It will cache the
function under the function name and the hash of the repr() of the arguments
tuple. We hash the repr() and not the tuple itself to avoid the problem of
unhashable arguments.
If you modify a function, it will still load the old cached version. | 625941c2091ae35668666f0c |
def define(key, value): <NEW_LINE> <INDENT> DEFINES[key] = value | Add a definition that can be used in the C struct | 625941c2ab23a570cc25012b |
def check_ib_vf_under_ipmp(name, password, vf): <NEW_LINE> <INDENT> port = get_domain_port(name) <NEW_LINE> domain = Ldom.Ldom(name, password, port) <NEW_LINE> link = get_ib_vf_link_in_domain(name, password, vf) <NEW_LINE> part = get_ib_part_over_link_in_domain(name, password, link)[0] <NEW_LINE> hotplug_dev = get_ib_vf_hotplug_dev(name, password, vf) <NEW_LINE> cmd = "ipadm |grep %s" % part <NEW_LINE> output = domain.retsend(cmd) <NEW_LINE> if output.split()[3] != '--': <NEW_LINE> <INDENT> ipmp_group = output.split()[3] <NEW_LINE> cmd = "ipmpstat -i|grep %s|grep -v %s" % ( ipmp_group, part) <NEW_LINE> output = domain.retsend(cmd) <NEW_LINE> if output: <NEW_LINE> <INDENT> another_part_under_ipmp = output.split()[0] <NEW_LINE> cmd = "dladm show-part -po LINK,OVER|grep %s" % another_part_under_ipmp <NEW_LINE> output = domain.retsend(cmd) <NEW_LINE> another_link = output.split(':')[1] <NEW_LINE> cmd = "dladm show-phys -p -o LINK,DEVICE|grep %s" % another_link <NEW_LINE> output = domain.retsend(cmd) <NEW_LINE> another_device = str(output.split(':')[1]) <NEW_LINE> another_driver = filter( str.isalpha, another_device) <NEW_LINE> another_device_num = filter( str.isdigit, another_device) <NEW_LINE> cmd = "cat /etc/path_to_inst|grep '%s \"%s\"'" % ( another_device_num, another_driver) <NEW_LINE> output = domain.retsend(cmd) <NEW_LINE> another_link_hotplug_dev = output.split()[0].strip('"') <NEW_LINE> pci_bus_path = another_link_hotplug_dev.split('/')[1] <NEW_LINE> if pci_bus_path != hotplug_dev.split('/')[1]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False | Purpose:
Check the part over the corresponding link of
ib vf is under ipmp group in io domain
Arguments:
name - IO domain name
password - IO domain password
vf - IB vf
Return:
True - Under IPMP group
False - Not under IPMP group | 625941c230bbd722463cbd6f |
def fit_predict(self, X, ml=[], hyperparameters=None): <NEW_LINE> <INDENT> assert isinstance(X, pd.DataFrame), 'X must be a pandas.DataFrame' <NEW_LINE> ml_flat = [idx for link in ml for idx in link] <NEW_LINE> assert not(is_duplicate(ml_flat)), 'Integers in ml are not unique' <NEW_LINE> assert (0 <= np.array(ml_flat)).all() and (np.array(ml_flat) < len(X)).all() and all([isinstance(item, int) for item in ml_flat]), 'Elements of ml must be integers in [0,len(X))' <NEW_LINE> X, n_cts, n_bin, n_ord = sort_features(X) <NEW_LINE> if hyperparameters is None: <NEW_LINE> <INDENT> nu = np.mean(X[X.columns[:n_cts]]) <NEW_LINE> rho = [1]*n_cts <NEW_LINE> a = [1]*n_cts <NEW_LINE> b = (np.var(X[X.columns[:n_cts]])) <NEW_LINE> gamma = [2]*n_bin <NEW_LINE> delta = (2-2*np.mean(X[X.columns[n_cts:(n_cts+n_bin)]]))/np.mean(X[X.columns[n_cts:(n_cts+n_bin)]]) <NEW_LINE> eps = [1]*n_ord <NEW_LINE> zeta = 1/np.mean(X[X.columns[(n_cts+n_bin):]]) <NEW_LINE> hyperparameters = dict(nu=nu, rho=rho, a=a, b=b, gamma=gamma, delta=delta, eps=eps, zeta=zeta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(hyperparameters, dict), 'hyperparameters must be a dictionary' <NEW_LINE> assert 'nu' in hyperparameters and 'rho' in hyperparameters and 'a' in hyperparameters and 'b' in hyperparameters and 'gamma' in hyperparameters and 'delta' in hyperparameters and 'eps' in hyperparameters and 'zeta' in hyperparameters, 'hyperparameters needs keys "nu", "rho", "a", "b", "gamma", "delta", "eps" & "zeta"' <NEW_LINE> assert len(hyperparameters['nu']) == n_cts and len(hyperparameters['rho']) == n_cts and len(hyperparameters['a']) == n_cts and len(hyperparameters['b']) == n_cts, 'Number of hyperparameters for continuous variates do not match the number of continuous variates' <NEW_LINE> assert len(hyperparameters['gamma']) == n_bin and len(hyperparameters['delta']) == n_bin, 'Number of hyperparameters for binary variates do not match the number of binary variates' <NEW_LINE> assert len(hyperparameters['eps']) == n_ord and len(hyperparameters['zeta']) == n_ord, 'Number of hyperparameters for ordinal variates do not match the number of ordinal variates' <NEW_LINE> <DEDENT> clust_soln = self._mfvi(X, hyperparameters, ml) <NEW_LINE> return clust_soln | Fit the model to X & predict clusters for each observation (row) in X given must-link constraints ml
:param pd.DataFrame X: data
:param list ml: each element is a list of indices of points that must be in the same cluster
:param hyperparameters: hyperparameters of distributions for the variates
:type hyperparameters: hyperparameters or None
:return: the clustering solution
:rtype: MFVICluster | 625941c223849d37ff7b303b |
def card_input_validate(card_names, previous_cards, num_cards_required=None): <NEW_LINE> <INDENT> if num_cards_required is not None and len(card_names) != num_cards_required: <NEW_LINE> <INDENT> print("Wrong number of cards.") <NEW_LINE> return False <NEW_LINE> <DEDENT> for card_name in card_names: <NEW_LINE> <INDENT> if card_name == "*": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif len(card_name) == 2 and card_name[0] in RANK_NAMES.values() and card_name[1] in SUIT_NAMES.values(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(card_name, " not recognized.") <NEW_LINE> return False <NEW_LINE> <DEDENT> if card_name in previous_cards and card_name != "*": <NEW_LINE> <INDENT> print(card_name + " appearing more than once.") <NEW_LINE> return False <NEW_LINE> <DEDENT> previous_cards.update(card_name) <NEW_LINE> <DEDENT> return True | To validate user input of cards, preventing wrong number of cards, cards not recognized in our notation, and
duplicated cards.
Called by prompt_user()
:param card_names: an array of strings, for the card names.
:param previous_cards: a set of strings, for the card names previously entered, to check for duplicates.
:param num_cards_required: the correct number of cards in card_names.
:return: boolean. True if the input is OK | 625941c2656771135c3eb817 |
def module_func(*args, **kwargs): <NEW_LINE> <INDENT> return 'blah' | Used by dispatch tests | 625941c2a17c0f6771cbdffd |
def common_command_formatting(self, page_or_embed, command): <NEW_LINE> <INDENT> page_or_embed.title = self.get_command_signature(command) <NEW_LINE> if command.description: <NEW_LINE> <INDENT> page_or_embed.description = f'{command.description}\n\n{command.help}' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page_or_embed.description = command.help or 'No help found...' | Command help formatting. | 625941c2cad5886f8bd26f84 |
def sort_text_column(self, tv, col, reverse=False): <NEW_LINE> <INDENT> l = [(tv.set(k, col), k) for k in tv.get_children('')] <NEW_LINE> l.sort(key=lambda x: x[0].lower(), reverse=reverse) <NEW_LINE> for index, (val, k) in enumerate(l): <NEW_LINE> <INDENT> tv.move(k, '', index) <NEW_LINE> <DEDENT> tv.heading(col, command=lambda col_=col: self.sort_text_column(tv, col_, not reverse)) | Sorts entries in treeview tables alphabetically. | 625941c24a966d76dd550fb9 |
def interval(a, b): <NEW_LINE> <INDENT> if a <= b: <NEW_LINE> <INDENT> return [a, b] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [b, a] | Construct an interval from a to b. | 625941c21d351010ab855ac7 |
def get_song(self, song_id): <NEW_LINE> <INDENT> url = get_song_url(song_id) <NEW_LINE> result = self.get_request(url) <NEW_LINE> return result['songs'][0] | Get song info by song id
:param song_id:
:return: | 625941c2d10714528d5ffc8c |
def _remove_in_process_courses(courses, in_process_course_actions): <NEW_LINE> <INDENT> def format_course_for_view(course): <NEW_LINE> <INDENT> return { 'display_name': course.display_name, 'course_key': unicode(course.location.course_key), 'url': reverse_course_url('course_handler', course.id), 'lms_link': get_lms_link_for_item(course.location), 'rerun_link': _get_rerun_link_for_item(course.id), 'org': course.display_org_with_default, 'number': course.display_number_with_default, 'run': course.location.run } <NEW_LINE> <DEDENT> in_process_action_course_keys = [uca.course_key for uca in in_process_course_actions] <NEW_LINE> courses = [ format_course_for_view(course) for course in courses if not isinstance(course, ErrorDescriptor) and (course.id not in in_process_action_course_keys) ] <NEW_LINE> return courses | removes any in-process courses in courses list. in-process actually refers to courses
that are in the process of being generated for re-run | 625941c2097d151d1a222e06 |
def get(self, *args): <NEW_LINE> <INDENT> return _vnl_vectorPython.vnl_vectorUL_get(self, *args) | get(self, unsigned int index) -> unsigned long | 625941c216aa5153ce362423 |
def add_meta_options(parser): <NEW_LINE> <INDENT> parser.add_argument('--force-handlers', default=C.DEFAULT_FORCE_HANDLERS, dest='force_handlers', action='store_true', help="run handlers even if a task fails") <NEW_LINE> parser.add_argument('--flush-cache', dest='flush_cache', action='store_true', help="clear the fact cache for every host in inventory") | Add options for commands which can launch meta tasks from the command line | 625941c226068e7796caec86 |
def __init__(self): <NEW_LINE> <INDENT> self.RouteTableName = None <NEW_LINE> self.RouteTableCidrBlock = None <NEW_LINE> self.VpcId = None | :param RouteTableName: 路由表名称。
:type RouteTableName: str
:param RouteTableCidrBlock: 路由表CIDR。
:type RouteTableCidrBlock: str
:param VpcId: VPC实例ID。
:type VpcId: str | 625941c2f8510a7c17cf96a6 |
def divMax(fData, realData): <NEW_LINE> <INDENT> maxData = max(fData) <NEW_LINE> for data in fData: <NEW_LINE> <INDENT> cuck = data / maxData <NEW_LINE> realData.append(cuck) <NEW_LINE> <DEDENT> pass | Calculate in relative, to the max data | 625941c282261d6c526ab447 |
def add_callback(self, callback): <NEW_LINE> <INDENT> self.callbacks.append(callback) | Adds a callback that inherits from HttpCallback. | 625941c27d43ff24873a2c4a |
def newspeed(self): <NEW_LINE> <INDENT> self.dirscan_speed = cfg.dirscan_speed() <NEW_LINE> self.trigger = True | We're notified of a scan speed change | 625941c27d847024c06be265 |
def test_validate2(self): <NEW_LINE> <INDENT> board = AtomicBoard(setup=FEN1) <NEW_LINE> board = board.move(parseSAN(board, 'Nc7+')) <NEW_LINE> print(board) <NEW_LINE> self.assertTrue(validate(board, parseSAN(board, 'Qxd2'))) <NEW_LINE> self.assertTrue(validate(board, parseSAN(board, 'Qxf2'))) <NEW_LINE> self.assertTrue(not validate(board, parseSAN(board, 'Qxb2'))) <NEW_LINE> self.assertTrue(not validate(board, parseSAN(board, 'Qe4+'))) | Testing explode king vs mate in Atomic variant | 625941c2cad5886f8bd26f85 |
def execute_step( self, tool_dependency, package_name, actions, action_dict, filtered_actions, env_file_builder, install_environment, work_dir, current_dir=None, initial_download=False, ): <NEW_LINE> <INDENT> with settings(warn_only=True): <NEW_LINE> <INDENT> configure_opts = action_dict.get("configure_opts", "") <NEW_LINE> if "prefix=" in configure_opts: <NEW_LINE> <INDENT> pre_cmd = f"./configure {configure_opts} && make && make install" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre_cmd = f"./configure --prefix=$INSTALL_DIR {configure_opts} && make && make install" <NEW_LINE> <DEDENT> cmd = install_environment.build_command(basic_util.evaluate_template(pre_cmd, install_environment)) <NEW_LINE> install_environment.handle_command( tool_dependency=tool_dependency, cmd=cmd, return_output=False, job_name=package_name ) <NEW_LINE> return tool_dependency, None, None | Handle configure, make and make install in a shell, allowing for configuration options. Since this
class is not used in the initial download stage, no recipe step filtering is performed here, and None
values are always returned for filtered_actions and dir. | 625941c2046cf37aa974ccf4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.