code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def Draw( self, surface ): <NEW_LINE> <INDENT> for textLine in self.textLines: <NEW_LINE> <INDENT> textLine.Draw( surface ) | Draw all text lines of this TextPage. | 625941cdf8510a7c17cf97fd |
def test_taint_union_memory_memory(self): <NEW_LINE> <INDENT> Triton = TritonContext() <NEW_LINE> Triton.setArchitecture(ARCH.X86_64) <NEW_LINE> Triton.taintMemory(MemoryAccess(0x2000, 4)) <NEW_LINE> self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 4))) <NEW_LINE> Triton.taintUnion(MemoryAccess(0x2000, 4), M... | Check tainting union memory U memory. | 625941cd21a7993f00bc7def |
def url_normalize(url, charset='utf-8'): <NEW_LINE> <INDENT> def _clean(string): <NEW_LINE> <INDENT> string = unicode(unquote(string), 'utf-8', 'replace') <NEW_LINE> return unicodedata.normalize('NFC', string).encode('utf-8') <NEW_LINE> <DEDENT> default_port = { 'ftp': 21, 'telnet': 23, 'http': 80, 'gopher': 70, 'news'... | Sometimes you get an URL by a user that just isn't a real
URL because it contains unsafe characters like ' ' and so on. This
function can fix some of the problems in a similar way browsers
handle data entered by the user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki... | 625941cdd4950a0f3b08c44f |
def make_boot(): <NEW_LINE> <INDENT> for r in topo.ALL_MACHINES: <NEW_LINE> <INDENT> append(boot(r), "config_helpers/boot.sh", {"node": r}) | Making boot script | 625941cd711fe17d8254246c |
@core <NEW_LINE> def transpose(a, dim0, dim1): <NEW_LINE> <INDENT> dims = _transpose_dims(len(a.shape), dim0, dim1) <NEW_LINE> return P.transpose(a, dims) | Map of 'transpose' pytorch method. | 625941cd71ff763f4b54978b |
def update_learning_rate(optimizer, lr): <NEW_LINE> <INDENT> for param_group in optimizer.param_groups: <NEW_LINE> <INDENT> param_group['lr'] = lr <NEW_LINE> <DEDENT> return optimizer | Updates learning rate for given optimizer.
Args:
optimizer: Optimizer object
lr: New learning rate
Returns:
optimizer: Updated optimizer object
s | 625941cd56b00c62f0f14759 |
def ReadDictionary(self): <NEW_LINE> <INDENT> pass | ReadDictionary(self: BinaryArchiveReader) -> ArchivableDictionary
Reads a complete Rhino.Collections.ArchivableDictionary from the archive.
Returns: The newly instantiated object. | 625941cd460517430c394285 |
def fts2maskmap(in_, out, ftsport, **kwargs): <NEW_LINE> <INDENT> return wrapper.starcomm("$SMURF_DIR/fts2maskmap", "fts2maskmap", in_, out, ftsport, **kwargs) | Mask time series data for a SCUBA-2 map with FTS-2 in the beam.
Runs the command: $SMURF_DIR/fts2maskmap .
Arguments
---------
`in_` : str,filename
Input time series cubes
out : str,filename
Output time series cubes
ftsport : str
FTS-2 port: tracking or image [TRACKING]
Notes
-----
See http://www.star... | 625941cdf7d966606f6aa104 |
def system_monitor_power_alert_action(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") <NEW_LINE> if kwargs.pop('delete_system_monitor', False) is True: <NEW_LINE> <INDENT> delete_s... | Auto Generated Code
| 625941cd0c0af96317bb82e8 |
def get_entity_from_dict(dict_obj,datastore_client,kind,exclude,id_=None): <NEW_LINE> <INDENT> if id_ is None: <NEW_LINE> <INDENT> task_key = datastore_client.key(kind) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> task_key = datastore_client.key(kind,id_) <NEW_LINE> <DEDENT> d = datastore.Entity(key=task_key, exclude_... | Builds a google datastore entity from a dictionary
args:
-id_(optional): the unique identifier, if a URL is given it MUST be hashed before: String
-dict_obj: the dictonary to store : dict
-datastore_client: instance of datasrore client (Object)
-kind: entity kind :String
-exclude: entity's attribut... | 625941cd4428ac0f6e5ba8f2 |
def read_dump(file_name, addrs, script_addrs, hd_master_addr_old): <NEW_LINE> <INDENT> with open(file_name, encoding='utf8') as inputfile: <NEW_LINE> <INDENT> found_addr = 0 <NEW_LINE> found_script_addr = 0 <NEW_LINE> found_addr_chg = 0 <NEW_LINE> found_addr_rsv = 0 <NEW_LINE> witness_addr_ret = None <NEW_LINE> hd_mast... | Read the given dump, count the addrs that match, count change and reserve.
Also check that the old hd_master is inactive | 625941cde8904600ed9f202c |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): <NEW_LINE> <INDENT> desc = None <NEW_LINE> tag = 'level_2' <NEW_LINE> if tag == 'level_1': <NEW_LINE> <INDENT> code = 'L1' <NEW_LINE> desc = None <NEW_LINE> <DEDENT> elif tag == 'level_2': <NEW_LINE> <INDENT> code = 'L2' <NEW_LINE> desc = None <NEW... | Produce a list of files corresponding to ICON IVM.
This routine is invoked by pysat and is not intended for direct use by
the end user.
Multiple data levels may be supported via the 'tag' input string.
Currently defaults to level-2 data, or L2 in the filename.
Parameters
----------
tag : string ('')
tag name use... | 625941cdeab8aa0e5d26dc58 |
def luo_otsikot(tiedosto): <NEW_LINE> <INDENT> with open(tiedosto, 'w', newline = '') as datatiedosto: <NEW_LINE> <INDENT> csv_kirjoittaja = csv.writer(datatiedosto, delimiter = ';', quotechar = '"', ) <NEW_LINE> csv_kirjoittaja.writerow(['Etunimi', 'Sukunimi', 'Pituus', 'Paino', 'Ikä', 'Sukupuoli', 'Tavoitepaino']) | Luodaan CSV-tiedostoon tarvittavat sarakeotsikot
Args:
tiedosto (string): muokattavan tiedoston nimi | 625941cd63f4b57ef000121a |
def transform(self, df, y=None): <NEW_LINE> <INDENT> return df['road_name'].apply(self.average_word_length) | The workhorse of this feature extractor | 625941cd1f037a2d8b9462fe |
def set_icon(self, icon): <NEW_LINE> <INDENT> pass | Sets the widget's icon to the provided image
| 625941cd5fdd1c0f98dc0333 |
def SetEnd(self, end_key): <NEW_LINE> <INDENT> lib.tera_scan_descriptor_set_end(self.desc, end_key, c_uint64(len(end_key))) | 不调用此函数时,end_key被置为“无穷大”
Args:
end_key(string): scan操作的终止位置,scan结果不包含end_key | 625941cd7cff6e4e81117a86 |
def mystery6(n): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> for i in range(0, n): <NEW_LINE> <INDENT> while n > 0: <NEW_LINE> <INDENT> sum += n <NEW_LINE> n = n // 2 <NEW_LINE> <DEDENT> <DEDENT> return sum | What is it's big O? | 625941cd55399d3f055887b4 |
def build_gui(self): <NEW_LINE> <INDENT> tip = _('Double-click on a row to edit the selected event.') <NEW_LINE> self.set_tooltip(tip) <NEW_LINE> top = Gtk.TreeView() <NEW_LINE> titles = [('', NOSORT, 50,), (_('Date'), 1, 200), (_('Place'), 2, 200)] <NEW_LINE> self.model = ListModel(top, titles, event_func=self.edit_ev... | Build the GUI interface. | 625941cd38b623060ff0aeee |
def zero_submodule(self): <NEW_LINE> <INDENT> return self.zero_subspace() | Return the zero submodule of self.
EXAMPLES::
sage: (QQ^4).zero_submodule()
Vector space of degree 4 and dimension 0 over Rational Field
Basis matrix:
[] | 625941cd0a50d4780f666f93 |
def classify0(inX, dataSet, labels, k): <NEW_LINE> <INDENT> dataSetSize = dataSet.shape[0] <NEW_LINE> diffMat = tile(inX, (dataSetSize,1)) - dataSet <NEW_LINE> sqDiffMat = diffMat**2 <NEW_LINE> sqDistances = sqDiffMat.sum(axis=1) <NEW_LINE> distances = sqDistances**0.5 <NEW_LINE> sortedDistIndicies = distances.argsort(... | 计算距离 选择距离最小的k个点 排序 | 625941cdfff4ab517eb2f53d |
def quit_sorte(self, my_list, l, r) -> list: <NEW_LINE> <INDENT> if r > l: <NEW_LINE> <INDENT> q = self.partition(my_list, l, r) <NEW_LINE> self.quit_sorte(my_list, l, q - 1) <NEW_LINE> self.quit_sorte(my_list, q + 1, r) <NEW_LINE> <DEDENT> return my_list | 主要逻辑 | 625941cd1b99ca400220abb2 |
def enable_pretty_logging(options=None, logger=None): <NEW_LINE> <INDENT> if options is None: <NEW_LINE> <INDENT> from lib.tornado.options import options <NEW_LINE> <DEDENT> if options.logging == 'none': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if logger is None: <NEW_LINE> <INDENT> logger = logging.getLogger() <... | Turns on formatted logging output as configured.
This is called automaticaly by `tornado.options.parse_command_line`
and `tornado.options.parse_config_file`. | 625941cd10dbd63aa1bd2ca4 |
def _update_position(self, agent, best_agent, function, energy): <NEW_LINE> <INDENT> a = copy.deepcopy(agent) <NEW_LINE> distance = agent.position - best_agent.position <NEW_LINE> for j in range(agent.n_variables): <NEW_LINE> <INDENT> for k in range(agent.n_dimensions): <NEW_LINE> <INDENT> if distance[j][k] == 0: <NEW_... | Updates agent's position.
Args:
agent (Agent): An agent instance.
best_agent (Agent): A best agent instance.
function (Function): A Function object that will be used as the objective function.
energy (float): Current energy value. | 625941cd5fdd1c0f98dc0334 |
def SetImage(self, image): <NEW_LINE> <INDENT> self._image = image | Sets the thumbnail image.
:param `image`: a `wx.Image` object. | 625941cd627d3e7fe0d68f50 |
def test_cli_help(): <NEW_LINE> <INDENT> result = CliRunner().invoke(cli, args=[args.HELP]) <NEW_LINE> sanity_check(result) | Test honeycomb launches without an error (tests :func:`honeycomb.cli`). | 625941cd3317a56b86939d59 |
def pop_scope(self): <NEW_LINE> <INDENT> self.scope_stack.pop() | Removes a scope from the top of the stack | 625941cdcb5e8a47e48b7bab |
def test_Uri(self): <NEW_LINE> <INDENT> tree = list(PhyloXMLIO.parse(EX_PHYLO))[9] <NEW_LINE> uri = tree.clade.taxonomies[0].uri <NEW_LINE> self.assertTrue(isinstance(uri, PX.Uri)) <NEW_LINE> self.assertEqual(uri.desc, 'EMBL REPTILE DATABASE') <NEW_LINE> self.assertEqual(uri.value, 'http://www.embl-heidelberg.de/~uetz/... | Instantiation of Uri objects. | 625941cdad47b63b2c50a080 |
def save_config(self): <NEW_LINE> <INDENT> rawconfig = [self._errors.ccode[2:-1],str(int(self.warnings.status)),self.warnings.ccode[2:-1],str(int(self.infos.status)),self.infos.ccode[2:-1],str(int(self.multiprocessing.status)),str(int(self.hermitianize.status)),str(int(self.lm2gl.status))] <NEW_LINE> nconfig = os.path.... | Writes to the configuration file "~/.nifty/nifty_config".
Returns
-------
None | 625941cd4428ac0f6e5ba8f3 |
def setAttributes(language, **kws): <NEW_LINE> <INDENT> pass | Set the language specific attribute of the translation defined by kw.
Parameter:
language -- Language code for example ``'de'``
kws -- Attributes that have to be set as keyword value pairs.
Exceptions:
KeyError -- If attribute does not exists. | 625941cd31939e2706e4cf6b |
def integrate(self): <NEW_LINE> <INDENT> L = self.level <NEW_LINE> P = L.prob <NEW_LINE> me = [] <NEW_LINE> for m in range(1, self.coll.num_nodes + 1): <NEW_LINE> <INDENT> me.append(P.dtype_u(P.init, val=0)) <NEW_LINE> for j in range(1, self.coll.num_nodes + 1): <NEW_LINE> <INDENT> me[-1] += L.dt * self.coll.Qmat[m, j]... | Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values | 625941cd435de62698dfdd4d |
def test_missing(self): <NEW_LINE> <INDENT> with patch.dict(smf.__salt__, {"cmd.run": MagicMock(return_value="A")}): <NEW_LINE> <INDENT> with patch.object(smf, "get_all", return_value=("A")): <NEW_LINE> <INDENT> self.assertFalse(smf.missing("A")) | The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise
returns ``False``. | 625941cd8da39b475bd65074 |
def calibration_pipe(original_value,gain,offset): <NEW_LINE> <INDENT> cal_value = original_value*gain+offset <NEW_LINE> return cal_value | Get the calibration results
Args:
ee_profile: dict type, the eeprom profile which calibration data stored
address: the starting address
gain: float data
offset: float data
Returns:
bool: True | False, True for success, False for adc read failed | 625941cd046cf37aa974ce48 |
def get_response_data(self, data): <NEW_LINE> <INDENT> empty = settings.REST_AUTH_LOGIN_EMPTY_RESPONSE <NEW_LINE> if not empty: <NEW_LINE> <INDENT> return data | Override this method when you use ``response_includes_data`` and
You wanna send customized user data (beyond serializer.data) | 625941cd379a373c97cfac45 |
def order(self): <NEW_LINE> <INDENT> return reduce(lcm,[1]+[len(cycle) for cycle in self.cyclic_form]) | Computes the order of a permutation.
When the permutation is raised to the power of its
order it equals the identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([3,1,5,2,4,0])
>>> p.order()
4
>>> (p**(p.order()))
Permutation([0, 1, 2, 3, 4, 5]) | 625941cd71ff763f4b54978c |
def validate(self): <NEW_LINE> <INDENT> return self.connectionWidget.validate() | Validates container GUI parameters.
:return: (str) invalidation reason. | 625941cd55399d3f055887b5 |
def remove(self, value, parentNode = None): <NEW_LINE> <INDENT> currentNode = self <NEW_LINE> while currentNode: <NEW_LINE> <INDENT> if value < currentNode.value: <NEW_LINE> <INDENT> parentNode = currentNode <NEW_LINE> currentNode = currentNode.left <NEW_LINE> <DEDENT> elif value > currentNode.value: <NEW_LINE> <INDENT... | :param value: the value to be deleted
:param parentNode: pointer to the parent node
Deletion is pretty complicated. We have a few subcases we need to take care of.
Traverse to the node that is to be deleted.
Check:
1) if the node has two children then we should find the smallest right most value and replace
... | 625941cdfbf16365ca6f62c5 |
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): <NEW_LINE> <INDENT> if context and not ( 'offerte' in context or 'natuurpunt_sale' in context ): <NEW_LINE> <INDENT> return super(res_partner,self).name_search(cr, user, name, args, operator=operator, context=context, limit=limi... | Returns a list of tupples containing id, name, as internally it is called {def name_get}
result format: {[(id, name), (id, name), ...]}
@param cr: A database cursor
@param user: ID of the user currently logged in
@param name: name to search
@param args: other arguments
@param operator: default operator is 'ilike', it ... | 625941cd1f5feb6acb0c4c51 |
def __set__(self, instance, value): <NEW_LINE> <INDENT> field = instance._fields[self.name] <NEW_LINE> value = field.pre_setattr(value) <NEW_LINE> instance._data[self.name] = value | Sets the field's value. | 625941cd67a9b606de4a7fbb |
def genereFichierTest(pathname,liaison=None) : <NEW_LINE> <INDENT> if liaison is None : <NEW_LINE> <INDENT> liaison = chaineAlea(24) <NEW_LINE> <DEDENT> f = open(pathname,'w') <NEW_LINE> f.write("Donne de test\n") <NEW_LINE> chaine = chaineAlea(100) <NEW_LINE> chaine+= liaison <NEW_LINE> chaine+= chaineAlea(5) <NEW_LIN... | ecris dans le fichier localisé en pathname | 625941cd66656f66f7cbc2ab |
def ProcessFile(filename, vlevel, extra_check_functions=[]): <NEW_LINE> <INDENT> _SetVerboseLevel(vlevel) <NEW_LINE> try: <NEW_LINE> <INDENT> CheckForFileCharacters(filename,Error) <NEW_LINE> CheckForFileNotes(filename,Error) <NEW_LINE> if filename == '-': <NEW_LINE> <INDENT> lines = codecs.StreamReaderWriter(sys.stdin... | Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run ... | 625941cde76e3b2f99f3a90c |
def update_question(self, question_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.update_question_with_http_info(question_id, question_ti... | Update question
Allows the user to update question. Returns the updated question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>... | 625941cdf7d966606f6aa105 |
def test_unlink1(self, u_boot_console, fs_obj_unlink): <NEW_LINE> <INDENT> fs_type,fs_img = fs_obj_unlink <NEW_LINE> with u_boot_console.log.section('Test Case 1 - unlink (file)'): <NEW_LINE> <INDENT> output = u_boot_console.run_command_list([ 'host bind 0 %s' % fs_img, '%srm host 0:0 dir1/file1' % fs_type, '%sls host ... | Test Case 1 - delete a file | 625941cd76e4537e8c351773 |
def __init__(self, shape=(4, 4)): <NEW_LINE> <INDENT> self._tiles = np.zeros(shape, dtype=np.int) | Constructor
Args:
shape: | 625941cd23e79379d52ee665 |
def writeLabelsToJsonFile(labels, fileName): <NEW_LINE> <INDENT> with open(fileName, 'w') as jsonFile: <NEW_LINE> <INDENT> json.dump(labels, jsonFile, indent=4) | Write a labels dictionary to a file. | 625941cd3346ee7daa2b2e6c |
def test_get_archived_artifacts_for_build(self): <NEW_LINE> <INDENT> dependency = DependencyFactory.create() <NEW_LINE> build = BuildFactory.create(job=dependency.job) <NEW_LINE> artifact = ArtifactFactory.create(build=build, filename="testing.gz") <NEW_LINE> archive = ArchiveFactory.create() <NEW_LINE> archive.add_bui... | We can fetch the artifacts that get added from a build. | 625941cd7d847024c06be3bc |
@manager.command <NEW_LINE> def build_tables(): <NEW_LINE> <INDENT> db.create_all() | Build database tables. | 625941cd046cf37aa974ce49 |
def write_page(self, fqdn, roles): <NEW_LINE> <INDENT> hostname, domain = fqdn.split('.', 1) <NEW_LINE> html_file = os.path.join(self.outdir, domain, hostname + '.html') <NEW_LINE> base_path = os.path.join(self.domains_dir, domain, hostname + '.rst') <NEW_LINE> if os.path.exists(base_path): <NEW_LINE> <INDENT> base_fil... | Writes out a generated file to the filesystem for a host.
Combines the info in a manual file with all info from any role templates. | 625941cd7047854f462a150b |
def fs_lasso_cv(X,y,feat_list, n_alphas=1000, cv=3, tol=0.00001, max_iter=10000, hard_shrink=None): <NEW_LINE> <INDENT> lcv = linear_model.LassoCV(n_jobs = max(1, mp.cpu_count()-1), n_alphas=n_alphas, cv=cv, tol=tol, max_iter=max_iter) <NEW_LINE> coefs = lcv.fit(X,y).coef_ <NEW_LINE> if hard_shrink is not None: np.plac... | Wrapper function to build a LassoCV model from sklearn and return important features | 625941cd0c0af96317bb82e9 |
def factR(n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return n*factR(n - 1) | Assumes n an int > 0
Returns n! | 625941cdcc40096d61595a51 |
def order( self, graph: nx.DiGraph, total_graph: nx.DiGraph, ) -> Sequence["PackageName"]: <NEW_LINE> <INDENT> return sorted( graph, key=lambda x: (len(nx.descendants(total_graph, x)), x), reverse=True, ) | Run the order by number of decedents, ties are resolved by package name | 625941cd5fcc89381b1e17c0 |
def update(self, **kwargs): <NEW_LINE> <INDENT> self.manager.update(self, **kwargs) | Update this share. | 625941cd498bea3a759b9bb0 |
def test_matching_query(self): <NEW_LINE> <INDENT> if not selectors.bug_is_fixed(3692, self.cfg.pulp_version): <NEW_LINE> <INDENT> self.skipTest('https://pulp.plan.io/issues/3692') <NEW_LINE> <DEDENT> client = api.Client(self.cfg, api.json_handler) <NEW_LINE> body = gen_repo() <NEW_LINE> body['importer_config'] = { 'fe... | Sync a repository with a query that matches units.
Assert that:
* None of the sync tasks has an error message.
* Searching for module ``pulp_2_tests.constants.PUPPET_MODULE_2``
yields one result.
* The synced-in module can be downloaded. | 625941cdd53ae8145f87a371 |
def _get_obs(self): <NEW_LINE> <INDENT> return self.state | This method is not necessary for the functionality of the environment,
but rather demonstrates a widely used concept
:return: The observation of the current state | 625941cd07f4c71912b11583 |
def multi_graph_partition(costs: Dict, probs: Dict, p_t: np.ndarray, idx2nodes: Dict, ot_hyperpara: Dict, weights: Dict = None, predefine_barycenter: bool = False) -> Tuple[List[Dict], List[Dict], List[Dict], Dict, np.ndarray]: <NEW_LINE> <INDENT> sub_costs_cluster = [] <NEW_LINE> sub_idx2nodes_cluster = [] <NEW... | Achieve multi-graph partition via calculating Gromov-Wasserstein barycenter
between the target graphs and a proposed one
Args:
costs: a dictionary of graphs {key: graph idx,
value: (n_s, n_s) adjacency matrix of source graph}
probs: a dictionary of graphs {key: graph idx,
... | 625941cdde87d2750b85fe94 |
def get_monitored_peer(self): <NEW_LINE> <INDENT> return self._monitored_peer | @return: The associated MonitoredPeer object | 625941cd4c3428357757c429 |
def CDATA(text=None): <NEW_LINE> <INDENT> element = ElementTree.Element('![CDATA[') <NEW_LINE> element.text = text <NEW_LINE> return element | Return a CDATA section | 625941cd15fb5d323cde0c11 |
def make_test_cases(lenses): <NEW_LINE> <INDENT> test_cases = [] <NEW_LINE> for lens_id, group in groupby(lenses, lambda x: x["id"]): <NEW_LINE> <INDENT> lens_group = list(group) <NEW_LINE> test_cases += [ { **lens["meta"], "id": lens["id"], "desc": lens["desc"], "target": " *OR* ".join([l["desc"] for l in lens_group i... | Creates a test case for each lens
Main job of this function is to collect all ambiguous lenses and define a test target
as the " *OR* " joined string of all ambiguous lens descriptions | 625941cd5510c4643540f4e6 |
def maximization(data: pd.DataFrame, theta: dict, num_clusters: int) -> dict: <NEW_LINE> <INDENT> percent_clusters = [] <NEW_LINE> data_size = len(data) <NEW_LINE> for i in range(num_clusters): <NEW_LINE> <INDENT> points_cluster = data[data['label'] == i] <NEW_LINE> percent_clusters.append(len(points_cluster) / data_si... | update estimates of lambda, mu and sigma | 625941cd44b2445a33932197 |
def scan_hashes(self, hash_callback): <NEW_LINE> <INDENT> for key in self.db: <NEW_LINE> <INDENT> rec = self.db[key] <NEW_LINE> hash_callback(rec["textures"]["skin_default_static"]) <NEW_LINE> hash_callback(rec["textures"]["skin_slim_static"]) <NEW_LINE> hash_callback(rec["textures"]["cape_static"]) <NEW_LINE> hash_cal... | used for TextureManager on startup | 625941cd656771135c3eb970 |
def reset_password(self, token, new_password): <NEW_LINE> <INDENT> s = Serializer(current_app.config['SECRET_KEY']) <NEW_LINE> try: <NEW_LINE> <INDENT> data = s.loads(token) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if data.get('reset') != self.id: <NEW_LINE> <INDENT> return False... | Change the password if the token matches. | 625941cd01c39578d7e74f3c |
def sltu(ir, instr, a, x, y): <NEW_LINE> <INDENT> e = [] <NEW_LINE> value = (((x - y) ^ ((x ^ y) & ((x - y) ^ x))) ^ x ^ y).msb().zeroExtend(32) <NEW_LINE> e.append(m2_expr.ExprAff(a, value)) <NEW_LINE> return e, [] | If @y is less than @x (unsigned), @a is set to one. It gets zero
otherwise. | 625941cda17c0f6771cbe151 |
def answer(self, address): <NEW_LINE> <INDENT> raise NotImplementedError('This method is abstract. Override it.') | Returns true iff the location being addressed is written. | 625941cdbe7bc26dc91cd701 |
def test_consistency_combine_dense(self): <NEW_LINE> <INDENT> self._check_consistency_combine(np.array) | Test for consistency when combining containers with dense matrices. | 625941cd0a366e3fb873e91b |
def read_data_file_col(ifile, sep='', remove=0, c_len=0): <NEW_LINE> <INDENT> data = mcf.read_data_file(ifile) <NEW_LINE> if remove > 0: <NEW_LINE> <INDENT> mcf.rm_file(ifile) <NEW_LINE> <DEDENT> if len(data) == 0: <NEW_LINE> <INDENT> return [0, 0] <NEW_LINE> <DEDENT> if sep != '': <NEW_LINE> <INDENT> atemp = re.split(... | read ascii data file
input: ifile --- file name
sep --- split indicator: default: '' --- not splitting
remove --- indicator whether to remove the file after reading: default: 0 --- no
c_len --- numbers of columns to be read. col=0 to col= c_len. default: 0 --- read all
output: data ... | 625941cd293b9510aa2c3398 |
def add_template_only_view(config: Configurator, pattern: str, name: str, template: str, view_args: t.Optional[dict]=None, route_args: t.Optional[dict]=None): <NEW_LINE> <INDENT> def _default_view(request): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> config.add_route(name, pattern) <NEW_LINE> config.add_view(view... | Adds a view which do not have a specific view function assgined.
The view will render a template with the default template context.
:param pattern: A path where the view is, e.g. ``/features``
:param name: View name for ``route_url()``
:param tempalte: A template to render
:param view_args: kwargs passed to :py:meth:... | 625941cd4a966d76dd551111 |
def inverse_modp(self): <NEW_LINE> <INDENT> assert self.dim_row == self.dim_col, 'Rectangle matrices are not invertible.' <NEW_LINE> A = [] <NEW_LINE> for row in self.coeffs: <NEW_LINE> <INDENT> row_tmp = [x for x in row]+[self.coeffs_field.zero for cnt in range(self.dim_row)] <NEW_LINE> A.append(row_tmp) <NEW_LINE> <D... | Computes the inverse of a matrix with coefficients in a finite field.
| 625941cd8a349b6b435e8274 |
def show_color(self): <NEW_LINE> <INDENT> plt.rcParams['figure.figsize'] = (3, 3) <NEW_LINE> fig, ax = plt.subplots() <NEW_LINE> ax.set_aspect('equal', 'datalim') <NEW_LINE> r = matplotlib.patches.Rectangle((0, 0), 1, 1, color=self.color) <NEW_LINE> ax.add_patch(r) <NEW_LINE> ax.text(0.5, 0.5, self.short_name, fontdict... | Show the color selected for the party_name.
A patch with the color of the party and its abreviation in white
is displayed using matplotlib. | 625941cdbe8e80087fb20d44 |
def hasDataBlock(self, unifName): <NEW_LINE> <INDENT> if unifName.startswith("wikipage/"): <NEW_LINE> <INDENT> return self.isDefinedWikiPageName(unifName[9:]) <NEW_LINE> <DEDENT> return self.guessDataBlockStoreHint(unifName) is not None | Return if datablock exists.
This works also with wiki pages (unified name starting with "wikipage/")
but does not return aliases in this case | 625941cd9c8ee82313fbb877 |
def _get_filenames_and_features(dataset_dir): <NEW_LINE> <INDENT> features=[] <NEW_LINE> photo_filenames =[] <NEW_LINE> f=open('data.txt','r') <NEW_LINE> line = f.readline() <NEW_LINE> name=line.strip().split(' ') <NEW_LINE> filenames=name[0] <NEW_LINE> features.append(dataset_dir+name[1]) <NEW_LINE> photo_filenames.ap... | Returns a list of filenames and inferred class names.
Args:
dataset_dir: A directory containing a set of subdirectories representing
class names. Each subdirectory should contain PNG or JPG encoded images.
Returns:
A list of image file paths, relative to `dataset_dir` and the list of
subdirectories, represent... | 625941cd50485f2cf553ce9b |
def handle_yaml_errors(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> async def send_with_error_handling(hass, connection, msg): <NEW_LINE> <INDENT> error = None <NEW_LINE> try: <NEW_LINE> <INDENT> result = await func(hass, connection, msg) <NEW_LINE> message = websocket_api.result_message( msg['id'], result ) <NEW... | Handle error with WebSocket calls. | 625941cd01c39578d7e74f3d |
def __init__(self, layer_collection, params, padding, strides=None, dilation_rate=None, data_format=None, extract_patches_fn=None, sub_sample_inputs=None, sub_sample_patches=None, use_sua_approx_for_input_factor=False, patch_mask=None): <NEW_LINE> <INDENT> self._padding = padding <NEW_LINE> self._strides = maybe_tuple(... | Creates a ConvKFCBasicFB block.
Args:
layer_collection: The LayerCollection object which owns this block.
params: The parameters (Tensor or tuple of Tensors) of this layer. If
kernel alone, a Tensor of shape [..spatial_filter_shape..,
in_channels, out_channels]. If kernel and bias, a tuple of 2 elements
... | 625941cdcb5e8a47e48b7bac |
def test_create_underline_solid_highlight_style_invalid_st2(self): <NEW_LINE> <INDENT> when(st_helper).is_st3().thenReturn(False) <NEW_LINE> self.assertRaises(AssertionError, lambda: Settings({ "search_colors_in": { "selection": { "enabled": True, "color_highlighters": { "color_scheme": { "enabled": True, "highlight_st... | Test creating color highlighting settings with invaid highlighting style.
underline_solid highlighting style is invalid in ST2. | 625941cd442bda511e8be51a |
def test_delete_namespaced_virtual_machine_instance(self): <NEW_LINE> <INDENT> pass | Test case for delete_namespaced_virtual_machine_instance | 625941cd3346ee7daa2b2e6d |
def spsolve(A,b): <NEW_LINE> <INDENT> if spar.issparse(A): <NEW_LINE> <INDENT> return spla.spsolve(A, b) <NEW_LINE> <DEDENT> elif spar.issparse(b): <NEW_LINE> <INDENT> Warn('b is sparse, but A is dense. Solving the dense system.') <NEW_LINE> return spsolve(A, b.toarray()) <NEW_LINE> <DEDENT> return scla.solve(A,b) | Solve the system Ax=b for x, depending on the type of A. The solution vector is equivalent to A^{-1}b
If a is sparse, the result will be sparse. Otherwise, the result will be dense. | 625941cd435de62698dfdd4e |
@login_required <NEW_LINE> def profile(request): <NEW_LINE> <INDENT> return render(request, "account.html", {"account": request.user}) | Displays the profile of the user. | 625941cd167d2b6e31218c97 |
def lose_spin_degree_of_freedom(gf, spin_fast=True): <NEW_LINE> <INDENT> norb = gf.target_shape[-1] // 2 <NEW_LINE> if spin_fast: <NEW_LINE> <INDENT> idx = gf.target_rank*(slice(None, None, 2),) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> idx = gf.target_rank*(slice(norb, None),) <NEW_LINE> <DEDENT> return gf[idx] | Only keep the up spin elements of a Greens function
Parameters:
gf: Greens function, the last rank dimenions must the orbitals
spin_fast: bool, True if spin is the fast index, e.g.
xz up, xz down, xy up, xy down, yz up, yz down,
or False if spin is the slow index, e.g.
xz u... | 625941cdd268445f265b4f6f |
def start_raw(self): <NEW_LINE> <INDENT> self.write_attr(0x28, b'\x01\x00') <NEW_LINE> self.write_attr(0x19, b'\x01\x03\x01\x01\x00') <NEW_LINE> self.write_attr(0x19, b'\x01\x03\x01\x01\x01') | Sending this sequence for v1.0 firmware seems to enable both raw
data and pose notifications. | 625941cd1f037a2d8b9462ff |
def Select(self, row_template, parameter_info=None): <NEW_LINE> <INDENT> template = list(row_template) <NEW_LINE> if self.columns > len(template): <NEW_LINE> <INDENT> template += [None] * (self.columns - len(template)) <NEW_LINE> <DEDENT> log.info('cache template=%s', template) <NEW_LINE> values = [] <NEW_LINE> aggrega... | Returns the list of rows matching row_template in the collection.
All tables in the collection are in play. The row matching done by the
cache layer conveniently prunes the number of tables accessed.
Args:
row_template: A row template tuple. The number of columns in the template
must match the number of columns... | 625941cd23849d37ff7b3191 |
def get_singlesig_privkey(privkey_info, blockchain='bitcoin', **blockchain_opts): <NEW_LINE> <INDENT> if blockchain == 'bitcoin': <NEW_LINE> <INDENT> return btc_get_singlesig_privkey(privkey_info, **blockchain_opts) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unknown blockchain "{}"'.format(blockcha... | Given a private key bundle, get the (single) private key | 625941cd99cbb53fe6792ce8 |
def get_orgunits(self, top_org_los_id): <NEW_LINE> <INDENT> top_org_los_id = int(top_org_los_id) <NEW_LINE> org_repo = Orgunit_repo(self.lora_constr) <NEW_LINE> orgs = org_repo.get_orgunits() <NEW_LINE> result = {} <NEW_LINE> for los_id in orgs: <NEW_LINE> <INDENT> org = orgs[los_id] <NEW_LINE> if Kalenda_greenbyte_syn... | Henter de relevante orgunits, fra en bestemt rod. Det sker fordi det kun er et bestemt område
af organisationen, som skal synkroniseres med kalenda-greenbyte.
Dette sher ud fra los_id, som kan findes i .env filen.
Hvis der skiftes rundt i LOS, skal dette ID opdateres. | 625941cd7b180e01f3dc48fe |
def MakeModeratedEffect(data,i = 0, j = 1, effect = 0): <NEW_LINE> <INDENT> N,M = data.shape <NEW_LINE> iD = data[:,i] - data[:,i].mean() <NEW_LINE> print(iD.mean()) <NEW_LINE> jD = data[:,j] - data[:,j].mean() <NEW_LINE> print(jD.mean()) <NEW_LINE> mD = np.array(iD*jD) <NEW_LINE> print(mD.mean()) <NEW_LINE> OutData = ... | Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
Examples
--------
>>> func(1, "a")
True | 625941cddd821e528d63b2aa |
def make_train_input_fn(ncf_dataset): <NEW_LINE> <INDENT> if not tf.gfile.Exists(ncf_dataset.cache_paths.subproc_alive): <NEW_LINE> <INDENT> raise ValueError("Generation subprocess did not start correctly. Data will " "not be available; exiting to avoid waiting forever.") <NEW_LINE> <DEDENT> train_epoch_dir = ncf_datas... | Construct training input_fn for the current epoch. | 625941cdf548e778e58cd67f |
def test_optional(self): <NEW_LINE> <INDENT> o = _pr._OptionalBlock([ _pr._Replacement(u"$Title"), _pr._LiteralText(u".foobar") ]) <NEW_LINE> subst = {'$Title': 'foo', '$Track': 'bar'} <NEW_LINE> res = o.render(subst) <NEW_LINE> self.assertEqual(res, u'foo.foobar', 'check non-empty replacement') <NEW_LINE> subst = {'$T... | pathrender: _OptionalBlock element processing | 625941cd97e22403b379d09b |
def show_trace_2d(f, res): <NEW_LINE> <INDENT> x1, x2 = zip(*res) <NEW_LINE> set_figsize() <NEW_LINE> plt.plot(x1, x2, '-o', color='#ff7f0e') <NEW_LINE> x1 = np.arange(-5.5, 1.0, 0.1) <NEW_LINE> x2 = np.arange(min(-3.0, min(x2) - 1), max(1.0, max(x2) + 1), 0.1) <NEW_LINE> x1, x2 = np.meshgrid(x1, x2) <NEW_LINE> plt.con... | Show the trace of 2d variables during optimization. | 625941cdcc0a2c11143dcf92 |
def create_workspace(self, workspace_json): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.conversation.create_workspace(name=workspace_json['name'], description=workspace_json['description'], language=workspace_json['language'], intents=workspace_json['intents'], entities=workspace_json['entities'], dial... | Creates a workspace from a given JSON file
:param workspace_json: The JSON file to create the workspace from.
:return: The created workspace ID. | 625941cda219f33f34628a6b |
def setup_exchange(self, exchange_name): <NEW_LINE> <INDENT> self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, EXCHANGE_TYPE) | Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare | 625941cd3617ad0b5ed67ff9 |
def getShakeDict(self): <NEW_LINE> <INDENT> return self._shakeDict | Get the shake dictionary (the attributes of the "shakemap_grid" element in the ShakeMap header).
:returns:
Dictionary containing the following fields:
- event_id: String like "us2016abcd".
- shakemap_id: String like "us2016abcd".
- shakemap_version: Version of the map that has been created.
- code_version... | 625941cdc432627299f04d47 |
def test_interface(self): <NEW_LINE> <INDENT> responder = self._responder_factory() <NEW_LINE> verifyObject(IResponder, responder) <NEW_LINE> self.assertThat(responder.challenge_type, Equals(self._challenge_type)) | The `.IResponder` interface is correctly implemented. | 625941cdb57a9660fec33986 |
def invalidate(self): <NEW_LINE> <INDENT> logging.info("Invalidating CacheFolder #%d" % self.cacheId) <NEW_LINE> try: <NEW_LINE> <INDENT> shutil.rmtree(self._makePath()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> os.mkdir(self._makePath()) <NEW_LINE> self.isCached = False <NEW_LINE> self.f... | Invalidates the cache folder, removing all files. | 625941cd711fe17d8254246d |
def create_menu_item(ia, parent_menu, menu_text, image=None, tooltip=None, shortcut=(), triggered=None, is_checked=None): <NEW_LINE> <INDENT> if shortcut is not None: <NEW_LINE> <INDENT> if len(shortcut) == 0: <NEW_LINE> <INDENT> shortcut = () <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shortcut = shortcut <NEW_LINE>... | Create a menu action with the specified criteria and action
Note that if no shortcut is specified, will not appear in Preferences->Keyboard
This method should only be used for actions which either have no shortcuts,
or register their menus only once. Use create_menu_action_unique for all else. | 625941cd0a366e3fb873e91c |
def servers_update_addresses(request, servers, all_tenants=False): <NEW_LINE> <INDENT> neutron_enabled = base.is_service_enabled(request, 'network') <NEW_LINE> if neutron_enabled: <NEW_LINE> <INDENT> neutron.servers_update_addresses(request, servers, all_tenants) | Retrieve servers networking information from Neutron if enabled.
Should be used when up to date networking information is required,
and Nova's networking info caching mechanism is not fast enough. | 625941cd6e29344779a62713 |
def mkdir(self, url, permissions): <NEW_LINE> <INDENT> pass | void KIO.SlaveBase.mkdir(KUrl url, int permissions) | 625941cda05bb46b383ec923 |
def picket_fence(command): <NEW_LINE> <INDENT> old = re.split(r'(?<!\\)/', command)[1] <NEW_LINE> new = re.split(r'(?<!\\)/', command)[2] <NEW_LINE> if '\/' in old: <NEW_LINE> <INDENT> old = old.replace('\/', '/') <NEW_LINE> <DEDENT> if '\/' in new: <NEW_LINE> <INDENT> new = new.replace('\/', '/') <NEW_LINE> <DEDENT> r... | separates old and new and deals with \/ if it's there
This helps the edit function by splitting the 's/old/new/' string into old
and new strings, also replacing '\/' with '/' if it exists. Both the old
and the new are returned. | 625941cd73bcbd0ca4b2c178 |
def get_segment(self, i=None): <NEW_LINE> <INDENT> i = i if i is not None else self.i <NEW_LINE> return self.segs[i], self.scores[i], self.marks[i] | Return segment, sonority score, and mark for the index.
i -- the index to use; if unspecified or set to None, self.i is used
instead. | 625941cda4f1c619b28b013b |
def get_products_statistics(loop, products): <NEW_LINE> <INDENT> description_placeholder = config["placeholders"]["description"] <NEW_LINE> img_url_placeholder = config["placeholders"]["img_url"] <NEW_LINE> futures = [get_offers_async(product["productId"]) for product in products] <NEW_LINE> all_offers = loop.run_until... | Enrich products with additional statistics from offers.
Args:
loop (asyncio.unix_events._UnixSelectorEventLoop): asyncio event loop
products (list): products of currently selected category
Returns:
list: products with additional statistics | 625941cd26238365f5f0ef70 |
def test_text_slug_max_length_not_exceed(self): <NEW_LINE> <INDENT> group = PostModelTest.group <NEW_LINE> max_length_slug = group._meta.get_field('slug').max_length <NEW_LINE> length_slug = (len(group.slug)) <NEW_LINE> self.assertEqual(max_length_slug, length_slug) | Длинный slug обрезается и не превышает max_length поля slug в модели. | 625941cdcdde0d52a9e53135 |
def test_add_new_pet_with_valid_data(name='Marta', animal_type='собака', age='2', pet_photo='images/Marta.jpeg'): <NEW_LINE> <INDENT> pet_photo = os.path.join(os.path.dirname(__file__), pet_photo) <NEW_LINE> _, auth_key = pf.get_api_key(valid_email, valid_password) <NEW_LINE> status, result = pf.add_new_pet(auth_key, n... | Проверяем что можно добавить питомца с корректными данными | 625941cdff9c53063f47c2f5 |
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True): <NEW_LINE> <INDENT> if dtype is None: <NEW_LINE> <INDENT> dtype = primary.dtype <NEW_LINE> <DEDENT> val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype) <NEW_LINE> return create_slot(primary, val, name, colocate_with_primary=colo... | Create a slot initialized to 0 with same shape as the primary object.
Args:
primary: The primary `Variable` or `Output`.
name: Name to use for the slot variable.
dtype: Type of the slot variable. Defaults to the type of `primary`.
colocate_with_primary: Boolean. If True the slot is located
on the same de... | 625941cd167d2b6e31218c98 |
def group_digits(self, text, separator=',', group_size=3): <NEW_LINE> <INDENT> if text < 0: <NEW_LINE> <INDENT> prefix = '-' <NEW_LINE> text = -text; <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = '' <NEW_LINE> <DEDENT> string = "{0}".format(text) <NEW_LINE> dot_index = string.find('.'); <NEW_LINE> string_size ... | Enables digit grouping (i.e. adds comma separators between
thousands digits).
Args:
text: A string of the text which will be searched for numbers to
group.
separator: String of the character(s) you'd like to add between the
digit groups. Default is a comma. (",")
group_size: How many digits... | 625941cdd164cc6175782e4f |
def set(self, irc, msg, args, channel, number, topic): <NEW_LINE> <INDENT> self._checkManageCapabilities(irc, msg, channel) <NEW_LINE> if number is not None: <NEW_LINE> <INDENT> topics = self._splitTopic(irc, channel) <NEW_LINE> topics[number] = topic <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> topics = [topic] <NEW_... | [<channel>] [<number>] <topic>
Sets the topic <number> to be <text>. If no <number> is given, this
sets the entire topic. <channel> is only necessary if the message
isn't sent in the channel itself. | 625941cdc432627299f04d48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.