code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def remloners(eastvel,northvel,iterations,loners): <NEW_LINE> <INDENT> if loners > 0: <NEW_LINE> <INDENT> loners = 0; <NEW_LINE> iterations = iterations + 1; <NEW_LINE> (xmax,ymax) = eastvel.shape; <NEW_LINE> for i in range(1,xmax-1): <NEW_LINE> <INDENT> for j in range(1,ymax-1): <NEW_LINE> <INDENT> if not (math.isnan(... | function REMLONERS recursively removes lone pixels
lone pixels are defined as pixels with NaN values on 3 or more sides
eastvel = east velocities
northvel = north velocities
iterations = number of iterations so far
loners = number of lone pixels found and removed during each iteration | 625941e34527f215b584c848 |
def label_encode(M, force_columns=[]): <NEW_LINE> <INDENT> M = utils.check_sa(M) <NEW_LINE> new_dtype = [] <NEW_LINE> result_arrays = [] <NEW_LINE> classes = {} <NEW_LINE> for (col_name, fmt) in M.dtype.descr: <NEW_LINE> <INDENT> if 'S' in fmt or 'O' in fmt or col_name in force_columns: <NEW_LINE> <INDENT> col = M[col_... | Changes string cols to ints so that there is a 1-1 mapping between
strings and ints
Parameters
----------
M : numpy.ndarray
structured array
force_columns : list of str
By default, label_encode will only encode string columns. If the name
of a numerical column is also present in force_columns, then that
... | 625941e43eb6a72ae02ec8dc |
def uninstall_hook(cr, registry): <NEW_LINE> <INDENT> with api.Environment.manage(): <NEW_LINE> <INDENT> env = api.Environment(cr, SUPERUSER_ID, {}) <NEW_LINE> rule = env.ref('base.res_partner_rule') <NEW_LINE> rule.write({ 'active': False, 'domain_force': ( "['|','|',('company_id.child_ids','child_of'," "[user.company... | Restore product rule to base value.
Args:
cr (Cursor): Database cursor to use for operation.
rule_ref (string): XML ID of security rule to remove the
`domain_force` from. | 625941e48a43f66fc4b54456 |
def normalize(self, s): <NEW_LINE> <INDENT> return ''.join(strip_color(s).split()) | Removes escape sequences (e.g. colored output) and all whitespace from string s. | 625941e47047854f462a17fa |
def test_create_enterpriseuser_error(self): <NEW_LINE> <INDENT> EnterpriseUserFactory(enterprise_id=self.uuid) <NEW_LINE> assert EnterpriseUser.objects.count() == 1 <NEW_LINE> args = [self.uuid] <NEW_LINE> with mock.patch('enterprise_data.tests.test_utils.EnterpriseUserFactory') as mock_factory: <NEW_LINE> <INDENT> moc... | Manangement command should successfully be able to create EnterpriseUser | 625941e44a966d76dd551408 |
def payment_statuses_edit(self, payment_status): <NEW_LINE> <INDENT> self.parameters['paymentStatus'] = json.dumps(payment_status) <NEW_LINE> return self.post('/reference/payment-statuses/' + payment_status['code'] + '/edit') | :param payment_status: object
:return: Response | 625941e4de87d2750b86018b |
def output_detect_result(ifiles, ofiles, is_simple=False): <NEW_LINE> <INDENT> n = ensure_equal_len(ifiles, ofiles) <NEW_LINE> if is_simple: <NEW_LINE> <INDENT> for i in range(n): <NEW_LINE> <INDENT> print(ifiles[i]) <NEW_LINE> print(ofiles[i]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(n): <... | Print ifiles and ofiles under the following formats.
Simple format:
1.inp
1.out
2.inp
2.out
Normal format:
'1.inp', '1.out'
'2.inp', '2.out'
Number of test case(s): 2. | 625941e4d53ae8145f87a65d |
def _get_style_dict(self, gc, rgbFace): <NEW_LINE> <INDENT> attrib = {} <NEW_LINE> forced_alpha = gc.get_forced_alpha() <NEW_LINE> if gc.get_hatch() is not None: <NEW_LINE> <INDENT> attrib['fill'] = "url(#%s)" % self._get_hatch(gc, rgbFace) <NEW_LINE> if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0 ... | Generate a style string from the GraphicsContext and rgbFace. | 625941e4187af65679ca5515 |
def post_course_certificate(client, username, certificate, visible_date): <NEW_LINE> <INDENT> client.credentials.post({ 'username': username, 'status': 'awarded' if certificate.is_valid() else 'revoked', 'credential': { 'course_run_key': str(certificate.course_id), 'mode': certificate.mode, 'type': COURSE_CERTIFICATE, ... | POST a certificate that has been updated to Credentials | 625941e4d58c6744b4258053 |
def get_user_read_hour(self, begin_date, end_date): <NEW_LINE> <INDENT> data = { "begin_date": begin_date, "end_date": end_date } <NEW_LINE> access_token = self.settings.GET_GLOBAL_ACCESS_TOKEN(self) <NEW_LINE> url = "https://api.weixin.qq.com/datacube/getuserreadhour?access_token=" + access_token <NEW_LINE> data = req... | Get user read hour
param data:begin_date, end_date
return :Raw data that wechat return. | 625941e4cc40096d61595d44 |
def textMargin(self, position): <NEW_LINE> <INDENT> spacing = self.__rightLayout.spacing() <NEW_LINE> w = 0 <NEW_LINE> if position == self.LeftSide: <NEW_LINE> <INDENT> w = self.__leftWidget.sizeHint().width() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w = self.__rightWidget.sizeHint().width() <NEW_LINE> <DEDENT> if... | Public method to get the text margin for a side.
@param position side to get margin for (E5LineEdit.LeftSide,
E5LineEdit.RightSide)
@return text margin (integer) | 625941e4f548e778e58cd974 |
def ls(self, *args): <NEW_LINE> <INDENT> return _egglib_binding.Container_ls(self, *args) | ls(Container self, unsigned int pos) -> unsigned int | 625941e426238365f5f0f269 |
def get_figures(self): <NEW_LINE> <INDENT> return self.__figures | Returns a list of all figures in this Gui. | 625941e48c0ade5d55d3edb3 |
def parentState(self): <NEW_LINE> <INDENT> return QState() | QState QAbstractState.parentState() | 625941e4a17c0f6771cbe444 |
def email_user( self, subject: str, message: str, from_email: Optional[str] = None ) -> int: <NEW_LINE> <INDENT> return send_mail(subject, message, from_email, [self.email]) | Send an email to this user. | 625941e4796e427e537b09be |
def _secretToPassphrase(secret): <NEW_LINE> <INDENT> minC = 32 <NEW_LINE> maxC = 127 <NEW_LINE> dC = maxC - minC <NEW_LINE> ret = '' <NEW_LINE> for i in range(512): <NEW_LINE> <INDENT> if secret == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> c = ( secret % dC ) + minC <NEW_LINE> ret += chr(c) <NEW_LINE> secret ... | Convert an integer (used as secret for Shamir) to a passphrase for cryptsetup. Use
only 7bit ASCII to be on the safe side. (Note that cryptsetup supports up to 512 chars.)
Just to be extra safe, we use the range from 32 (space, inclusive) through 127
(DEL, exclusive).
Note: if you change this algorithm, you will break... | 625941e43539df3088e2e740 |
def add(self, viewlet): <NEW_LINE> <INDENT> if not viewlet.name in self.keys(): <NEW_LINE> <INDENT> self[viewlet.name] = viewlet | Adds a registered viewlet to the Library dict | 625941e47d847024c06be6b5 |
def test_show_running(self): <NEW_LINE> <INDENT> conv_helper = self.setup_conversation(started=True, name=u"myconv") <NEW_LINE> response = self.client.get(conv_helper.get_view_url('show')) <NEW_LINE> conversation = response.context[0].get('conversation') <NEW_LINE> self.assertEqual(conversation.name, u"myconv") <NEW_LI... | Test showing the conversation | 625941e47cff6e4e81117d7b |
def next( self, method: Union[str, Callable[["Flight"], Iterator["Flight"]]], ) -> Optional["Flight"]: <NEW_LINE> <INDENT> fun = ( getattr(self.__class__, method) if isinstance(method, str) else method ) <NEW_LINE> return next(fun(self), None) | Returns the first segment of trajectory yielded by flight.method()
>>> flight.next("go_around")
>>> flight.next("runway_change")
>>> flight.next(lambda f: f.aligned_on_ils("LFBO")) | 625941e4a219f33f34628d59 |
def filter_and_extract(imgs, extraction_function, parameters, memory_level=0, memory=Memory(location=None), verbose=0, confounds=None, sample_mask=None, copy=True, dtype=None): <NEW_LINE> <INDENT> if verbose > 0: <NEW_LINE> <INDENT> class_name = enclosing_scope_name(stack_level=10) <NEW_LINE> <DEDENT> if isinstance(img... | Extract representative time series using given function.
Parameters
----------
imgs : 3D/4D Niimg-like object
Images to be masked. Can be 3-dimensional or 4-dimensional.
extraction_function : function
Function used to extract the time series from 4D data. This function
should take images as argument and r... | 625941e4287bf620b61d3e57 |
def get_observations(xmin, xmax, n): <NEW_LINE> <INDENT> list_observations = [] <NEW_LINE> list_y = [] <NEW_LINE> for _ in range(n): <NEW_LINE> <INDENT> i = np.random.uniform(low=xmin, high=xmax) <NEW_LINE> list_observations.append((i,)) <NEW_LINE> list_y.append(density(i)) <NEW_LINE> <DEDENT> return list_observations,... | Get a list of random observation
:param xmin: minimum x value where to plot the density
:param xmax: maximum x value where to plot the density
:param n: number of observation
:return: two lists of the same length. One list of the observation points,
and one list of the evaluation of the density at the observation poi... | 625941e44e696a04525c9842 |
def removeFromFirstToLastFromList(myList,start,end): <NEW_LINE> <INDENT> i=end <NEW_LINE> while i>=start: <NEW_LINE> <INDENT> aux = myList[:] <NEW_LINE> myList.pop(i) <NEW_LINE> i=i-1 <NEW_LINE> <DEDENT> return myList | in:param myList,start,end
out:return:myList | 625941e4b7558d58953c5301 |
def glcm_mbb(img, mask): <NEW_LINE> <INDENT> positions = dwi.util.bounding_box(mask) <NEW_LINE> slices = [slice(*t) for t in positions] <NEW_LINE> img = img[slices] <NEW_LINE> mask = mask[slices] <NEW_LINE> img[~mask] = 0 <NEW_LINE> feats = glcm_props(img, ignore_zeros=True) <NEW_LINE> output = list(feats.values()) <NE... | Single GLCM features for selected area inside minimum bounding box. | 625941e4ac7a0e7691ed44ba |
def can_eval(self): <NEW_LINE> <INDENT> return all(type(a) not in (Var, Func) for a in self.args) | Test if each argument term already has value. | 625941e499fddb7c1c9de784 |
def test_file_full_pipeline(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tempdir, in_dir, out_dir = self._create_tempdir_structure('input', 'output') <NEW_LINE> in_file, out_file, cfg_file = self._create_single_file_test( 'file.txt', 'file.txt.tar.xz.gpg', tempdir, in_dir, out_dir, ... | Basic test of a single file archive, compress, encrypt and backup. | 625941e4925a0f43d254a270 |
@lru_cache() <NEW_LINE> def get_git_changeset(path=None): <NEW_LINE> <INDENT> base_dir = path if path else os.path.dirname(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> git_tag = subprocess.Popen( 'git describe --exact-match HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=base_dir, unive... | Returns a hash of the latest git changeset. | 625941e4b545ff76a891420a |
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = 'glenda@NEURONMEXICO.Com' <NEW_LINE> user = get_user_model().objects.create_user(email, 'test123') <NEW_LINE> self.assertEqual(user.email, email.lower()) | Test the email for a new user is normalized | 625941e4dd821e528d63b59b |
def velo_iterator(data, linefreq=None, useFreq=True, subvframe=True): <NEW_LINE> <INDENT> for ii in range(data.CRPIX1.shape[0]): <NEW_LINE> <INDENT> if hasattr(data,'SPECTRA'): <NEW_LINE> <INDENT> npix = data.SPECTRA.shape[1] <NEW_LINE> CRPIX = data.CRPIX1[ii] <NEW_LINE> if useFreq: <NEW_LINE> <INDENT> CRVAL = data.CRV... | Yield a velocity axis array | 625941e42ae34c7f2600d526 |
def resnet18_v1b(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): <NEW_LINE> <INDENT> model = ResNetV1b(BasicBlockV1b, [2, 2, 2, 2], **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> from .model_store import get_model_file <NEW_LINE> model.load_params(get_model_file('resnet%d_v%db'%(18, 1), root=r... | Constructs a ResNetV1b-18 model.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
ctx : Context, default CPU
The context in which to load the pretrained weights.
dilated:... | 625941e4de87d2750b86018c |
def test_mle(self): <NEW_LINE> <INDENT> data = self._dist.simulation(10) <NEW_LINE> mle = core.frequency_estimation(data) <NEW_LINE> self.assertGreaterEqual(mle.estimated.loglikelihood(data), self._dist.loglikelihood(data)) | Test ordinal ML estimation | 625941e4d7e4931a7ee9e314 |
def payback_time(market_cap, net_income, estimated_growth_rate): <NEW_LINE> <INDENT> yearly_income = net_income <NEW_LINE> total_payback = 0 <NEW_LINE> years = 0 <NEW_LINE> while (total_payback < market_cap): <NEW_LINE> <INDENT> if yearly_income <= 0 or estimated_growth_rate <= 0: <NEW_LINE> <INDENT> years = -1 <NEW_LI... | Determine the amount of years to get your money back if you were to buy the
entire company at the current market cap given the TTM net income and
expected growth rate.
For more details, read PaybackTime by Phil Town for information on this
calculation. Basically its the summation of each years future value (FV
functio... | 625941e47d43ff24873a3099 |
def select_sort(data_list): <NEW_LINE> <INDENT> list_len = len(data_list) <NEW_LINE> for i in range(0, list_len - 1): <NEW_LINE> <INDENT> tem_min_index = i <NEW_LINE> for j in range(i + 1, list_len): <NEW_LINE> <INDENT> if data_list[tem_min_index] > data_list[j]: <NEW_LINE> <INDENT> tem_min_index = j <NEW_LINE> <DEDENT... | 选择排序
:param data_list: 待排序列表
:return: | 625941e4187af65679ca5516 |
def match(self, path): <NEW_LINE> <INDENT> return bool(self._re.match(path)) | Try to match a path against this ignore pattern.
:param path: Path to match (relative to ignore location)
:return: boolean | 625941e49b70327d1c4e11cc |
@dramatiq.actor(max_retries=0, max_age=300000, store_results=True) <NEW_LINE> def find_smallest_in_big_array(data): <NEW_LINE> <INDENT> workers_count = 4 <NEW_LINE> task_list = [] <NEW_LINE> slice_start = 0 <NEW_LINE> slice_end = None <NEW_LINE> len_per_worker = len(data) // workers_count <NEW_LINE> for i in range(1, w... | Lets distribute calculations on different workers
:param data:
:return: | 625941e44f88993c3716c459 |
def main(args=None): <NEW_LINE> <INDENT> args = args or sys.argv[1:] <NEW_LINE> opts = PARSER.parse_args(args) <NEW_LINE> selection = opts.plot or (_JOINED) <NEW_LINE> data = opts.data[opts.begin:opts.end] <NEW_LINE> radio_plot(data, opts.title, selection) | iotlab-plot radio command | 625941e430dc7b7665901d58 |
def copySetFrom (self, other): <NEW_LINE> <INDENT> if other.hasTemperatureWarningReason(): <NEW_LINE> <INDENT> self.temperatureWarningReason=other.temperatureWarningReason <NEW_LINE> self._myHasTemperatureWarningReason=other._myHasTemperatureWarningReason <NEW_LINE> self._myTemperatureWarningReasonRequested=other._myTe... | This method will copy to self only the leaves & descendant that are set in ***other*** | 625941e4167d2b6e31218f8a |
def callCallback(self, callback_id, message): <NEW_LINE> <INDENT> if self.hasCallback(callback_id): <NEW_LINE> <INDENT> callback = self.callbacks[callback_id] <NEW_LINE> self.callbacks[callback_id] = None <NEW_LINE> return callback(message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Invoke a callback defined on the Device, if it exists. | 625941e4ec188e330fd5ab8d |
def delete(self, item): <NEW_LINE> <INDENT> last_node = None <NEW_LINE> current = self.head <NEW_LINE> while current is not None: <NEW_LINE> <INDENT> if(current.data == item): <NEW_LINE> <INDENT> if last_node: <NEW_LINE> <INDENT> last_node.next = current.next <NEW_LINE> <DEDENT> if self.head == current: <NEW_LINE> <IND... | Delete the given item from this linked list, or raise ValueError | 625941e4167d2b6e31218f8b |
def get_plugin_title(self): <NEW_LINE> <INDENT> return _('Internal console') | Return widget title | 625941e43617ad0b5ed682ec |
def max(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Bag): <NEW_LINE> <INDENT> raise TypeError("Expected a Bag") <NEW_LINE> <DEDENT> retval = Bag(_similar=self) <NEW_LINE> retval._update_type(other) <NEW_LINE> for key, val in other.iteritems(): <NEW_LINE> <INDENT> retval[key] = max(val, self[key]) <NEW_LI... | B.max(bag) -> new bag with maximum value for each key in originals | 625941e430bbd722463cc1bd |
def test_list_json(simple_script: PipTestEnvironment) -> None: <NEW_LINE> <INDENT> result = simple_script.pip("list", "--format=json") <NEW_LINE> data = json.loads(result.stdout) <NEW_LINE> assert {"name": "simple", "version": "1.0"} in data <NEW_LINE> assert {"name": "simple2", "version": "3.0"} in data | Test json formatting of list command | 625941e48e7ae83300e4b3c3 |
def isPalindrome(self, s): <NEW_LINE> <INDENT> a = [i for i in s.lower() if i.isdigit() or i.isalpha()] <NEW_LINE> return a[::-1] == a | :type s: str
:rtype: bool | 625941e4442bda511e8be808 |
def loglike(self, params): <NEW_LINE> <INDENT> q = 2*self.endog - 1 <NEW_LINE> X = self.exog <NEW_LINE> return np.sum(np.log(np.clip(self.cdf(q*np.dot(X,params)),1e-20, 1))) | Log-likelihood of probit model (i.e., the normal distribution).
Parameters
----------
params : array-like
The parameters of the model.
Returns
-------
loglike : float
The log-likelihood function of the model evaluated at `params`.
See notes.
Notes
-----
.. math:: \ln L=\sum_{i}\ln\Phi\left(q_{i}x_{i}^{\p... | 625941e4e8904600ed9f2328 |
def find_or_create_bucket(**kw): <NEW_LINE> <INDENT> return kw.get('bucket') | Find or create a bucket, returning the bucket.
Use the keywords to name the bucket.
For NOOP, provide a bucket to get a test bucket back. | 625941e4cdde0d52a9e5342b |
def deal_hand(n): <NEW_LINE> <INDENT> hand={} <NEW_LINE> num_vowels = int(math.ceil(n / 3)) <NEW_LINE> for i in range(num_vowels): <NEW_LINE> <INDENT> x = random.choice(VOWELS) <NEW_LINE> hand[x] = hand.get(x, 0) + 1 <NEW_LINE> <DEDENT> for i in range(num_vowels, n): <NEW_LINE> <INDENT> x = random.choice(CONSONANTS) <N... | Returns a random hand containing n lowercase letters.
ceil(n/3) letters in the hand should be VOWELS (note,
ceil(n/3) means the smallest integer not less than n/3).
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int... | 625941e430bbd722463cc1be |
def addFolders(self, curPath, dirs): <NEW_LINE> <INDENT> sql = '' <NEW_LINE> qsz = 0 <NEW_LINE> for dirName in dirs: <NEW_LINE> <INDENT> path_ = normpathEx(curPath + dirName) <NEW_LINE> sql += (" union all " if sql else " insert into Folders (path) ") <NEW_LINE> sql += " select '%s' " % path_.replace("'", "''") <NEW_LI... | For internal usage.
| 625941e45fc7496912cc3d74 |
def test_with_inner_text_1(self): <NEW_LINE> <INDENT> elem = etree.Element('id') <NEW_LINE> elem.text = '162' <NEW_LINE> actual = drupal_to_solr.with_inner_text(elem, 'feast') <NEW_LINE> assert len(actual) == 1 <NEW_LINE> actual = actual[0] <NEW_LINE> assert actual.tag == 'field' <NEW_LINE> assert actual.get('name') ==... | When it's an "id" field. | 625941e49b70327d1c4e11cd |
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True): <NEW_LINE> <INDENT> ret = OrderedDict() <NEW_LINE> if not isinstance(properties, list): <NEW_LINE> <INDENT> properties = properties.split(',') <NEW_LINE> <DEDENT> while 'name' in properties: <NEW_LINE> <INDENT> properties.remove('name')... | <<<<<<< HEAD
=======
.. versionadded:: 2015.5.0
>>>>>>> 2018.3
Return information about (all) storage pools
zpool : string
optional name of storage pool
properties : string
<<<<<<< HEAD
comma-separated list of properties to display
parsable : boolean
display data in python... | 625941e4507cdc57c63070d9 |
def execute(self, ignore_errors=True, use_progressbar=False): <NEW_LINE> <INDENT> keywords_set = KeywordsSet() <NEW_LINE> _logger.debug("Fetching Maven and executing Maven index checker") <NEW_LINE> maven_index_checker_dir = get_files_dir() <NEW_LINE> maven_index_checker_jar = path.join(maven_index_checker_dir, "maven-... | Collect Maven keywords. | 625941e48c3a8732951587b5 |
def rightSideView(self, root): <NEW_LINE> <INDENT> self.rightSideView_dfs(root, 0) <NEW_LINE> return self.result | :type root: TreeNode
:rtype: List[int] | 625941e4566aa707497f4959 |
def _get_jinja_error(trace, context=None): <NEW_LINE> <INDENT> if not context: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> out = '' <NEW_LINE> error = _get_jinja_error_slug(trace) <NEW_LINE> line = _get_jinja_error_line(trace) <NEW_LINE> msg = _get_jinja_error_message(trace) <NEW_LINE> add_log = False <NEW_LIN... | Return the error line and error message output from
a stacktrace.
If we are in a macro, also output inside the message the
exact location of the error in the macro | 625941e407d97122c4178c8a |
def addSynchronizeAction(self): <NEW_LINE> <INDENT> m = self._menu <NEW_LINE> ac = self._actionCollection <NEW_LINE> m.addAction(ac.viewer_sync_cursor) | Add an action telling the viewer to
always try syncing with the input editor. | 625941e4eab8aa0e5d26df50 |
def get_eval_size(params): <NEW_LINE> <INDENT> eval_sizes = { 'cifar10': 10000, 'cifar10_4000': 10000, 'cifar10_4000_uda': 10000, 'cifar10_4000_mpl': 10000, 'cifar100': 10000, 'cifar100_10k': 10000, 'imagenet_heldout': 25000, 'imagenet': 50000, 'imagenet_noisy_student': 50000, 'imagenet_uda': 50000, 'imagenet_10_percen... | Builds `eval_data` depends on `params.dataset_name`. | 625941e499fddb7c1c9de785 |
def infer_type(self, value: typing.Any) -> type: <NEW_LINE> <INDENT> from d3m.primitive_interfaces import base as primitive_interfaces_base <NEW_LINE> if utils.is_type(value) and issubclass(value, primitive_interfaces_base.PrimitiveBase): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> re... | Infers a structural type of ``value``.
There is a special case if ``value`` is a primitive class, in that case it is returned
as is.
Parameters
----------
value:
Value to infer a type for.
Returns
-------
Type of ``value``, or ``value`` itself if ``value`` is a primitive class. | 625941e415fb5d323cde0f0b |
def __repr__(self): <NEW_LINE> <INDENT> return "{name}".format( name=self.name ) | str version of object, currently name only | 625941e4adb09d7d5db6cb83 |
def toJSON(self): <NEW_LINE> <INDENT> data = { 'message': self.team_msg, 'message_timestamp': str(self.timestamp) } <NEW_LINE> return data | Obtain a JSON style representation of object. | 625941e4435de62698dfe043 |
def fromString(self, tagstring, keepcase=False): <NEW_LINE> <INDENT> tagstring = j.data.text.hrd2machinetext(tagstring) <NEW_LINE> if not tagstring: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tags = tagstring.split() <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> if tag.find(':') > 0: <NEW_LINE> <INDENT> key = tag... | go from string to Tag class filled in
@param tagstring: example "important customer:kristof"
@type tagstring: string | 625941e48a43f66fc4b54457 |
def _extract_link_text(s, rec, exceptions={}): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> regex = re.compile(r'(\[\[(.+?)\]\])') <NEW_LINE> while re.search(regex, s): <NEW_LINE> <INDENT> tmp = re.search(regex, s) <NEW_LINE> t = tmp.group(2) <NEW_LINE> if t.find('|') >= 0: <NEW_LINE> <INDENT> t = t[t.find('|') + 1:] <NEW_L... | [[hoge]][[fuga]] -> ['hoge', 'fuga'] | 625941e4bf627c535bc135c6 |
def delete_user_secret(self, user_id: str, name: str) -> PrivXAPIResponse: <NEW_LINE> <INDENT> response_status, data = self._http_delete( UrlEnum.VAULT.USER_SECRET, path_params={"user_id": user_id, "name": name}, ) <NEW_LINE> return PrivXAPIResponse(response_status, HTTPStatus.OK, data) | Delete a user's secret.
Returns:
PrivXAPIResponse | 625941e491f36d47f21ac8ed |
def __makeBruch(other): <NEW_LINE> <INDENT> if type(other) is Bruch: <NEW_LINE> <INDENT> return other <NEW_LINE> <DEDENT> elif type(other) is int: <NEW_LINE> <INDENT> b1 = Bruch(other, 1) <NEW_LINE> return b1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('nicht korrekte Typen') | Ein Bruch erstellen
:param other: Bruch oder int
:return: Bruch
:raise TypeError: nicht korrekte Typen | 625941e494891a1f4081bea1 |
def my_rebalance(context, data): <NEW_LINE> <INDENT> long_weight, short_weight = my_compute_weights(context) <NEW_LINE> for security in context.portfolio.positions: <NEW_LINE> <INDENT> if security not in context.longs and security not in context.shorts and data.can_trade(security): <NEW_LINE> <INDENT> order_target_perc... | Rebalance every day 1 hour after market open. | 625941e4dd821e528d63b59c |
def plotVelTrial(sp, varList, iterList, noise_sigma, **kw): <NEW_LINE> <INDENT> r = kw.pop('r', 0) <NEW_LINE> c = kw.pop('c', 0) <NEW_LINE> sigmaTitle = kw.pop('sigmaTitle', True) <NEW_LINE> cbar = kw.pop('cbar', True) <NEW_LINE> annotations = kw.pop('annotations', None) <NEW_LINE> C = ag... | Plot a parameter sweep of velocity data.
These are either bump slope or line fit error. | 625941e4d164cc6175783145 |
def parents(self, vertices): <NEW_LINE> <INDENT> parents = set() <NEW_LINE> for v in vertices: <NEW_LINE> <INDENT> for p in self.vertices[v].parents: <NEW_LINE> <INDENT> parents.add(p.name) <NEW_LINE> <DEDENT> <DEDENT> return parents | Get parents of a vertex or set of vertices.
:param vertices: iterable of vertex names.
:return: set of parents. | 625941e43d592f4c4ed1d459 |
def find_all_indexes(text, pattern): <NEW_LINE> <INDENT> assert isinstance(text, str), 'text is not a string: {}'.format(text) <NEW_LINE> assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) <NEW_LINE> if pattern == '': <NEW_LINE> <INDENT> return [i for i in range(len(text))] <NEW_LINE> <DEDENT> ... | Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
O(n) where n is the number of letters in the text | 625941e444b2445a33932489 |
def p_indexList2(t): <NEW_LINE> <INDENT> t[0] = [t[1]] <NEW_LINE> repGrammar.append(t.slice) | indexList : columnIndex | 625941e415baa723493c436e |
def create_captcha_image(self, chars, color, background): <NEW_LINE> <INDENT> image = Image.new('RGB', (self._width, self._height), background) <NEW_LINE> draw = Draw(image) <NEW_LINE> def _draw_character(c): <NEW_LINE> <INDENT> font_u = random.choice(self.truefonts_0) <NEW_LINE> if 64<ord(c)<97: <NEW_LINE> <INDENT> fo... | Create the CAPTCHA image itself.
:param chars: text to be generated.
:param color: color of the text.
:param background: color of the background.
The color should be a tuple of 3 numbers, such as (0, 255, 255). | 625941e41f037a2d8b9465f3 |
def askDir(): <NEW_LINE> <INDENT> win = tk.Tk() <NEW_LINE> win.title() <NEW_LINE> win.withdraw() <NEW_LINE> directory = askdirectory() <NEW_LINE> win.destroy() <NEW_LINE> return(directory) | function for ask user witch directory should be used by program | 625941e43cc13d1c6d3c776e |
def is_descendant_of(self, target, node): <NEW_LINE> <INDENT> return target.tree_id == node.tree_id and target.lft > node.lft and target.rgt < node.rgt | :returns: ``True`` if the node if a descendant of another node given
as an argument, else, returns ``False``
See: :meth:`easytree.managers.EasyTreeManager.is_descendant_of` | 625941e457b8e32f52483894 |
def _synapse_delete(self, syn): <NEW_LINE> <INDENT> uri = '/entity/{id}/table/deleteRows'.format(id=self.tableId) <NEW_LINE> return syn.restPOST(uri, body=json.dumps(RowSelection( rowIds=[row['rowId'] for row in self], etag=self.etag, tableId=self.tableId))) | Delete the rows that result from a table query.
Example::
syn.delete(syn.tableQuery('select name from %s where no_good = true' % schema1.id)) | 625941e4a934411ee3751a8b |
@sell.command() <NEW_LINE> @click.argument('appname') <NEW_LINE> @click.pass_context <NEW_LINE> def destroy(ctx, appname): <NEW_LINE> <INDENT> config = ctx.obj["config"] <NEW_LINE> if appname in os.listdir("/etc/nginx/site-includes/"): <NEW_LINE> <INDENT> if destroy_app(appname): <NEW_LINE> <INDENT> config.log(UxString... | Stop/Remove a current app that is currently
being run on the host.
Stop worker processes and disable site from sites-enabled
| 625941e4fff4ab517eb2f834 |
def apply_datasets_list(self, list_): <NEW_LINE> <INDENT> self.x = self.x.loc[list_] <NEW_LINE> self.n = self.n.loc[list_] | Reduce datasets according to another file | 625941e456ac1b37e62645be |
def rotateRight(self, head, k): <NEW_LINE> <INDENT> if k == 0 or head == None: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> old_head = head <NEW_LINE> pre = old_head <NEW_LINE> cnt = 1 <NEW_LINE> while pre != None and pre.next != None: <NEW_LINE> <INDENT> pre = pre.next <NEW_LINE> cnt += 1 <NEW_LINE> <DEDENT> k ... | :type head: ListNode
:type k: int
:rtype: ListNode | 625941e4be8e80087fb21033 |
def argtopk(a: T, k: int, split_every: int | None = None) -> T: <NEW_LINE> <INDENT> if isinstance(a, da.Array): <NEW_LINE> <INDENT> return a.argtopk(k, split_every=split_every) <NEW_LINE> <DEDENT> idx = np.argpartition(a, -k) <NEW_LINE> if k > 0: <NEW_LINE> <INDENT> idx = idx[..., -k:] <NEW_LINE> <DEDENT> else: <NEW_LI... | If a is a :class:`dask.array.Array`, invoke a.argtopk; else reimplement
the functionality in plain numpy. | 625941e455399d3f05588aad |
def replace_required_status_checks_contexts_of_protected_branch(owner: str, repo: str, branch: str, json=None, auth=None) -> requests.Response: <NEW_LINE> <INDENT> return requests.put( "https://api.github.com/repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts".format(owner=owner, repo=rep... | :param owner:
:param repo:
:param branch:
:param json:
:param auth:
:return: :class:`Response <Response>` object
:rtype: requests.Response | 625941e466673b3332b92487 |
def clean(self): <NEW_LINE> <INDENT> super(NGReportForm, self).clean() <NEW_LINE> cdata = self.cleaned_data <NEW_LINE> activity = cdata.get('activity') <NEW_LINE> if (activity and activity.name == ACTIVITY_CAMPAIGN and not cdata.get('campaign')): <NEW_LINE> <INDENT> msg = 'Please select an option from the list.' <NEW_L... | Clean Form. | 625941e4925a0f43d254a271 |
def reportPage(request): <NEW_LINE> <INDENT> user_obj=request.user <NEW_LINE> ins_id=user_obj.instructor.id <NEW_LINE> batches=Batch.objects.filter(instructor_id=ins_id) <NEW_LINE> return render(request,"Instructor/report.html",{"batches":batches}) | renders template that shows all the batches of instructor for report generation | 625941e455399d3f05588aac |
def ctf_Instance_03(self): <NEW_LINE> <INDENT> for x in self.envdict.keys(): <NEW_LINE> <INDENT> e = self.envdict[x] <NEW_LINE> e.Clear() <NEW_LINE> e.Reset() <NEW_LINE> c = e.BuildClass("C4", "(is-a USER)") <NEW_LINE> e.LoadInstancesFromString("(d of C4)(f of C4)") <NEW_LINE> d = e.FindInstance('d') <NEW_LINE> f = e.F... | Testing: LoadInstancesFromString | 625941e432920d7e50b285ca |
def do_next(self, n, b_timeout_prompt): <NEW_LINE> <INDENT> return self.execute_command(self.GS_NEXT + " " + str(n), b_timeout=b_timeout_prompt) | Perform n 'next' commands. Returns output. | 625941e40a366e3fb873ec14 |
def attack_result(self, damage): <NEW_LINE> <INDENT> return EventResult(damage, 0, 3, 1) | damages monster some, and gives some gold and XP upon defeat.
:param damage: amount of damage dealt
:return: | 625941e4ff9c53063f47c5e8 |
def __init__(self, position=0.0, TapChanger=None, *args, **kw_args): <NEW_LINE> <INDENT> self.position = position <NEW_LINE> self._TapChanger = None <NEW_LINE> self.TapChanger = TapChanger <NEW_LINE> super(SvTapStep, self).__init__(*args, **kw_args) | Initialises a new 'SvTapStep' instance.
@param position: The floating point tap position. To get integer value scale with range and round off.
@param TapChanger: The tap changer associated with the tap step state. | 625941e41f5feb6acb0c4f40 |
def extrapolate( self, shape: SpectralShape, extrapolator: Optional[Type[TypeExtrapolator]] = None, extrapolator_kwargs: Optional[Dict] = None, ) -> SpectralDistribution: <NEW_LINE> <INDENT> shape_start, shape_end, shape_interval = as_float_array( [ self.shape.start, self.shape.end, self.shape.interval, ] ) <NEW_LINE> ... | Extrapolate the spectral distribution in-place according to
*CIE 15:2004* and *CIE 167:2005* recommendations or given extrapolation
arguments.
Parameters
----------
shape
Spectral shape used for extrapolation.
extrapolator
Extrapolator class type to use as extrapolating function.
extrapolator_kwargs
Argume... | 625941e42c8b7c6e89b35bb4 |
def insert_element_built_in_type(xsd_string, xpath, element_type_name, request): <NEW_LINE> <INDENT> xsd_tree = XSDTree.build_tree(xsd_string) <NEW_LINE> namespaces = get_namespaces(xsd_string) <NEW_LINE> default_prefix = get_default_prefix(namespaces) <NEW_LINE> xpath = xpath.replace(default_prefix + ":", LXML_SCHEMA_... | Insert element with a builtin type in xsd string.
Args:
xsd_string: xsd string
xpath: xpath where to insert the element
element_type_name: name of the type to insert
request: request
Returns: | 625941e4236d856c2ad44bd6 |
def i2c_write(self, address, args): <NEW_LINE> <INDENT> data = [address, PrivateConstants.I2C_WRITE] <NEW_LINE> for item in args: <NEW_LINE> <INDENT> item_lsb = item & 0x7f <NEW_LINE> data.append(item_lsb) <NEW_LINE> item_msb = (item >> 7) & 0x7f <NEW_LINE> data.append(item_msb) <NEW_LINE> <DEDENT> self._send_sysex(Pri... | Write data to an i2c device.
:param address: i2c device address
:param args: A variable number of bytes to be sent to the device
passed in as a list | 625941e40a50d4780f66728c |
def letterCombinations(self, digits): <NEW_LINE> <INDENT> c = [] <NEW_LINE> self.dfs(c, "", digits) <NEW_LINE> return c | :type digits: str
:rtype: List[str] | 625941e424f1403a92600f59 |
def create_arguments(self, filename, file, config_file, eslint_config: str = '', language: language = language('JavaScript'), global_vars: typed_list(str) = (), eslint_env: typed_list(str) = (), ): <NEW_LINE> <INDENT> args = ( '--no-ignore', '--no-color', '-f=json', '--stdin', '--stdin-filename=' + filename, ) <NEW_LIN... | :param eslint_config: The location of the .eslintrc config file. | 625941e491af0d3eaac9be13 |
def filterBookingBrains(self, booking_brains, start_date, end_date): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for brain in booking_brains: <NEW_LINE> <INDENT> booking_start_date = brain['start'] <NEW_LINE> booking_end_date = brain['end'] <NEW_LINE> is_booked = self.isBooked(booking_start_date, booking_end_date, start... | Returns brains booked in interval of start date and end date
| 625941e4379a373c97cfaf3d |
def test_get_random_matrix(self): <NEW_LINE> <INDENT> similarity_matrix = [[1.0, 0.89441830645266462, 0.95097107828998639], [0.89441830645266462, 1.0, 0.97565300931621723], [0.95097107828998639, 0.97565300931621723, 1.0]] <NEW_LINE> random_matrix = part.get_random_matrix(similarity_matrix) <NEW_LINE> for row in r... | Tests the get_random_matrix function. | 625941e476d4e153a657ef29 |
def dropdown(): <NEW_LINE> <INDENT> choices = list() <NEW_LINE> con=pymysql.connect(user='root', password='', host='localhost', database='parking_locator') <NEW_LINE> cur = con.cursor() <NEW_LINE> sql="select lot_area_id from parking_lot_details order by lot_area_id asc" <NEW_LINE> cur.execute(sql) <NEW_LINE> result = ... | Title: Tk dropdown example
Website: Python Tutorials
URL:https://pythonspot.com/tk-dropdown-example/
Author: -
Date Posted: -
Date Referred: 10 May 2020 | 625941e4596a897236089eb2 |
def stop(self): <NEW_LINE> <INDENT> if self.is_running(): <NEW_LINE> <INDENT> DynamipsHypervisor.stop(self) <NEW_LINE> log.info("stopping Dynamips PID={}".format(self._process.pid)) <NEW_LINE> try: <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> self._process.terminate() <NEW_LINE> self._process.wait(1) <NEW_LINE> <DED... | Stops the Dynamips hypervisor process. | 625941e4460517430c394571 |
def blank_not(validator): <NEW_LINE> <INDENT> def blank_not_validator(value, expect): <NEW_LINE> <INDENT> if value == '': <NEW_LINE> <INDENT> raise ValueError( '%s does not accept blank values' % blank_not_validator.__name__ ) <NEW_LINE> <DEDENT> return validator(value, expect) <NEW_LINE> <DEDENT> return wraps(blank_no... | blank_not(validator) -> validator_blank_not
Short circuit a validator and raise ValueError if an empty value is given. | 625941e473bcbd0ca4b2c46c |
def _parseLeafTableCellHeader(self, data, offset, freespace=None): <NEW_LINE> <INDENT> headerlist = list() <NEW_LINE> overflowpagenum = 0 <NEW_LINE> payloadsizeincell = 0 <NEW_LINE> overflowpageoffset = offset <NEW_LINE> recordnum = 0 <NEW_LINE> payloadlen = 0 <NEW_LINE> length = 0 <NEW_LINE> if freespace is False: <NE... | Parse a B-Tree Leaf Page Cell Header, given it's starting absolute byte
offset.
Pass absolute starting byte offset for the cell header to be decoded.
Returns tuple containing a list of tuples in the form
[(String type,int length),...], and the starting offset of the payload
fields. | 625941e43cc13d1c6d3c776f |
def __str__(self): <NEW_LINE> <INDENT> return "[{}] ({}) {}".format(self.__class__.__name__, self.id, self.__dict__) | prints dictionary of attributes of the instance | 625941e4ab23a570cc25057c |
def go(self, poller_configurations): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> notify( CachableSourcePollersAboutToStartEvent(poller_configurations)) <NEW_LINE> logger.info("Starting pollers") <NEW_LINE> exit_ = threading.Event() <NEW_LINE> for config in poller_configurations: <NEW_LINE> <INDENT> kwargs = {'exit_': ... | Create threaded pollers and start configured polling cycles
| 625941e416aa5153ce36286e |
def print_diff(ip, common, diff1, diff2): <NEW_LINE> <INDENT> logging.info('IP: %s', ip) <NEW_LINE> if common: <NEW_LINE> <INDENT> common = [' {0}'.format(elem) for elem in common] <NEW_LINE> logging.info('\n'.join(common)) <NEW_LINE> <DEDENT> if diff1: <NEW_LINE> <INDENT> diff = ['+ {0}'.format(elem) for elem in diff... | Print out the common, added, and removed network objects between 2 IPs.
Args:
ip: the IP being compared against
common: the network objects shared between the two IPs
('ip' and the other passed into options.cmp)
diff1: the network objects present in 'ip' but not in the other IP
... | 625941e4cdde0d52a9e5342c |
def set_PageSize(self, value): <NEW_LINE> <INDENT> super(GetMessagesThatContainInputSet, self)._set_input('PageSize', value) | Set the value of the PageSize input for this Choreo. ((optional, integer) The number of results per page to search through. Defaults to 50.) | 625941e43346ee7daa2b3165 |
def adam(x, dx, config=None): <NEW_LINE> <INDENT> if config is None: <NEW_LINE> <INDENT> config = {} <NEW_LINE> <DEDENT> config.setdefault('learning_rate', 1e-3) <NEW_LINE> config.setdefault('beta1', 0.9) <NEW_LINE> config.setdefault('beta2', 0.999) <NEW_LINE> config.setdefault('epsilon', 1e-8) <NEW_LINE> config.setdef... | Uses the Adam update rule, which incorporates moving averages of both the
gradient and its square and a bias correction term.
config format:
- learning_rate: Scalar learning rate.
- beta1: Decay rate for moving average of first moment of gradient.
- beta2: Decay rate for moving average of second moment of gradient.
- ... | 625941e42eb69b55b151ccab |
def test_sparse_array_bits_in_common(): <NEW_LINE> <INDENT> s = core.SparseArray() <NEW_LINE> t = core.SparseArray() <NEW_LINE> s.set_range(2, 4) <NEW_LINE> t.set_range(5, 4) <NEW_LINE> assert s.has_bits_in_common(t) <NEW_LINE> s = core.SparseArray() <NEW_LINE> t = core.SparseArray() <NEW_LINE> s.set_range(2, 4) <NEW_L... | Tests SparseArray behavior for has_bits_in_common(). | 625941e41f037a2d8b9465f4 |
def decrypt_block(block, key, verbose=False): <NEW_LINE> <INDENT> assert len(block) == BLOCK_SIZE <NEW_LINE> assert len(key) == KEY_SIZE <NEW_LINE> sumation = c_uint32(SUMATION) <NEW_LINE> delta = c_uint32(DELTA) <NEW_LINE> for index in range(0, ROUNDS): <NEW_LINE> <INDENT> block[1].value -= ((block[0].value << 4) + ke... | Decrypt a single 64-bit block using a given key
@param block: list of two c_uint32s
@param key: list of four c_uint32s | 625941e44f88993c3716c45a |
@pytest.fixture() <NEW_LINE> def boto3_stubber(request, mocker): <NEW_LINE> <INDENT> __tracebackhide__ = True <NEW_LINE> created_stubbers = [] <NEW_LINE> mocked_clients = {} <NEW_LINE> region = "us-east-1" <NEW_LINE> module_under_test = request.module.__name__.replace("test_", "") <NEW_LINE> mocked_client_factory = moc... | Create a function to easily mock boto3 clients.
To mock a boto3 service simply pass the name of the service to mock and
the mocked requests, where mocked_requests is an object containing the method to mock,
the response to return and the expected params for the boto3 method that gets called.
The function makes use of... | 625941e430c21e258bdfa897 |
def test_service_check(): <NEW_LINE> <INDENT> print("test defaults; Issues Warnings") <NEW_LINE> doc = Doc(None) <NEW_LINE> alive = doc.is_live <NEW_LINE> print("Server:", doc.server_url, "Service", doc.service_path, "Alive:", alive) <NEW_LINE> assert alive <NEW_LINE> print("test bad ags file; Issues Warnings") <NEW_LI... | Test the Doc when created with Doc(path, server).
No need to test Doc(), IDE will give a warning about missing parameter,
and we will crash right away (programming error) | 625941e4dc8b845886cb592d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.