code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
def loads(string): <NEW_LINE> <INDENT> return ""
|
loads(string) -- Load a pickle from the given string
|
625941bb596a897236089978
|
def get_set_from_ranges(ranges): <NEW_LINE> <INDENT> result = set() <NEW_LINE> for range_from, range_to in ranges: <NEW_LINE> <INDENT> result |= set(range(range_from, range_to + 1)) <NEW_LINE> <DEDENT> return result
|
Convert [(a, b), (c, d), ...] to a set of all numbers in these ranges (inclusive)
|
625941bba8370b771705274f
|
def scan(self, scan_number=None, data_type='centroided', **kwargs): <NEW_LINE> <INDENT> scan_data = self._read_data() <NEW_LINE> return self._make_scan(scan_data, data_type)
|
Retrieves specified scan from document.
Args:
scan_number: int or None
Specifies the scan number of the scan to be retrieved. If not
provided or set to None, first scan is returned. The None value
is typically used for files containing just one scan without
specific scan number assigned.
data_type: str
Specifies how data points should be handled if this value is not
available from the file.
centroided - points will be handled as centroids
profile - points will be handled as profile
Returns:
msread.Scan
MS scan.
|
625941bb9b70327d1c4e0c82
|
def next_version(version): <NEW_LINE> <INDENT> dots = version.count('.') <NEW_LINE> new = str(int(version.replace('.', '')) + 1) <NEW_LINE> new = '.'.join(new) <NEW_LINE> new = new.replace('.', '', new.count('.') - dots) <NEW_LINE> return new
|
Increment version number by one
Args:
version (str): '1.0.0'
Returns:
str: New version '1.0.1'
Examples:
>>> next_version('1.0.0')
'1.0.1'
|
625941bbd4950a0f3b08c200
|
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ResourceListOfQuote): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
|
Returns true if both objects are equal
|
625941bbb830903b967e97c4
|
def add_users( self, tag_id: int, user_ids: Optional[List[str]] = None, department_ids: Optional[List[int]] = None ) -> dict: <NEW_LINE> <INDENT> self._validate_tag_id(tag_id) <NEW_LINE> if not user_ids and not department_ids: <NEW_LINE> <INDENT> raise ValueError("user_ids and department_ids cannot be empty at the same time") <NEW_LINE> <DEDENT> if user_ids is not None and len(user_ids) > 1000: <NEW_LINE> <INDENT> raise ValueError("the length of the user_ids cannot be greater than 1000") <NEW_LINE> <DEDENT> if department_ids is not None and len(department_ids) > 100: <NEW_LINE> <INDENT> raise ValueError("the length of the department_ids cannot be greater than 100") <NEW_LINE> <DEDENT> data: Dict[str, Any] = {"tagid": tag_id} <NEW_LINE> if user_ids: <NEW_LINE> <INDENT> data["userlist"] = user_ids <NEW_LINE> <DEDENT> if department_ids: <NEW_LINE> <INDENT> data["partylist"] = department_ids <NEW_LINE> <DEDENT> return self._post("tag/addtagusers", data=data)
|
增加标签成员
参考:https://work.weixin.qq.com/api/doc/90000/90135/90214
**权限说明**:
调用的应用必须是指定标签的创建者;成员属于应用的可见范围。
**注意**:每个标签下部门、人员总数不能超过3万个。
返回结果示例:
a. 正确时返回 ::
{
"errcode": 0,
"errmsg": "ok"
}
b. 若部分userid、partylist非法,则返回 ::
{
"errcode": 0,
"errmsg": "ok",
"invalidlist":"usr1|usr2|usr",
"invalidparty":[2,4]
}
c. 当包含userid、partylist全部非法时返回 ::
{
"errcode": 40070,
"errmsg": "all list invalid "
}
结果参数说明:
+--------------+------------------------+
| 参数 | 说明 |
+==============+========================+
| errcode | 返回码 |
+--------------+------------------------+
| errmsg | 对返回码的文本描述内容 |
+--------------+------------------------+
| invalidlist | 非法的成员帐号列表 |
+--------------+------------------------+
| invalidparty | 非法的部门id列表 |
+--------------+------------------------+
:param tag_id: 标签ID,非负整型
:param user_ids: 企业成员ID列表,注意:user_ids和department_ids不能同时为空,
单次请求个数不超过1000
:param department_ids: 企业部门ID列表,注意:user_ids和department_ids不能
同时为空,单次请求个数不超过100
:return: 请求结果
|
625941bbd53ae8145f87a124
|
def on(self): <NEW_LINE> <INDENT> pass
|
Stub function
|
625941bb2ae34c7f2600cfe0
|
def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % self.session_name
|
Returns unicode string describting the objects and his content
*Args:*
*None*
*Returns:*
:unicode: unicode string representation
of an :py:class:`schedule.Interval`
|
625941bb91af0d3eaac9b8c3
|
def setup(self): <NEW_LINE> <INDENT> opts = self.options <NEW_LINE> vec_size = opts['vec_size'] <NEW_LINE> n_rows, n_cols = opts['A_shape'] <NEW_LINE> self.add_input(name=opts['A_name'], shape=(vec_size,) + opts['A_shape'], units=opts['A_units']) <NEW_LINE> self.add_input(name=opts['x_name'], shape=(vec_size,) + (n_cols,), units=opts['x_units']) <NEW_LINE> b_shape = (vec_size,) + (n_rows,) if vec_size > 1 else (n_rows,) <NEW_LINE> self.add_output(name=opts['b_name'], val=np.ones(shape=b_shape), units=opts['b_units']) <NEW_LINE> A = np.ones(shape=(vec_size,) + opts['A_shape']) <NEW_LINE> x = np.ones(shape=(vec_size,) + (n_cols,)) <NEW_LINE> bd_A = spla.block_diag(*A) <NEW_LINE> x_repeat = np.repeat(x, A.shape[1], axis=0) <NEW_LINE> bd_x_repeat = spla.block_diag(*x_repeat) <NEW_LINE> db_dx_rows, db_dx_cols = np.nonzero(bd_A) <NEW_LINE> db_dA_rows, db_dA_cols = np.nonzero(bd_x_repeat) <NEW_LINE> self.declare_partials(of=opts['b_name'], wrt=opts['A_name'], rows=db_dA_rows, cols=db_dA_cols) <NEW_LINE> self.declare_partials(of=opts['b_name'], wrt=opts['x_name'], rows=db_dx_rows, cols=db_dx_cols)
|
Declare inputs, outputs, and derivatives for the matrix vector product component.
|
625941bb45492302aab5e16f
|
def _replace_table_file(self): <NEW_LINE> <INDENT> if is_file(self.table_file): <NEW_LINE> <INDENT> from time import strftime <NEW_LINE> old_table_file = "%s.old.%s" % (self.table_file, strftime("%Y%m%d%H%M%S")) <NEW_LINE> move(self.table_file, old_table_file) <NEW_LINE> <DEDENT> self._create_table_file()
|
replace table file
:return:
|
625941bb15fb5d323cde09b9
|
def onRemoveZone(self): <NEW_LINE> <INDENT> if self.runtime_view: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> selected_zoneitem = self.selectedConfigurationCombo.selectedItem() <NEW_LINE> if selected_zoneitem: <NEW_LINE> <INDENT> selected_zone = selected_zoneitem.label() <NEW_LINE> zone = self.fw.config().getZoneByName(selected_zone) <NEW_LINE> zone.remove() <NEW_LINE> self.load_zones()
|
manages remove zone button
|
625941bbfb3f5b602dac353e
|
def construct(k): <NEW_LINE> <INDENT> order = 2*k + 1 <NEW_LINE> *A,x = sy.symbols("a0:%d,x" % (order+1)) <NEW_LINE> w = sum(a*x**i for i,a in enumerate(A)) <NEW_LINE> λw = lambda x0: w.subs({x: x0}) <NEW_LINE> wp = [sy.diff(w, x, i) for i in range(1,1+k)] <NEW_LINE> λwp = [(lambda expr: lambda x0: expr.subs({x: x0}))(expr) for expr in wp] <NEW_LINE> zero,one = sy.S.Zero, sy.S.One <NEW_LINE> w0,w1 = sy.symbols("w0, w1") <NEW_LINE> eqs = [λw(zero) - w0, λw(one) - w1] <NEW_LINE> dofs = [w0, w1] <NEW_LINE> for i,f in enumerate(λwp): <NEW_LINE> <INDENT> d0_name = "w%s0" % ((i+1) * "p") <NEW_LINE> d1_name = "w%s1" % ((i+1) * "p") <NEW_LINE> d0,d1 = sy.symbols("%s, %s" % (d0_name, d1_name)) <NEW_LINE> eqs.extend([f(zero) - d0, f(one) - d1]) <NEW_LINE> dofs.extend([d0, d1]) <NEW_LINE> <DEDENT> coeffs = sy.solve(eqs, A) <NEW_LINE> solution = w.subs(coeffs) <NEW_LINE> solution = sy.collect(sy.expand(solution), dofs) <NEW_LINE> N = [solution.coeff(dof) for dof in dofs] <NEW_LINE> return (dofs, N)
|
Construct Hermite shape functions.
The result can be used for interpolating a function and its first k derivatives on [0,1].
|
625941bb8e05c05ec3eea220
|
def start_session(self, **kwargs): <NEW_LINE> <INDENT> authset = set(self.__all_credentials.values()) <NEW_LINE> if len(authset) > 1: <NEW_LINE> <INDENT> raise InvalidOperation("Cannot call start_session when" " multiple users are authenticated") <NEW_LINE> <DEDENT> server_session = self._get_server_session() <NEW_LINE> opts = client_session.SessionOptions(**kwargs) <NEW_LINE> return client_session.ClientSession(self, server_session, opts, authset)
|
Start a logical session.
This method takes the same parameters as
:class:`~pymongo.client_session.SessionOptions`. See the
:mod:`~pymongo.client_session` module for details and examples.
Requires MongoDB 3.6. It is an error to call :meth:`start_session`
if this client has been authenticated to multiple databases using the
deprecated method :meth:`~pymongo.database.Database.authenticate`.
.. versionadded:: 3.6
|
625941bba4f1c619b28afeef
|
def has_cycle(G): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> consume(topological_sort(G)) <NEW_LINE> <DEDENT> except nx.NetworkXUnfeasible: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
|
Decides whether the directed graph has a cycle.
|
625941bb30c21e258bdfa34a
|
def get_ntp_servers_summary(servers, states): <NEW_LINE> <INDENT> summary = _("NTP servers:") <NEW_LINE> for server in servers: <NEW_LINE> <INDENT> summary += "\n" + get_ntp_server_summary(server, states) <NEW_LINE> <DEDENT> if not servers: <NEW_LINE> <INDENT> summary += " " + _("not configured") <NEW_LINE> <DEDENT> return summary
|
Generate a summary of NTP servers and their states.
:param servers: a list of NTP servers
:type servers: a list of TimeSourceData
:param states: a cache of NTP server states
:type states: an instance of NTPServerStatusCache
:return: a string with a summary
|
625941bb67a9b606de4a7d6b
|
def result_view(request): <NEW_LINE> <INDENT> if 'result' in request.session: <NEW_LINE> <INDENT> result = request.session['result'] <NEW_LINE> del request.session['result'] <NEW_LINE> return render(request, 'vouchers/result.html', result) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render( request, 'vouchers/result.html', { 'valid': False, 'message': 'Bad request! You reached this page incorrectly.' } )
|
This view renders the result page.
Args:
request (HttpRequest object): The request object passed to the view.
Returns:
A HttpResponse rendered using the 'render' function.
|
625941bba17c0f6771cbdf02
|
def normalize(self, x): <NEW_LINE> <INDENT> return self._ETA * (x - self._md) + self._mr
|
Normalizes a value.
|
625941bb4e696a04525c92fb
|
def join(self, timeout=None): <NEW_LINE> <INDENT> if self.worker is not None: <NEW_LINE> <INDENT> self.worker.join(timeout)
|
Wait until the queue is empty or closed.
|
625941bbd8ef3951e32433ec
|
@app.route('/experience/', strict_slashes=False) <NEW_LINE> def load_experience_page(): <NEW_LINE> <INDENT> return render_template('experience.html', cache_id=uuid.uuid4())
|
renders experience.html
Return: rendered html
|
625941bb627d3e7fe0d68cfd
|
def accept(self): <NEW_LINE> <INDENT> self.save() <NEW_LINE> super(FoldersManageDialog, self).accept()
|
ok button clicked
|
625941bb8c3a87329515826d
|
def set_trigger_setting(self, setting, value): <NEW_LINE> <INDENT> if self.is_enabled(): <NEW_LINE> <INDENT> return ["Cannot edit script with enabled, first disable and try again.", False] <NEW_LINE> <DEDENT> if setting not in self.get_trigger_settings(): <NEW_LINE> <INDENT> return ["Script does not have setting: "+setting, False] <NEW_LINE> <DEDENT> self._trigger[setting] = value <NEW_LINE> return [setting+" set to "+str(value), True]
|
Set trigger settings value
Settings cannot be changed when script is enabled
|
625941bb0a366e3fb873e6c6
|
def decrypt(self, data): <NEW_LINE> <INDENT> decrypted = [] <NEW_LINE> for i, char in enumerate(data): <NEW_LINE> <INDENT> key_char = ord(self.KEY[i % len(self.KEY)]) <NEW_LINE> enc_char = ord(char) <NEW_LINE> decrypted.append(chr((enc_char - key_char) % 127)) <NEW_LINE> <DEDENT> msg = ''.join(decrypted) <NEW_LINE> return self.decorated.decrypt(msg)
|
Decrypts a string using caesar decryption
:param data: str
:rtype: str
:return: Result of the decorated instance
|
625941bbab23a570cc25002e
|
def getEndFlag(self): <NEW_LINE> <INDENT> return self.endFlag
|
endFlagを返す。
コマンドが終了しているかどうかを判定できる。
Returns
-------
endFlag : Bool
コマンドが終了していればTrue
実行中ならFalse
|
625941bbcb5e8a47e48b795d
|
def handle_error(error, path, file, old_file, file_error_cb, missing_cb): <NEW_LINE> <INDENT> if error.errno == errno.EACCES: <NEW_LINE> <INDENT> file_error_cb(path, file, error) <NEW_LINE> <DEDENT> elif error.errno == errno.ENOENT: <NEW_LINE> <INDENT> if old_file is not None: <NEW_LINE> <INDENT> missing_cb(old_file) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise error
|
Deal with file error.
|
625941bbd6c5a10208143ef6
|
def CF_Gxy_TIR_square_2d2d(parms, tau, wixi=wixi): <NEW_LINE> <INDENT> D_2D1 = parms[0] <NEW_LINE> D_2D2 = parms[1] <NEW_LINE> sigma = parms[2] <NEW_LINE> a = parms[3] <NEW_LINE> kappa = 1/parms[4] <NEW_LINE> Conc_2D1 = parms[5] <NEW_LINE> Conc_2D2 = parms[6] <NEW_LINE> alpha = parms[7] <NEW_LINE> var1 = sigma**2+D_2D1*tau <NEW_LINE> AA1 = 2*np.sqrt(var1)/(a**2*np.sqrt(np.pi)) <NEW_LINE> BB1 = np.exp(-a**2/(4*(var1))) - 1 <NEW_LINE> CC1 = sps.erf(a/(2*np.sqrt(var1)))/a <NEW_LINE> g2D1 = Conc_2D1 * (AA1*BB1+CC1)**2 <NEW_LINE> var2 = sigma**2+D_2D2*tau <NEW_LINE> AA2 = 2*np.sqrt(var2)/(a**2*np.sqrt(np.pi)) <NEW_LINE> BB2 = np.exp(-a**2/(4*(var2))) - 1 <NEW_LINE> CC2 = sps.erf(a/(2*np.sqrt(var2)))/a <NEW_LINE> g2D2 = alpha**2 * Conc_2D2 * (AA2*BB2+CC2)**2 <NEW_LINE> F = Conc_2D1 + alpha * Conc_2D2 <NEW_LINE> G = (g2D1 + g2D2) / F**2 <NEW_LINE> return G
|
Two-component two-dimensional diffusion with a square-shaped
lateral detection area taking into account the size of the
point spread function.
*parms* - a list of parameters.
Parameters (parms[i]):
[0] D_2D1 Diffusion coefficient of species 1
[1] D_2D2 Diffusion coefficient of species 2
[2] σ Lateral size of the point spread function
σ = σ₀ * λ / NA
[3] a Side size of the square-shaped detection area
[4] d_eva Evanescent penetration depth
[5] C_2D1 Two-dimensional concentration of species 1
[6] C_2D2 Two-dimensional concentration of species 2
[7] α Relative molecular brightness of particle
2 compared to particle 1 (α = q₂/q₁)
*tau* - lag time
|
625941bb1f037a2d8b9460ad
|
@tf_export('test.is_built_with_xla') <NEW_LINE> def is_built_with_xla(): <NEW_LINE> <INDENT> return _test_util.IsBuiltWithXLA()
|
Returns whether TensorFlow was built with XLA support.
|
625941bb99fddb7c1c9de241
|
def test_run_attach_detach_volume_for_instance(self): <NEW_LINE> <INDENT> mountpoint = "/dev/sdf" <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> volume = tests_utils.create_volume(self.context, admin_metadata={'readonly': 'True'}, **self.volume_params) <NEW_LINE> volume_id = volume.id <NEW_LINE> self.volume.create_volume(self.context, volume) <NEW_LINE> attachment = self.volume.attach_volume(self.context, volume_id, instance_uuid, None, mountpoint, 'ro') <NEW_LINE> vol = objects.Volume.get_by_id(context.get_admin_context(), volume_id) <NEW_LINE> self.assertEqual("in-use", vol['status']) <NEW_LINE> self.assertEqual('attached', attachment['attach_status']) <NEW_LINE> self.assertEqual(mountpoint, attachment['mountpoint']) <NEW_LINE> self.assertEqual(instance_uuid, attachment['instance_uuid']) <NEW_LINE> self.assertIsNone(attachment['attached_host']) <NEW_LINE> admin_metadata = vol['admin_metadata'] <NEW_LINE> self.assertEqual(2, len(admin_metadata)) <NEW_LINE> expected = dict(readonly='True', attached_mode='ro') <NEW_LINE> self.assertDictMatch(expected, admin_metadata) <NEW_LINE> connector = {'initiator': 'iqn.2012-07.org.fake:01'} <NEW_LINE> conn_info = self.volume.initialize_connection(self.context, volume_id, connector) <NEW_LINE> self.assertEqual('ro', conn_info['data']['access_mode']) <NEW_LINE> self.assertRaises(exception.VolumeAttached, self.volume.delete_volume, self.context, volume) <NEW_LINE> self.volume.detach_volume(self.context, volume_id, attachment['id']) <NEW_LINE> vol.refresh() <NEW_LINE> self.assertEqual('available', vol.status) <NEW_LINE> self.volume.delete_volume(self.context, volume) <NEW_LINE> self.assertRaises(exception.VolumeNotFound, objects.Volume.get_by_id, self.context, volume_id)
|
Make sure volume can be attached and detached from instance.
|
625941bbbe8e80087fb20af6
|
def npoints(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._npoints <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return len(self.points())
|
Return the number of lattice points of this polytope.
EXAMPLES: The number of lattice points of the 3-dimensional
octahedron and its polar cube::
sage: o = lattice_polytope.cross_polytope(3)
sage: o.npoints() # optional - palp
7
sage: cube = o.polar()
sage: cube.npoints() # optional - palp
27
|
625941bba05bb46b383ec6d3
|
def default(self): <NEW_LINE> <INDENT> self.__hours.set("12") <NEW_LINE> self.__minutes.set("00")
|
This function sets the time to its defaul (noon)
|
625941bb3346ee7daa2b2c19
|
def fillFromCatalogue(self, target): <NEW_LINE> <INDENT> mangaid = target['mangaid'] <NEW_LINE> fill = False <NEW_LINE> for col in target.colnames: <NEW_LINE> <INDENT> if (np.isscalar(target[col]) and (target[col] == -999 or (isinstance(target[col], six.string_types) and '-999' in target[col]))): <NEW_LINE> <INDENT> fill = True <NEW_LINE> break <NEW_LINE> <DEDENT> elif np.any(np.array(target[col] == -999)): <NEW_LINE> <INDENT> fill = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not fill: <NEW_LINE> <INDENT> return target <NEW_LINE> <DEDENT> log.info('filling out incomplete information for mangaid={0}' .format(mangaid)) <NEW_LINE> catalogueData = table.Table(getCatalogueRow(mangaid)) <NEW_LINE> for col in catalogueData.colnames: <NEW_LINE> <INDENT> if col != col.lower(): <NEW_LINE> <INDENT> catalogueData.rename_column(col, col.lower()) <NEW_LINE> <DEDENT> <DEDENT> for col in target.colnames: <NEW_LINE> <INDENT> if col not in catalogueData.colnames: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (np.isscalar(target[col]) and (target[col] == -999 or (isinstance(target[col], six.string_types) and '-999' in target[col]))): <NEW_LINE> <INDENT> target[col] = catalogueData[col][0] <NEW_LINE> <DEDENT> elif np.any(np.array(target[col] == -999)): <NEW_LINE> <INDENT> target[col] = catalogueData[col] <NEW_LINE> <DEDENT> <DEDENT> return target
|
Checks a target for fields with -999 values and tries to complete
them from the parent catalogue.
|
625941bb8e7ae83300e4ae7a
|
def dict_subset(dict_, keys, default=util_const.NoParam): <NEW_LINE> <INDENT> items = dict_take(dict_, keys, default) <NEW_LINE> subdict_ = collections.OrderedDict(list(zip(keys, items))) <NEW_LINE> return subdict_
|
Get a subset of a dictionary
Args:
dict_ (dict): superset dictionary
keys (list): keys to take from `dict_`
Returns:
dict: subset dictionary
Example:
>>> import ubelt as ub
>>> dict_ = {'K': 3, 'dcvs_clip_max': 0.2, 'p': 0.1}
>>> keys = ['K', 'dcvs_clip_max']
>>> subdict_ = ub.dict_subset(dict_, keys)
>>> print(ub.repr2(subdict_, nl=0))
{'K': 3, 'dcvs_clip_max': 0.2}
|
625941bbd164cc6175782bfd
|
def __str__ (self): <NEW_LINE> <INDENT> output = 'DB: {' <NEW_LINE> end = min(5, len(self)) <NEW_LINE> for index, key in enumerate(itertools.islice(self.data.keys(), end)): <NEW_LINE> <INDENT> output += key <NEW_LINE> if (index < (end - 1)): <NEW_LINE> <INDENT> output += ', ' <NEW_LINE> <DEDENT> <DEDENT> if (len(self) != end): <NEW_LINE> <INDENT> output += ',...' <NEW_LINE> <DEDENT> output += '}}\nNum. sequences: {:d}\nHistory:\n'.format(len(self)) <NEW_LINE> output += '\n'.join([' '.join(x) for x in self._report]) <NEW_LINE> return (output)
|
Returns:
string
Fancy print of the data stored in the BioSeqs object.
|
625941bb3c8af77a43ae364c
|
def sample_file_from_sample_path(self, sample_path, runfolder): <NEW_LINE> <INDENT> file_name = os.path.basename(sample_path) <NEW_LINE> m = re.match(self.filename_regexp, file_name) <NEW_LINE> if not m or len(m.groups()) != 5: <NEW_LINE> <INDENT> raise FileNameParsingException("Could not parse information from file name '{}'".format(file_name)) <NEW_LINE> <DEDENT> sample_name = str(m.group(1)) <NEW_LINE> sample_index = str(m.group(2)) <NEW_LINE> lane_no = int(m.group(3)) <NEW_LINE> is_index = (str(m.group(4)) == "I") <NEW_LINE> read_no = int(m.group(5)) <NEW_LINE> try: <NEW_LINE> <INDENT> checksum = self.checksum_from_sample_path(sample_path, runfolder) <NEW_LINE> <DEDENT> except ChecksumNotFoundException as e: <NEW_LINE> <INDENT> log.info(e) <NEW_LINE> checksum = None <NEW_LINE> <DEDENT> return SampleFile( sample_path, sample_name=sample_name, sample_index=sample_index, lane_no=lane_no, read_no=read_no, is_index=is_index, checksum=checksum)
|
Create a SampleFile instance from the supplied path. Attributes will be parsed from elements in the file name
and path.
:param sample_path: path to a sample sequence file
:param runfolder: a Runfolder instance
:return: a SampleFile instance
|
625941bb3eb6a72ae02ec383
|
def treeChanged(self): <NEW_LINE> <INDENT> for graph in self.graphs: <NEW_LINE> <INDENT> graph.treeChanged(self.event)
|
Update graph option when a parameter has been changed
|
625941bb7b25080760e39309
|
def __idiv__(self, *args): <NEW_LINE> <INDENT> return _vnl_matrixPython.vnl_matrix_vcl_complexLD___idiv__(self, *args)
|
__idiv__(self, vcl_complexLD value) -> vnl_matrix_vcl_complexLD
|
625941bb26238365f5f0ed19
|
def test_openvpn_server_update_noop(self): <NEW_LINE> <INDENT> obj = dict(name='ovpns2', mode='p2p_tls', ca='OpenVPN CA', local_port=1195, tls=TLSKEY, tls_type='auth') <NEW_LINE> self.do_module_test(obj, changed=False)
|
test not updating a OpenVPN server
|
625941bb925a0f43d2549d23
|
def _kill_proc(proc, wait_event, timeout): <NEW_LINE> <INDENT> if not wait_event.wait(timeout): <NEW_LINE> <INDENT> proc.terminate()
|
function used in a separate thread to kill process
|
625941bb2c8b7c6e89b35672
|
def haversine(lon1, lat1, lon2, lat2): <NEW_LINE> <INDENT> lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) <NEW_LINE> dlon = lon2 - lon1 <NEW_LINE> dlat = lat2 - lat1 <NEW_LINE> a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 <NEW_LINE> c = 2 * asin(sqrt(a)) <NEW_LINE> r = 6371 <NEW_LINE> return c * r
|
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
Source: https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
|
625941bb5fc7496912cc3835
|
def _get_proc_create_time(proc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return proc.create_time() if PSUTIL2 else proc.create_time <NEW_LINE> <DEDENT> except (psutil.NoSuchProcess, psutil.AccessDenied): <NEW_LINE> <INDENT> return None
|
Returns the create_time of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
|
625941bb99cbb53fe6792a96
|
def score_it(A,T,m): <NEW_LINE> <INDENT> if A==[] and T==[]: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> score_left=0 if A==[] else prod(map(lambda a: m(a,T), A)) <NEW_LINE> score_right=0 if T==[] else prod(map(lambda t: m(t,A),T)) <NEW_LINE> return min(score_left,score_right)
|
A: list of A items
T: list of T items
m: set membership measure
m(a \in A) gives a membership quality of a into A
This function implements a fuzzy accuracy score:
score(A,T) = min{prod_{a \in A} m(a \in T), prod_{t \in T} m(a \in A)}
where A and T are set representations of the answers
and m is a measure
|
625941bb85dfad0860c3ad08
|
def valueFromText(self, p_str): <NEW_LINE> <INDENT> return 0
|
valueFromText(self, str) -> int
|
625941bb7b180e01f3dc46b4
|
def test_set_metadata(self): <NEW_LINE> <INDENT> m = Model() <NEW_LINE> m.from_document(InselectDocument.load(TESTDATA / 'shapes.inselect')) <NEW_LINE> i = m.index(0, 0) <NEW_LINE> expected = { "catalogNumber": "1", "scientificName": "A", } <NEW_LINE> self.assertEqual(expected, m.data(i, MetadataRole)) <NEW_LINE> m.setData(i, {'catalogNumber': '1234'}, MetadataRole) <NEW_LINE> expected = { "catalogNumber": "1234", "scientificName": "A", } <NEW_LINE> self.assertEqual(expected, m.data(i, MetadataRole))
|
Alter box's metadata
|
625941bbab23a570cc25002f
|
def _cache_and_write_image(self, image_info, device, configdrive=None): <NEW_LINE> <INDENT> _download_image(image_info) <NEW_LINE> self.partition_uuids = _write_image(image_info, device, configdrive) <NEW_LINE> self.cached_image_id = image_info['id']
|
Cache an image and write it to a local device.
:param image_info: Image information dictionary.
:param device: The disk name, as a string, on which to store the
image. Example: '/dev/sda'
:param configdrive: A string containing the location of the config
drive as a URL OR the contents (as gzip/base64)
of the configdrive. Optional, defaults to None.
:raises: ImageDownloadError if the image download fails for any reason.
:raises: ImageChecksumError if the downloaded image's checksum does not
match the one reported in image_info.
:raises: ImageWriteError if writing the image fails.
|
625941bb56ac1b37e6264085
|
@hook.sieve(priority=50) <NEW_LINE> @asyncio.coroutine <NEW_LINE> def ignore_sieve(bot, event, _hook): <NEW_LINE> <INDENT> if _hook.type in ("irc_raw", "event"): <NEW_LINE> <INDENT> return event <NEW_LINE> <DEDENT> if _hook.type == "command" and event.triggered_command in ("unignore", "global_unignore"): <NEW_LINE> <INDENT> return event <NEW_LINE> <DEDENT> if event.mask is None: <NEW_LINE> <INDENT> return event <NEW_LINE> <DEDENT> if is_ignored(event.conn.name, event.chan, event.mask): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return event
|
:type bot: cloudbot.bot.CloudBot
:type event: cloudbot.event.Event
:type _hook: cloudbot.plugin.Hook
|
625941bb3eb6a72ae02ec384
|
def interpolate(self, *args): <NEW_LINE> <INDENT> return _motionplanning.CSpaceInterface_interpolate(self, *args)
|
interpolate(CSpaceInterface self, PyObject * a, PyObject * b, double u) -> PyObject *
Interpolates between two configurations.
|
625941bb3617ad0b5ed67dad
|
def tag_album(path, genre, encoding='mp3', discno='1/1', test=False): <NEW_LINE> <INDENT> year_regex = '\((\d{4})\)$' <NEW_LINE> song_regex = '^(\d{2})\. (.+).' + encoding <NEW_LINE> art, alb = path.split('/')[-2:] <NEW_LINE> artist = art <NEW_LINE> year = re.search(year_regex, alb).group(0) <NEW_LINE> album = alb.split(year)[0].strip() <NEW_LINE> date = year[1:5] <NEW_LINE> songs = [f for f in os.listdir(path) if encoding in f] <NEW_LINE> total = str(len(songs)) <NEW_LINE> for song in songs: <NEW_LINE> <INDENT> match = re.search(song_regex, song) <NEW_LINE> trackno, title = match.groups() <NEW_LINE> if trackno[0] == '0': <NEW_LINE> <INDENT> trackno = trackno[1] <NEW_LINE> <DEDENT> trackno = trackno + '/' + total <NEW_LINE> if test: <NEW_LINE> <INDENT> print("Album: ", album) <NEW_LINE> print("Artist: ", artist) <NEW_LINE> print("Date: ", date) <NEW_LINE> print("Disc No: ", discno) <NEW_LINE> print("Genre: ", genre) <NEW_LINE> print("Title: ", title) <NEW_LINE> print("Track No: ", trackno) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> audio = EasyID3(path + "/" + song) <NEW_LINE> audio['album'] = album <NEW_LINE> audio['artist'] = artist <NEW_LINE> audio['date'] = date <NEW_LINE> audio['discnumber'] = discno <NEW_LINE> audio['genre'] = genre <NEW_LINE> audio['title'] = title <NEW_LINE> audio['tracknumber'] = trackno <NEW_LINE> audio.save() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> print('Cannot open song: ' + song) <NEW_LINE> <DEDENT> except (AttributeError, KeyError): <NEW_LINE> <INDENT> print('Something wrong with writing tag to file') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(audio.pprint() + '\n')
|
Create tag for every song in a given album.
By default, each tag has the following fields:
-Album
-Artist
-Date (Album release date)
-Disc Number
-Genre
-Title
-Track Number
Args:
path: Path to the album directory
genre: Album genre (e.g. 'Rock, 'Indie', 'Jazz')
encoding: Song encoding (e.g. 'mp3', 'm4a', 'flac'); only mp3
is supported at the moment
discno: Disc Number / Total Number of Discs in Album set
test: This option allows you to view what information is written
to the tags before actually doing it
Note:
The function makes a few assumptions regarding the path
and song format (based on a convention I picked). First,
the path argument takes the form:
"~/music/albums/'Artist'/'Album (Year)'"
where Year is four digits. Second, each song takes the form:
"xx. Song Title.mp3"
where xx is a two-digit number (e.g. 05, 12). Last, album covers
have the relative path "artwork/cover.jpg" from the album
directory.
|
625941bbd7e4931a7ee9ddcb
|
def _score_by_len(self, lst): <NEW_LINE> <INDENT> words = [] <NEW_LINE> score = 0 <NEW_LINE> if isinstance(lst, tuple): <NEW_LINE> <INDENT> words = [lst[1]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for each in lst: <NEW_LINE> <INDENT> words.append(each[1]) <NEW_LINE> <DEDENT> <DEDENT> for word in words: <NEW_LINE> <INDENT> if word in unigram_counts: <NEW_LINE> <INDENT> score = score + len(word) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> score = score + len(word) <NEW_LINE> <DEDENT> <DEDENT> return score
|
Score a `word` in the context of the previous word, `prev`.
|
625941bb91af0d3eaac9b8c4
|
def readDataFile(fname = '../DailyLife/OrdonezA_ADLs.txt'): <NEW_LINE> <INDENT> itemList = set([]) <NEW_LINE> dataTable = [] <NEW_LINE> fin = open(fname) <NEW_LINE> fin.readline() <NEW_LINE> fin.readline() <NEW_LINE> for line in fin.readlines(): <NEW_LINE> <INDENT> content = re.split(r'\t\t| \t' ,line.strip()) <NEW_LINE> item = content[2].strip() <NEW_LINE> raw_time = content[0].strip() <NEW_LINE> itemList.add(item) <NEW_LINE> timeStamp = datetime.strptime(raw_time, '%Y-%m-%d %H:%M:%S') <NEW_LINE> dataTable.append([item, timeStamp]) <NEW_LINE> <DEDENT> dataDF = pd.DataFrame(dataTable, columns=['item', 'timeStamp']) <NEW_LINE> dataDF = dataDF.sort_values(['timeStamp'], ascending=True) <NEW_LINE> dataTable = dataDF.values.tolist() <NEW_LINE> return sorted(list(itemList)), dataTable
|
read separated chartevents.csv of each patient
Args:
path: data file path
fName: data file name
Returns:
dataTable: stored as list
|
625941bb1b99ca400220a960
|
def __getitem__(self, i): <NEW_LINE> <INDENT> return self.objects[i]
|
We can be accessed like an array
|
625941bb56b00c62f0f14506
|
def find_title(url, verify=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get(url, stream=True, verify=verify, headers=DEFAULT_HEADERS) <NEW_LINE> content = b'' <NEW_LINE> for byte in response.iter_content(chunk_size=512): <NEW_LINE> <INDENT> content += byte <NEW_LINE> if b'</title>' in content or len(content) > MAX_BYTES: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> content = content.decode('utf-8', errors='ignore') <NEW_LINE> response.close() <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError: <NEW_LINE> <INDENT> LOGGER.exception('Unable to reach URL: %s', url) <NEW_LINE> return None <NEW_LINE> <DEDENT> except ( requests.exceptions.InvalidURL, UnicodeError, LocationValueError, ): <NEW_LINE> <INDENT> LOGGER.debug('Invalid URL: %s', url) <NEW_LINE> return None <NEW_LINE> <DEDENT> content = TITLE_TAG_DATA.sub(r'<\1title>', content) <NEW_LINE> content = QUOTED_TITLE.sub('', content) <NEW_LINE> start = content.rfind('<title>') <NEW_LINE> end = content.rfind('</title>') <NEW_LINE> if start == -1 or end == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> title = web.decode(content[start + 7:end]) <NEW_LINE> title = title.strip()[:200] <NEW_LINE> title = ' '.join(title.split()) <NEW_LINE> title = RE_DCC.sub('', title) <NEW_LINE> return title or None
|
Return the title for the given URL.
|
625941bb3c8af77a43ae364d
|
def test_timeout_lock(self): <NEW_LINE> <INDENT> lock = self.get_success(self.store.try_acquire_lock("name", "key")) <NEW_LINE> self.assertIsNotNone(lock) <NEW_LINE> self.get_success(lock.__aenter__()) <NEW_LINE> lock._looping_call.stop() <NEW_LINE> self.reactor.advance(2 * _LOCK_TIMEOUT_MS / 1000) <NEW_LINE> lock2 = self.get_success(self.store.try_acquire_lock("name", "key")) <NEW_LINE> self.assertIsNotNone(lock2) <NEW_LINE> self.assertFalse(self.get_success(lock.is_still_valid()))
|
Test that we time out locks if they're not updated for ages
|
625941bbe1aae11d1e749b64
|
def Kdiag_grad_X(self, d): <NEW_LINE> <INDENT> return _core.CSqExpCF_Kdiag_grad_X(self, d)
|
Kdiag_grad_X(CSqExpCF self, limix::muint_t const d)
Parameters
----------
d: limix::muint_t const
|
625941bb21a7993f00bc7b9a
|
def __get_system_mis_pls(self, values): <NEW_LINE> <INDENT> smp = values[5].find_all(text=True) <NEW_LINE> if len(smp) < 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.system = SYSTEMS.get(smp[0], 0) <NEW_LINE> safeint = lambda i: int(''.join(c for c in i if c.isdigit())) <NEW_LINE> for line in smp[1:]: <NEW_LINE> <INDENT> if 'stream ' in line: <NEW_LINE> <INDENT> self.is_id = safeint(line[7:]) <NEW_LINE> <DEDENT> elif 'PLS gold ' in line: <NEW_LINE> <INDENT> self.pls_code = safeint(line[9:]) <NEW_LINE> <DEDENT> elif 'PLS root ' in line: <NEW_LINE> <INDENT> self.pls_code = root2gold(safeint(line[9:])) <NEW_LINE> <DEDENT> elif 'PLP ' in line: <NEW_LINE> <INDENT> self.t2mi_plp_id = safeint(line[4:])
|
parse the system, mis, pls and plp from the fifth column of row
|
625941bb66673b3332b91f40
|
def _rosservice_type(service_name): <NEW_LINE> <INDENT> service_type = get_service_type(service_name) <NEW_LINE> if service_type is None: <NEW_LINE> <INDENT> print("Unknown service [%s]"%service_name, file=sys.stderr) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(service_type)
|
Implements 'type' command. Prints service type to stdout. Will
system exit with error if service_name is unknown.
:param service_name: name of service, ``str``
|
625941bb76d4e153a657e9e0
|
def connect(self, name="default-conn"): <NEW_LINE> <INDENT> fwglobals.log.debug("VPP Connect: " + name)
|
Connect to dummy VPP.
|
625941bb099cdd3c635f0b0c
|
def setGoalPos(self, newPos): <NEW_LINE> <INDENT> (row, col) = newPos <NEW_LINE> if self.isOutOfBounds(row, col) or self.isBlocked(row, col): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.goalPos = newPos
|
Takes in a new position, checks that it is valid, and then sets the robotPos to that value if it is.
|
625941bb9f2886367277a740
|
def extendSelectionToEndOfDisplayOrDocumentLine(self): <NEW_LINE> <INDENT> self.SendScintilla(QsciScintilla.SCI_HOMEDISPLAYEXTEND)
|
Extend the selection to the start of the displayed line.
|
625941bbd99f1b3c44c67445
|
def _viterbi(self, outputs: List[int]) -> Tuple[List[int], float]: <NEW_LINE> <INDENT> T = len(outputs) <NEW_LINE> state_path = [[-1]*self.states for _ in range(T)] <NEW_LINE> prob = self.pi * self.B[:,outputs[0]] <NEW_LINE> for t in range(1, T): <NEW_LINE> <INDENT> prob_ = np.ones_like(prob) <NEW_LINE> for i in range(self.states): <NEW_LINE> <INDENT> prob_ji = prob * self.A[:,i].T <NEW_LINE> prob_i, prefix_i = np.max(prob_ji) * self.B[i][outputs[t]], np.argmax(prob_ji) <NEW_LINE> prob_[i] = prob_i <NEW_LINE> state_path[t][i] = prefix_i <NEW_LINE> <DEDENT> prob = prob_ <NEW_LINE> <DEDENT> decode_id = np.argmax(prob) <NEW_LINE> decode = [] <NEW_LINE> step = T-1 <NEW_LINE> while decode_id >= 0: <NEW_LINE> <INDENT> decode.append(decode_id) <NEW_LINE> decode_id = state_path[step][decode_id] <NEW_LINE> step -= 1 <NEW_LINE> <DEDENT> return decode, max(prob)
|
使用DP的维特比解码
|
625941bba4f1c619b28afef0
|
def append(self, item): <NEW_LINE> <INDENT> root = self._root <NEW_LINE> last = root[0] <NEW_LINE> node = [last, root, item] <NEW_LINE> last[1] = root[0] = node <NEW_LINE> self._num += 1 <NEW_LINE> return node
|
Insert the item at the tail of the queue.
Returns the list node, that can be used to remove the
item anytime by passing it to :meth:`remove`
:Parameters:
- `item`: the item to push.
|
625941bba17c0f6771cbdf03
|
@format_manager.register_format_decorator('html_template') <NEW_LINE> def format_html_template(request, data): <NEW_LINE> <INDENT> return render_template(request, data, format_path='html')
|
Return html content with no head/body tags
Base templates must support result['format'] for this to function
|
625941bbcb5e8a47e48b795e
|
@memo <NEW_LINE> def utility(state, score_func): <NEW_LINE> <INDENT> return max(quality(state, action, score_func) for action in get_actions(state))
|
The value of being in a certain state
|
625941bb57b8e32f52483350
|
def draw_image(self, event): <NEW_LINE> <INDENT> dc = event.GetDC() <NEW_LINE> if not dc: <NEW_LINE> <INDENT> dc = wx.ClientDC(self) <NEW_LINE> rect = self.GetUpdateRegion().GetBox() <NEW_LINE> dc.SetClippingRect(rect) <NEW_LINE> <DEDENT> dc.Clear() <NEW_LINE> image = wx.Bitmap(self.image) <NEW_LINE> dc.DrawBitmap(image, 0, 0) <NEW_LINE> self.SetFocus()
|
Draws the image to the panel's background.
|
625941bb82261d6c526ab352
|
def resattnet236(**kwargs): <NEW_LINE> <INDENT> return get_resattnet(blocks=236, model_name="resattnet236", **kwargs)
|
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
|
625941bb32920d7e50b2807c
|
def GET(url: str) -> Union[http.client.HTTPResponse, NoReturn]: <NEW_LINE> <INDENT> request = urllib.request.Request(url) <NEW_LINE> request.add_header("Pragma", "no-cache") <NEW_LINE> request.add_header("User-Agent", f"this-repo-has-x-stars/{__version__}") <NEW_LINE> with urllib.request.urlopen(request) as response: <NEW_LINE> <INDENT> assert response.status == 200, "Oops! HTTP Request failed: {response.status}" <NEW_LINE> return response.read().decode("utf-8")
|
HTTP(s) GET Requests
|
625941bb55399d3f05588563
|
def _tokenize(self, text): <NEW_LINE> <INDENT> return filter(bool, self.re_split.split(text))
|
@param text
@return list
|
625941bbd268445f265b4d1e
|
def list_living_married(self): <NEW_LINE> <INDENT> living_and_married = [] <NEW_LINE> for individual in self._individuals.values(): <NEW_LINE> <INDENT> if individual.spouse is not None and individual.alive: <NEW_LINE> <INDENT> living_and_married.append([individual.name, individual.age]) <NEW_LINE> <DEDENT> <DEDENT> return living_and_married
|
List all living married people in a GEDCOM file
|
625941bb01c39578d7e74cf3
|
def select_random_points(solution, k): <NEW_LINE> <INDENT> node_list = get_all_node(solution.root) <NEW_LINE> points = random.sample(node_list, k=k) <NEW_LINE> return points
|
Obtain `k` points in the solution at random.
:param solution: class `Solution`
:param k: the number of points to obtain
:return: a list of class `Node`
|
625941bb5166f23b2e1a5009
|
def set_cells(self): <NEW_LINE> <INDENT> self.cell_centers_dev[0:self.n_cells].set(self.cell_centers[0:self.n_cells]) <NEW_LINE> self.cell_dirs_dev[0:self.n_cells].set(self.cell_dirs[0:self.n_cells]) <NEW_LINE> self.cell_lens_dev[0:self.n_cells].set(self.cell_lens[0:self.n_cells]) <NEW_LINE> self.cell_rads_dev[0:self.n_cells].set(self.cell_rads[0:self.n_cells]) <NEW_LINE> self.cell_dlens_dev[0:self.n_cells].set(self.cell_dlens[0:self.n_cells]) <NEW_LINE> self.cell_dcenters_dev[0:self.n_cells].set(self.cell_dcenters[0:self.n_cells]) <NEW_LINE> self.cell_dangs_dev[0:self.n_cells].set(self.cell_dangs[0:self.n_cells])
|
Copy cell centers, dirs, lens, and rads to the device from local.
|
625941bbbde94217f3682cab
|
def testTitleByRegexMatchingAllWithBlacklist(self): <NEW_LINE> <INDENT> mockOpener = mock_open(read_data=( dumps(PARAMS) + '\n' + dumps(RECORD0) + '\n' + dumps(RECORD1) + '\n' + dumps(RECORD2) + '\n')) <NEW_LINE> with patch.object(builtins, 'open', mockOpener): <NEW_LINE> <INDENT> reads = Reads() <NEW_LINE> reads.add(Read('id0', 'A' * 70)) <NEW_LINE> reads.add(Read('id1', 'A' * 70)) <NEW_LINE> reads.add(Read('id2', 'A' * 70)) <NEW_LINE> readsAlignments = DiamondReadsAlignments( reads, 'file.json', databaseFilename='database.fasta') <NEW_LINE> blacklist = ['gi|887699|gb|DQ37780 Squirrelpox virus 1296/99', 'gi|887699|gb|DQ37780 Squirrelpox virus 55'] <NEW_LINE> result = list(readsAlignments.filter(titleRegex='pox', blacklist=blacklist)) <NEW_LINE> self.assertEqual(2, len(result)) <NEW_LINE> self.assertEqual('id1', result[0].read.id) <NEW_LINE> self.assertEqual('id2', result[1].read.id)
|
Filtering with a title regex that matches all alignments
must keep everything, except for any blacklisted titles.
|
625941bb0a366e3fb873e6c7
|
def shuffle_deck(deck): <NEW_LINE> <INDENT> rand.shuffle(deck) <NEW_LINE> return deck
|
Shuffles a standard deck of cards using random.shuffle
|
625941bbd8ef3951e32433ed
|
def test_original_server_disconnects(tctx): <NEW_LINE> <INDENT> tctx.server.state = ConnectionState.OPEN <NEW_LINE> assert ( Playbook(http.HttpLayer(tctx, HTTPMode.transparent)) >> ConnectionClosed(tctx.server) << CloseConnection(tctx.server) )
|
Test that we correctly handle the case where the initial server conn is just closed.
|
625941bbde87d2750b85fc3e
|
def test_dirty_scenario(simple_linear_model): <NEW_LINE> <INDENT> model = simple_linear_model <NEW_LINE> model.setup() <NEW_LINE> assert not model.dirty <NEW_LINE> scenario = Scenario(model, "test", size=42) <NEW_LINE> assert model.dirty
|
Adding a scenario to a model makes it dirty
|
625941bb097d151d1a222d0c
|
def SetNormalFont(self, font): <NEW_LINE> <INDENT> self._normal_font = font
|
Sets the normal font for drawing tab labels.
:param Font `font`: the new font to use to draw tab labels in their normal, un-selected state.
|
625941bba8370b7717052750
|
def forward(self, text, text_len, triple_id, triple_words, triple_len, enc_text_last, flag, test_flag): <NEW_LINE> <INDENT> triple_len_sum=torch.sum(triple_len,1)+2 <NEW_LINE> if flag=='pos': <NEW_LINE> <INDENT> enc_te = self.encode(text,text_len,self.lstm_text,True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enc_te = enc_text_last <NEW_LINE> <DEDENT> if test_flag: <NEW_LINE> <INDENT> enc_text = enc_te.expand(triple_id.size(0), -1, -1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enc_text = enc_te <NEW_LINE> <DEDENT> enc_triple=self.encode(triple_words,triple_len_sum,self.lstm_tri,True) <NEW_LINE> att_mask = get_attn_key_pad_mask(text, triple_words) <NEW_LINE> att=self.tri2text_att(enc_text,enc_triple,att_mask) <NEW_LINE> triple_text_rep=att.matmul(enc_text) <NEW_LINE> enc_triple_final=self.encode(torch.cat((enc_triple,triple_text_rep),dim=2),triple_len_sum,self.lstm_tri_att, False) <NEW_LINE> index_ht=triple_len[:,0]-1 <NEW_LINE> index_r1=index_ht+2 <NEW_LINE> index_rt=index_r1+triple_len[:,1]-1 <NEW_LINE> index_t1=index_rt+2 <NEW_LINE> index_tt=index_t1+triple_len[:,2]-1 <NEW_LINE> h1=enc_triple_final[:,0,:] <NEW_LINE> ht=self.batched_index_select(enc_triple_final,1,index_ht).squeeze() <NEW_LINE> r1=self.batched_index_select(enc_triple_final,1,index_r1).squeeze() <NEW_LINE> rt=self.batched_index_select(enc_triple_final,1,index_rt).squeeze() <NEW_LINE> t1=self.batched_index_select(enc_triple_final,1,index_t1).squeeze() <NEW_LINE> tt=self.batched_index_select(enc_triple_final,1,index_tt).squeeze() <NEW_LINE> h_text=self.entity_linear(torch.cat((h1,ht),dim=1)) <NEW_LINE> r_text=self.relation_linear(torch.cat((r1,rt),dim=1)) <NEW_LINE> t_text=self.entity_linear(torch.cat((t1,tt),dim=1)) <NEW_LINE> h = h_text.matmul(self.A)+self.entity_bias(triple_id[:,0]) <NEW_LINE> t = t_text.matmul(self.B)+self.entity_bias(triple_id[:,2]) <NEW_LINE> r = r_text.matmul(self.C)+self.relation_bias(triple_id[:,1]) <NEW_LINE> score=torch.sum(torch.abs(h + r - t), 1) <NEW_LINE> return score,enc_te
|
train:
text[batch_size,max_text_len]
text_len[batch_size]
triple_id[batch_size,3]
triple_words[batch_size,max_triple_len]
triple_len[batch_size,3]
test:
text[1,len]
text_len[1]
triple_id[batch_size,3]
triple_words[batch_size,max_triple_len]
triple_len[batch_size,3]
|
625941bb30bbd722463cbc73
|
def set(self, name, obj): <NEW_LINE> <INDENT> assert isinstance(obj, ssobject.W_Root) <NEW_LINE> if self.closure: <NEW_LINE> <INDENT> loc = self.scope.get(name, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loc = self.globalscope.get(name, None) <NEW_LINE> <DEDENT> if loc is not None: <NEW_LINE> <INDENT> loc.obj = obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.put(name, obj)
|
update existing location or create new location
|
625941bb8c0ade5d55d3e86f
|
def __repr__(self): <NEW_LINE> <INDENT> return "<Customer: %s %s, %s>" % (self.first_name, self.last_name, self.password)
|
Convenience method to show information about user.
|
625941bbd4950a0f3b08c202
|
def handlePbaData(self, initRequest): <NEW_LINE> <INDENT> response = False <NEW_LINE> initRequest = json.loads(initRequest) <NEW_LINE> lookup = initRequest["lookup"] <NEW_LINE> id = initRequest["id"] <NEW_LINE> source = initRequest.get("source", None), <NEW_LINE> line = initRequest["line"] + 1, <NEW_LINE> column = initRequest["column"], <NEW_LINE> path = initRequest["path"] <NEW_LINE> definition = False <NEW_LINE> completionWords = str(source[0].split("\r\n")[line[0] - 1][ : column[0]]).split(" ")[ -1 ].split(".") <NEW_LINE> for line in source[0].split("\r\n"): <NEW_LINE> <INDENT> if completionWords[0] + " =" in line or completionWords[0] + " =" in line: <NEW_LINE> <INDENT> definition = line <NEW_LINE> <DEDENT> <DEDENT> className = self.getPbaClass(path, definition) <NEW_LINE> if not definition: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> if "= PbaProObject" in definition or "=PbaProObject" in definition: <NEW_LINE> <INDENT> if lookup == "completions": <NEW_LINE> <INDENT> return json.dumps({"id": id, "results": pbaDefinitions[className][lookup]}) <NEW_LINE> <DEDENT> elif lookup == "tooltip": <NEW_LINE> <INDENT> return json.dumps({"id": id, "results": pbaDefinitions[className][lookup][completionWords[-1]]}) <NEW_LINE> <DEDENT> elif lookup == "arguments": <NEW_LINE> <INDENT> index = len(completionWords[-1].split(",")) - 1 <NEW_LINE> argData = pbaDefinitions[className][lookup][completionWords[-1].split("(")[0]] <NEW_LINE> response = {"id": id, "results": [ {"raw_docstring": argData[0]["raw_docstring"], "name": argData[0]["name"], "docstring": argData[0]["docstring"], "params": argData[0]["params"], "paramindex": index, "bracketstart": [index], "description": argData[0]["description"] } ] } <NEW_LINE> return json.dumps(response) <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> return response
|
Method that injects intellisense for PbaProObject
|
625941bb851cf427c661a3c2
|
def filename(stem, dtype, shape=None, multiple_records=False): <NEW_LINE> <INDENT> suffix = suffix_from_dtype(dtype, shape, multiple_records) <NEW_LINE> return stem + '.' + suffix
|
Build a filename, given a stem, element datatype, and record array shape
filename('mydata', data.dtype, data.shape)
filename('mydata', data)
:param stem: variable name without suffix or dimensions
:param dtype: numpy data type, may or may not include dimensions
:param shape: if dtype does not include record shape, use this
:param multiple_records: True if first dtype dimension is the record dimension and should be skipped
|
625941bb07d97122c417873c
|
def state_get(self): <NEW_LINE> <INDENT> return BTorrentHandlerMirror.state_get_from_original(self) <NEW_LINE> rv = {}
|
Summarize internal state using nested dicts, lists, ints and strings
|
625941bb92d797404e304039
|
def getAuthenticatedMember(): <NEW_LINE> <INDENT> pass
|
Return the currently authenticated member object
o If no valid credentials are passed in the request, return
the Anonymous User.
o Permission: Public
|
625941bb15fb5d323cde09bb
|
def setAsDefault(self, captionAssetId): <NEW_LINE> <INDENT> kparams = KalturaParams() <NEW_LINE> kparams.addStringIfDefined("captionAssetId", captionAssetId) <NEW_LINE> self.client.queueServiceActionCall("caption_captionasset", "setAsDefault", None, kparams) <NEW_LINE> if self.client.isMultiRequest(): <NEW_LINE> <INDENT> return self.client.getMultiRequestResult() <NEW_LINE> <DEDENT> resultNode = self.client.doQueue()
|
Markss the caption as default and removes that mark from all other caption assets of the entry.
|
625941bb4c3428357757c1db
|
def dest_form_view(request): <NEW_LINE> <INDENT> c = {} <NEW_LINE> c.update(csrf(request)) <NEW_LINE> a = Destination() <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> dest_form = DestForm(request.POST, instance=a) <NEW_LINE> if dest_form.is_valid(): <NEW_LINE> <INDENT> a = dest_form.save() <NEW_LINE> return HttpResponseRedirect('destinations/dest_form_complete/') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> dest_form = DestForm(instance=a) <NEW_LINE> <DEDENT> return render_to_response('destinations/dest_form.html', { 'dest_form': dest_form, }, context_instance=RequestContext(request))
|
View for destination creation form.
|
625941bb498bea3a759b9961
|
def setCorrection(self, *args): <NEW_LINE> <INDENT> return _DataModel.ResponseFIR_setCorrection(self, *args)
|
setCorrection(ResponseFIR self, Seiscomp::Core::Optional< double >::Impl const & correction)
|
625941bb7c178a314d6ef30a
|
def process_if_notification(self, i): <NEW_LINE> <INDENT> if i.server in self.pending_servers: <NEW_LINE> <INDENT> self.pending_servers.remove(i.server) <NEW_LINE> <DEDENT> if i.is_connected(): <NEW_LINE> <INDENT> self.interfaces[i.server] = i <NEW_LINE> self.add_recent_server(i) <NEW_LINE> i.send_request({'method':'blockchain.headers.subscribe','params':[]}) <NEW_LINE> if i.server == self.default_server: <NEW_LINE> <INDENT> self.switch_to_interface(i.server) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.interfaces.pop(i.server, None) <NEW_LINE> self.heights.pop(i.server, None) <NEW_LINE> if i == self.interface: <NEW_LINE> <INDENT> self.set_status('disconnected') <NEW_LINE> <DEDENT> self.disconnected_servers.add(i.server) <NEW_LINE> <DEDENT> self.notify('interfaces')
|
Handle interface addition and removal through notifications
|
625941bb63b5f9789fde6f96
|
def test_cppcheck(): <NEW_LINE> <INDENT> root_dir = os.path.join(os.path.dirname(__file__), '..') <NEW_LINE> dirs = [os.path.join(root_dir, d) for d in ['include', 'share', 'src', 'tools', 'plugins']] <NEW_LINE> enabled_checks = 'warning,style,information,performance,portability,missingInclude' <NEW_LINE> cmd = ['cppcheck', '--quiet', '--language=c++', '--inline-suppr', '--error-exitcode=1', '--enable=' + enabled_checks, '--suppress=copyCtorAndEqOperator', '-I', os.path.join(root_dir, 'python/scrimmage/bindings/include'), '-I', os.path.join(root_dir, 'include')] + dirs <NEW_LINE> print('running the following command:') <NEW_LINE> print(' '.join(cmd)) <NEW_LINE> subprocess.check_call(cmd)
|
Code static analysis using cppcheck.
|
625941bb7cff6e4e81117836
|
def _expand(self, normalization, csphase, lmax_calc, backend, nthreads): <NEW_LINE> <INDENT> from .shcoeffs import SHCoeffs <NEW_LINE> if normalization.lower() == '4pi': <NEW_LINE> <INDENT> norm = 1 <NEW_LINE> <DEDENT> elif normalization.lower() == 'schmidt': <NEW_LINE> <INDENT> norm = 2 <NEW_LINE> <DEDENT> elif normalization.lower() == 'unnorm': <NEW_LINE> <INDENT> norm = 3 <NEW_LINE> <DEDENT> elif normalization.lower() == 'ortho': <NEW_LINE> <INDENT> norm = 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt' " + "or 'unnorm'. Input value is {:s}." .format(repr(normalization)) ) <NEW_LINE> <DEDENT> cilm = backend_module( backend=backend, nthreads=nthreads).SHExpandGLQ( self.data[:, :self.nlon-self.extend], self.weights, self.zeros, norm=norm, csphase=csphase, lmax_calc=lmax_calc) <NEW_LINE> coeffs = SHCoeffs.from_array(cilm, normalization=normalization.lower(), csphase=csphase, units=self.units, copy=False) <NEW_LINE> return coeffs
|
Expand the grid into real spherical harmonics.
|
625941bb8e05c05ec3eea222
|
def test_generate_basic_project_land_cover(self): <NEW_LINE> <INDENT> project_name = "grid_standard_basic_land_cover" <NEW_LINE> project_manager, db_sessionmaker = dbt.get_project_session(project_name, self.gssha_project_directory, map_type=1) <NEW_LINE> db_session = db_sessionmaker() <NEW_LINE> db_session.add(project_manager) <NEW_LINE> db_session.commit() <NEW_LINE> mask_name = '{0}.msk'.format(project_name) <NEW_LINE> msk_file = WatershedMaskFile(project_file=project_manager, session=db_session) <NEW_LINE> msk_file.generateFromWatershedShapefile(self.shapefile_path, cell_size=1000, out_raster_path=mask_name, ) <NEW_LINE> ele_file = ElevationGridFile(project_file=project_manager, session=db_session) <NEW_LINE> ele_file.generateFromRaster(self.elevation_path, self.shapefile_path) <NEW_LINE> mapTableFile = MapTableFile(project_file=project_manager) <NEW_LINE> mapTableFile.addRoughnessMapFromLandUse("roughness", db_session, self.land_use_grid, land_use_grid_id='glcf', ) <NEW_LINE> project_manager.setCard('TOT_TIME', '180') <NEW_LINE> project_manager.setCard('TIMESTEP', '10') <NEW_LINE> project_manager.setCard('HYD_FREQ', '15') <NEW_LINE> project_manager.setCard('SUMMARY', '{0}.sum'.format(project_name), add_quotes=True) <NEW_LINE> project_manager.setCard('OUTLET_HYDRO', '{0}.otl'.format(project_name), add_quotes=True) <NEW_LINE> project_manager.setCard('PRECIP_UNIF', '') <NEW_LINE> project_manager.setCard('RAIN_INTENSITY', '2.4') <NEW_LINE> project_manager.setCard('RAIN_DURATION', '30') <NEW_LINE> project_manager.setCard('START_DATE', '2017 02 28') <NEW_LINE> project_manager.setCard('START_TIME', '14 33') <NEW_LINE> project_manager.writeInput(session=db_session, directory=self.gssha_project_directory, name=project_name) <NEW_LINE> db_session.close() <NEW_LINE> self._compare_basic_model_idx_maps(project_name)
|
Tests generating a basic GSSHA project with land cover
|
625941bb711fe17d82542222
|
def __init__(self, sink, sinkbox="inbox", sinkcontrol = None): <NEW_LINE> <INDENT> self.sink = sink <NEW_LINE> self.sinkbox = sinkbox <NEW_LINE> self.sinkcontrol = sinkcontrol
|
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
|
625941bb4e696a04525c92fd
|
def call_proc(self, procedure_name, parameters, out_type='CURSOR'): <NEW_LINE> <INDENT> out_type = self.db_type(out_type) <NEW_LINE> res = self.cursor.callproc(procedure_name, parameters) <NEW_LINE> if out_type is cx_Oracle.CURSOR: <NEW_LINE> <INDENT> res = self._fetch(res) <NEW_LINE> <DEDENT> return res
|
Вызов ORACLE процедуры
:param procedure_name: имя процедуры
:type procedure_name: string
:param parameters: список параметров
:type parameters: tuple
:param out_type: тип возвращаемого значения
:type out_type: _BASEVARTYPE
:return: результат выполнения процедуры
|
625941bb287bf620b61d391e
|
def GetStdoutQuiet(cmdlist): <NEW_LINE> <INDENT> job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> out = job.communicate()[0].decode("utf-8") <NEW_LINE> if job.returncode != 0: <NEW_LINE> <INDENT> raise GypError("Error %d running %s" % (job.returncode, cmdlist[0])) <NEW_LINE> <DEDENT> return out.rstrip("\n")
|
Returns the content of standard output returned by invoking |cmdlist|.
Ignores the stderr.
Raises |GypError| if the command return with a non-zero return code.
|
625941bbd8ef3951e32433ee
|
def __delitem__(self, key): <NEW_LINE> <INDENT> del self.variables[key]
|
Delete a variable.
|
625941bb55399d3f05588564
|
def acquire(context): <NEW_LINE> <INDENT> pass
|
Acquire a storage instance of this backend from context.
|
625941bb4e4d5625662d428d
|
def resize_image(image, height, width): <NEW_LINE> <INDENT> org_height, org_width = image.shape[:2] <NEW_LINE> height_ratio = float(height)/org_height <NEW_LINE> width_ratio = float(width)/org_width <NEW_LINE> if height_ratio > width_ratio: <NEW_LINE> <INDENT> resized = cv2.resize(image,(int(org_height*height_ratio),int(org_width*height_ratio))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resized = cv2.resize(image,(int(org_height*width_ratio),int(org_width*width_ratio))) <NEW_LINE> <DEDENT> return resized
|
渡された画像をheightとwidthの大きい方に合わせてリサイズします。
アスペクト比の変更はしません。
|
625941bb8da39b475bd64e28
|
def index_queryset(self, using=None): <NEW_LINE> <INDENT> return self.get_model().objects.filter(publish_time__lte=datetime.datetime.now())
|
Used when the entire index for model is updated.
|
625941bba934411ee375154b
|
def build_data_dir(): <NEW_LINE> <INDENT> make_change("./data") <NEW_LINE> make("train") <NEW_LINE> make("validation") <NEW_LINE> make("test") <NEW_LINE> os.chdir("..")
|
Add a data directory to project.
|
625941bbeab8aa0e5d26da0f
|
def test_hmtk_histogram_1D_edgecase(self): <NEW_LINE> <INDENT> xdata = np.array([3.1, 4.1, 4.56, 4.8, 5.2]) <NEW_LINE> xbins = np.arange(3.0, 5.35, 0.1) <NEW_LINE> expected_counter = np.array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 1.]) <NEW_LINE> np.testing.assert_array_almost_equal( utils.hmtk_histogram_1D(xdata, xbins), expected_counter)
|
Tests the 1D hmtk histogram with edge cases
Should be exactly equivalent to numpy's histogram function
|
625941bb1f037a2d8b9460af
|
def test_handling_missing_runtime_analyser(dep_workbench, dependent_object): <NEW_LINE> <INDENT> plugin = dep_workbench.get_plugin('exopy.app.dependencies') <NEW_LINE> for b in plugin.build_deps.contributions.values(): <NEW_LINE> <INDENT> setattr(b, 'run', ['dummy']) <NEW_LINE> <DEDENT> core = dep_workbench.get_plugin('enaml.workbench.core') <NEW_LINE> dep = core.invoke_command(ANALYSE, {'obj': dependent_object, 'dependencies': ['runtime']}) <NEW_LINE> assert 'runtime' in dep.errors and 'dummy' in dep.errors['runtime']
|
Test analysing the dependencies of an object for which a runtime
collector is missing.
|
625941bb7047854f462a12bd
|
def get_payment_details(self, pay_key=None): <NEW_LINE> <INDENT> if not pay_key: <NEW_LINE> <INDENT> raise PayPalError('You must specify a pay_key') <NEW_LINE> <DEDENT> data = { 'payKey': pay_key, } <NEW_LINE> resp, cont = self.do_request(action='PaymentDetails', data=data) <NEW_LINE> if 'responseEnvelope.ack' not in cont: <NEW_LINE> <INDENT> raise PayPalError('Error: Invalid PayPal response: {0}'.format(cont)) <NEW_LINE> <DEDENT> if cont['responseEnvelope.ack'].lower() != 'success': <NEW_LINE> <INDENT> errors = [] <NEW_LINE> for k,v in cont.iteritems(): <NEW_LINE> <INDENT> if k.find('error') > -1 and k.find('message') > -1: <NEW_LINE> <INDENT> v = urllib.unquote_plus(v) <NEW_LINE> errors.append(v.replace('+', ' ')) <NEW_LINE> <DEDENT> <DEDENT> raise PayPalError('Error requesting payment: {0}'.format('. '.join(errors))) <NEW_LINE> <DEDENT> return cont
|
Gets information about a payment
:keyword pay_key: Pay key to lookup
:rtype: response as dict
|
625941bb92d797404e30403a
|
def _xml_escape_attr(attr, skip_single_quote=True): <NEW_LINE> <INDENT> escaped = _AMPERSAND_RE.sub('&', attr) <NEW_LINE> escaped = (attr .replace('"', '"') .replace('<', '<') .replace('>', '>')) <NEW_LINE> if not skip_single_quote: <NEW_LINE> <INDENT> escaped = escaped.replace("'", "'") <NEW_LINE> <DEDENT> return escaped
|
Escape the given string for use in an HTML/XML tag attribute.
By default this doesn't bother with escaping `'` to `'`, presuming that
the tag attribute is surrounded by double quotes.
|
625941bbb5575c28eb68deaf
|
def __eq__(self, other): <NEW_LINE> <INDENT> return (self.parent == other.parent and all(abs(u_x - u_y) < EPSILON for (x, u_x), (y, u_y) in zip(self, other)))
|
Return True if range and values/degree_of_membeship are equal,
False otherwise.
|
625941bbbd1bec0571d904ea
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.