code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def sortColors(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> left, right, now = 0, len(nums) - 1, 0 <NEW_LINE> while now <= right: <NEW_LINE> <INDENT> if nums[now] == 0: <NEW_LINE> <INDENT> nums[left], nums[now] = nums[now], nums[left] <NEW_LINE> left += 1 <NEW_LINE> now += 1 <NEW_LINE> <DEDENT> elif nums[now] ==... | Do not return anything, modify nums in-place instead. | 625941d067a9b606de4a801a |
def AOS(ann, trk_results, trk_names): <NEW_LINE> <INDENT> print("Average Overlap Score:") <NEW_LINE> for trk_r, trk_name in zip(trk_results, trk_names): <NEW_LINE> <INDENT> if trk_name.find('SORT') != -1 or trk_name.find('YOLO') != -1 or trk_name.find('IoU') != -1: <NEW_LINE> <INDENT> isMOTformat = True <NEW_LINE> <DED... | Show AOS of many trackers
Params:
ann: list of path to annotation files
trk_results: list of list of path to tracking results
trk_names: list of tracker names
Return:
None | 625941d055399d3f05588815 |
def set_loglevel_value(self, log_level): <NEW_LINE> <INDENT> with self.loglevel.get_lock(): <NEW_LINE> <INDENT> self.loglevel.value = getattr(logging, log_level) | Assumes log_level is a string corresponding to the supported logging-module levels. | 625941d01b99ca400220ac12 |
def update_pending_parses(self): <NEW_LINE> <INDENT> plugin_manager = self.plugin.manager <NEW_LINE> pending_plugin_resources_map = {} <NEW_LINE> for resource, plugin_id in colony.legacy.items(self.pending_plugin_resources_map): <NEW_LINE> <INDENT> configuration_plugin = plugin_manager._get_plugin_by_id(plugin_id) <NEW... | Updates the current resources manager state so that
the pending plugin resources (not parsed correctly because no adapter
was available) are tested again for parsing.
In case there's success in the parsing the of the plugin resource
it's registered in the associated plugin. | 625941d0a934411ee37517f4 |
def test_nexus_vxlan_two_network(self): <NEW_LINE> <INDENT> self._basic_create_verify_port_vlan( 'test_vxlan_config5', self.results.get_test_results( 'add_port_driver_result4')) <NEW_LINE> self._create_port( self.test_configs['test_vxlan_config6'], override_netid=888) <NEW_LINE> self._verify_results( self.results.get_t... | Test processing for creating one VXLAN segment. | 625941d0a8ecb033257d322e |
def GetFieldMinMax(fielddef): <NEW_LINE> <INDENT> minmax = {'c': (0, 0xff), '?': (0, 1), 'b': (~0x7f, 0x7f), 'B': (0, 0xff), 'h': (~0x7fff, 0x7fff), 'H': (0, 0xffff), 'i': (~0x7fffffff, 0x7fffffff), 'I': (0, ... | Get minimum, maximum of field based on field format definition
@param fielddef:
field format - see "Settings dictionary" above
@return:
min, max | 625941d02c8b7c6e89b35921 |
def Print(self, *args): <NEW_LINE> <INDENT> return _itkNeighborhoodPython.itkNeighborhoodRGBUS3_Print(self, *args) | Print(self, ostream os) | 625941d03c8af77a43ae3901 |
def test_gridworkflow_with_time_depth(): <NEW_LINE> <INDENT> fakecrs = geometry.CRS("EPSG:4326") <NEW_LINE> grid = 100 <NEW_LINE> pixel = 10 <NEW_LINE> gridspec = GridSpec( crs=fakecrs, tile_size=(grid, grid), resolution=(-pixel, pixel) ) <NEW_LINE> def make_fake_datasets(num_datasets): <NEW_LINE> <INDENT> start_time =... | Test GridWorkflow with time series.
Also test `Tile` methods `split` and `split_by_time` | 625941d0bf627c535bc13330 |
def unidentified_rate(net_table): <NEW_LINE> <INDENT> unidentified_plants = sum(1 if p.lower().startswith('unidentified') else 0 for p in net_table.index) <NEW_LINE> unidentified_pols = sum(1 if p.lower().startswith('unidentified') else 0 for p in net_table.columns) <NEW_LINE> return unidentified_plants / len(net_table... | Counts the number of COMPLETELY unidentified species of plants and pollinators
in a network and divides by the total species number. Assumes such species are
named `unidentified` in the network, and are wholly unknown (i.e. the genus is
also unknown).
:param net_table: pandas table of a pollinator network
:return: tupl... | 625941d085dfad0860c3afbc |
def generate_subdir(channel): <NEW_LINE> <INDENT> return os.path.join('%s' % (channel), strftime("%d_%b_%y")) | Generate a subdirectory name using channel and date.
Can be used for output and log files, so consistent between both.
>>> generate_subdir('ggh_4tau', 8)
ggh_4tau/05_Oct_15 | 625941d02ae34c7f2600d292 |
def create_message(sender, to, subject, message_text): <NEW_LINE> <INDENT> message = MIMEText(message_text) <NEW_LINE> message['to'] = to <NEW_LINE> message['from'] = sender <NEW_LINE> message['subject'] = subject <NEW_LINE> message = message.as_string() <NEW_LINE> message = base64.urlsafe_b64encode(message.encode('UTF... | Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object. | 625941d0236d856c2ad4493c |
def update_subgroup(self, subgroups): <NEW_LINE> <INDENT> api_args = {'subgroup': subgroups} <NEW_LINE> uri = '/PermissionGroupSubgroupEntry/{}/'.format(self._group_name) <NEW_LINE> DynectSession.get_session().execute(uri, 'PUT', api_args) <NEW_LINE> self._subgroup = subgroups | Update the subgroups under this :class:`PermissionsGroup`
:param subgroups: The subgroups with updated information | 625941d03617ad0b5ed68058 |
def t_ID(self, t): <NEW_LINE> <INDENT> if t.value in self.reserved: <NEW_LINE> <INDENT> t.type = self.reserved[t.value] <NEW_LINE> <DEDENT> elif t.value in self.functions: <NEW_LINE> <INDENT> t.type = 'FUNC' <NEW_LINE> <DEDENT> return t | [a-zA-Z_][a-zA-Z_0-9]* | 625941d06fb2d068a760f1ff |
def _check_md5(self): <NEW_LINE> <INDENT> self.log.info('-' * 80) <NEW_LINE> self.log.info('Check md5 sum') <NEW_LINE> self.log.info(self._ref_value) <NEW_LINE> self.log.info(self._output_file) <NEW_LINE> code, out = cmd_exec(['md5sum', self._output_file], shell=False, log=self.log) <NEW_LINE> if code: <NEW_LINE> <INDE... | Compare reference md5sum with actual
:return: Boolean | 625941d0d7e4931a7ee9e07f |
def getEditorColour(key, prefClass=Prefs): <NEW_LINE> <INDENT> col = prefClass.settings.value("Editor/Colour/" + key) <NEW_LINE> if col is not None: <NEW_LINE> <INDENT> if len(col) == 9: <NEW_LINE> <INDENT> return QColor.fromRgba(int(col[1:], 16)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return QColor(col) <NEW_LI... | Module function to retrieve the various editor marker colours.
@param key the key of the value to get
@param prefClass preferences class used as the storage area
@return the requested editor colour | 625941d05fc7496912cc3adf |
def search(self, query, order="date"): <NEW_LINE> <INDENT> params = dict(q=query, order=order, format="text") <NEW_LINE> return NexusDatasetInfoList(self, "/api/search", params) | Retrieves a list of datasets matching a query string from Nexus.
@param query: the query string. Searches are case insensitive and
Nexus searches for complete words only. The special word OR
can be used to find datasets that contain any of the given words
(instead of all of them). Exact phrases must be enclosed ... | 625941d0090684286d50ee47 |
def build_optimizer(self, method, param_groups=None, **kwargs): <NEW_LINE> <INDENT> if isinstance(method, str): <NEW_LINE> <INDENT> optimizer_class = getattr(torch.optim, method, None) <NEW_LINE> if optimizer_class is None: <NEW_LINE> <INDENT> optimizer_class = getattr(optimizers, method, None) <NEW_LINE> <DEDENT> asse... | Builds the optimizer for training.
Parameters
----------
method : str or callable or torch.optim.Optimizer
Name of the optimizer when str, handle to the optimizer class when callable,
or a torch.optim.Optimizer instance. If a name is provided, this method looks
for the optimizer in `torch.optim` module fir... | 625941d0eab8aa0e5d26dcb9 |
def test_snapshot_minram_mindisk_VHD(self): <NEW_LINE> <INDENT> self.fake_image.update(disk_format='vhd', min_ram=1, min_disk=1) <NEW_LINE> self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) <NEW_LINE> instance = self._create_fake_instance(type_name='m1.small') <NEW_LINE> image = self.compute_api.snap... | Ensure a snapshots min_ram and min_disk are correct.
A snapshot of a non-shrinkable VHD should have min_disk
set to that of the original instances flavor. | 625941d01f5feb6acb0c4cb1 |
def test_summary(self): <NEW_LINE> <INDENT> mock_lst = MagicMock(return_value=[]) <NEW_LINE> with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}): <NEW_LINE> <INDENT> with patch('salt.utils.fopen', mock_open(read_data="resources: 1")): <NEW_LINE> <INDENT> self.assertDictEqual(puppet.summary(), {'resources': 1}) <NEW... | Test to show a summary of the last puppet agent run | 625941d057b8e32f524835fc |
def ping_monitor(self, mon_id): <NEW_LINE> <INDENT> self.require_state("configuring", "connected") <NEW_LINE> outstrp = pointer(pointer(c_char())) <NEW_LINE> outstrlen = c_long() <NEW_LINE> ret = run_in_thread(self.librados.rados_ping_monitor, (self.cluster, c_char_p(mon_id), outstrp, byref(outstrlen))) <NEW_LINE> my_o... | Ping a monitor to assess liveness
May be used as a simply way to assess liveness, or to obtain
informations about the monitor in a simple way even in the
absence of quorum.
:param mon_id: the ID portion of the monitor's name (i.e., mon.<ID>)
:type mon_id: str
:returns: the string reply from the monitor | 625941d0956e5f7376d70fce |
def widget_parent_sensitive(widget): <NEW_LINE> <INDENT> return (widget.flags() & gtk.PARENT_SENSITIVE) != 0 | Equivalent to the GTK_WIDGET_PARENT_SENSITIVE macro | 625941d0a8370b7717052a00 |
def evaluate_block(self, comments): <NEW_LINE> <INDENT> if self.jsdocs: <NEW_LINE> <INDENT> m1 = RE_JSDOC.match(comments) <NEW_LINE> if m1: <NEW_LINE> <INDENT> lines = [] <NEW_LINE> for line in m1.group(1).splitlines(True): <NEW_LINE> <INDENT> l = line.lstrip() <NEW_LINE> lines.append(l[1:] if l.startswith('*') else l)... | Evaluate block comments. | 625941d03c8af77a43ae3902 |
def get_env_path(key, default): <NEW_LINE> <INDENT> if key in os.environ: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = os.environb.get(key.encode('utf-8')) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> path = os.environ[key] <NEW_LINE> <DEDENT> return path.decode(sys.getfilesystemencoding()).enc... | Get a UTF-8 encoded path from an environment variable. | 625941d0d99f1b3c44c676ee |
def residual(self, allvalues, data, weights, *coords): <NEW_LINE> <INDENT> if len(coords) == 0: <NEW_LINE> <INDENT> coords = (weights,) <NEW_LINE> weights = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> l = [p for p in self.parameterValues] <NEW_LINE> l.append([_sciwrap(c) for c in coords]) <NEW_LINE> l.append(self... | Find residual as sum of squared differences of function and data
Arguments:
allvalues -- boolean, currently ignored
data -- used to subtract from evaluated function
weights -- weighting for each squared difference, can be None
coords -- coordinates over which the function is evaluated | 625941d063f4b57ef0001279 |
def write_project_config(config) : <NEW_LINE> <INDENT> with open('./abrio.json', 'w' ) as config_file: <NEW_LINE> <INDENT> config_file.write(json.dumps(config, indent=4, separators=(',', ': '))) | write config dict to json file | 625941d099fddb7c1c9de4f2 |
def GetGlobalFutureCodeByItemMonth(self, sItem, sMonth): <NEW_LINE> <INDENT> if not (isinstance(sItem, str) and isinstance(sMonth, str)): <NEW_LINE> <INDENT> print("Error : ParameterTypeError by GetGlobalFutureCodeByItemMonth") <NEW_LINE> raise ParameterTypeError() <NEW_LINE> <DEDENT> return self.dynamicCall("GetGlobal... | 23) GetGlobalFutureCodeByItemMonth
원형 BSTR GetGlobalFutureCodeByItemMonth(BSTR sItem, BSTR sMonth)
설명 해외선물종목코드를 상품/월물별로 반환한다.
입력값 sItem: 상품코드(6A, ES..),
sMonth: “201606”
반환값 종목코드를 문자값으로 반환한다.
비고 | 625941d097e22403b379d0fb |
def register(self, integration_cls: Type[BaseIntegration], **kwargs) -> BaseIntegration: <NEW_LINE> <INDENT> if integration_cls.name in self.integrations: <NEW_LINE> <INDENT> raise ImproperlyConfigured( f"Integration with name {integration_cls.name} already registered" ) <NEW_LINE> <DEDENT> self.integrations[integratio... | Register an integration. | 625941d0d99f1b3c44c676ef |
def point(x: float, y: float, crs: MaybeCRS) -> Geometry: <NEW_LINE> <INDENT> return Geometry({'type': 'Point', 'coordinates': [float(x), float(y)]}, crs=crs) | Create a 2D Point
>>> point(10, 10, crs=None)
Geometry(POINT (10 10), None) | 625941d063d6d428bbe44650 |
def _create_activation_condition(self, activation_condition): <NEW_LINE> <INDENT> conditions = [] <NEW_LINE> for condition in activation_condition.conditions: <NEW_LINE> <INDENT> if isinstance(condition, base_classes.KeyboardCondition): <NEW_LINE> <INDENT> conditions.append( actions.KeyboardCondition( condition.scan_co... | Creates activation condition objects base on the given data.
:param activation_condition data about activation condition to be
used in order to generate executable nodes | 625941d021bff66bcd684ab3 |
def set_snappy(self): <NEW_LINE> <INDENT> return self.__push('snappy', True) | snappy (nsqd 0.2.23+) enable snappy compression for this connection.
--snappy (nsqd flag) enables support for this server side
The client should expect an additional, snappy compressed OK response
immediately after the IDENTIFY response.
A client cannot enable both snappy and deflate. | 625941d082261d6c526ab601 |
def get_urls_from_content(content): <NEW_LINE> <INDENT> anchor = "<a href=" <NEW_LINE> url_links = set() <NEW_LINE> start_idx = 0 <NEW_LINE> found = content.find(anchor, start_idx) <NEW_LINE> while found != -1: <NEW_LINE> <INDENT> href_end = content.find('"', found + len(anchor) + 1) <NEW_LINE> href = content[found + l... | Get absolute urls from string content. | 625941d021a7993f00bc7e52 |
def test_get_query_object_none(self): <NEW_LINE> <INDENT> mixin = SingleObjectMixin() <NEW_LINE> mixin.get_session = mock.Mock() <NEW_LINE> self.assertRaises(ImproperlyConfigured, mixin.get_query_object) | Test not providing query_object or model. | 625941d0b57a9660fec339e5 |
def create_deployment_object(*args): <NEW_LINE> <INDENT> fh = sys.argv[2] <NEW_LINE> fh1 = sys.argv[3] <NEW_LINE> if fh.lower() == '-f': <NEW_LINE> <INDENT> with open(fh1)as f: <NEW_LINE> <INDENT> config = yaml.load(f) <NEW_LINE> name = config["metadata"]["name"] <NEW_LINE> image = config["metadata"]["image"] <NEW_LINE... | Function to create deplyment with replication
configuration details fetch from yaml input | 625941d0167d2b6e31218cf7 |
def cnr(n, r): <NEW_LINE> <INDENT> coef = fac(n) / (fac(r) * fac(n-r)) <NEW_LINE> return int(coef) | Calculate the combinatorial coefficient
| 625941d032920d7e50b28332 |
def deserialize(self, data): <NEW_LINE> <INDENT> nodes = data.split(",") <NEW_LINE> def _deserialize(nodelist): <NEW_LINE> <INDENT> if nodelist[0] == "None": <NEW_LINE> <INDENT> nodelist.pop(0) <NEW_LINE> return None <NEW_LINE> <DEDENT> root = TreeNode(nodelist.pop(0)) <NEW_LINE> root.left = _deserialize(nodelist) <NEW... | Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode | 625941d07c178a314d6ef5c2 |
def _display_folder_scandir(self, folder, reset=True, update_bar=True): <NEW_LINE> <INDENT> folder = abspath(folder) <NEW_LINE> if not self.path_bar.winfo_ismapped(): <NEW_LINE> <INDENT> self.path_bar.grid() <NEW_LINE> self.right_tree.configure(displaycolumns=("size", "date")) <NEW_LINE> w = self.right_tree.winfo_width... | Display the content of folder in self.right_tree.
Arguments:
* reset (boolean): forget all the part of the history right of self._hist_index
* update_bar (boolean): update the buttons in path bar | 625941d044b2445a339321f7 |
def dNdxi(self,eta,xi): <NEW_LINE> <INDENT> dNdxi_mat = np.zeros((3,3*9)) <NEW_LINE> dNdxi1 = .25*(eta**2-eta)*(2*xi-1) <NEW_LINE> dNdxi2 = -(eta**2-eta)*xi <NEW_LINE> dNdxi3 = .25*(eta**2-eta)*(2*xi+1) <NEW_LINE> dNdxi4 = .5*(1-eta**2)*(2*xi-1) <NEW_LINE> dNdxi5 = -2*(1-eta**2)*xi <NEW_LINE> dNdxi6 = .5*(1-eta**2)*(2*... | Generates a gradient of the shape-function value weighting matrix.
Intended primarily as a private method but left public, this method
generates the gradient of the weighting matrix with respect to xi and
is used to interpolate values within the element. This method however
is mainly reserved for the cross-sectional a... | 625941d0be8e80087fb20da3 |
def start(self, instance_name="", capture_output=True, wait=True, update_service_list=True): <NEW_LINE> <INDENT> if not update_service_list: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> svc_list = [] <NEW_LINE> try: <NEW_LINE> <INDENT> with open(paths.SVC_LIST_FILE, 'r') as f: <NEW_LINE> <INDENT> svc_list = json.load... | When a service is started record the fact in a special file.
This allows ipactl stop to always stop all services that have
been started via ipa tools | 625941d01d351010ab855c7d |
def test_default(self): <NEW_LINE> <INDENT> snapshot = Snapshot(label='test_name', snapshot_type='state') <NEW_LINE> self.assertIsInstance(snapshot.id, int) <NEW_LINE> self.assertEqual(snapshot.name, 'test_name') <NEW_LINE> self.assertEqual(snapshot.type, 'state') <NEW_LINE> self.assertEqual(snapshot.duration, 0) <NEW_... | Test default snapshot. | 625941d0fb3f5b602dac37f5 |
def __add__(self, other): <NEW_LINE> <INDENT> return Point(self.x + other.x, self.y + other.y) | Return a new point (point1 + point2). | 625941d031939e2706e4cfcb |
def __eq__(self, f): <NEW_LINE> <INDENT> return bool() | bool Qt.Alignment.__eq__(Qt.Alignment f) | 625941d0287bf620b61d3bc5 |
def get_output_score_metadata(self): <NEW_LINE> <INDENT> return | Gets the metadata for the output score start range.
:return: metadata for the output score start range
:rtype: ``osid.Metadata``
*compliance: mandatory -- This method must be implemented.* | 625941d0627d3e7fe0d68fb2 |
def generate_public_key_rsa(private_key): <NEW_LINE> <INDENT> return private_key.publickey() | Generate a public key from its private key
:param private_key:
:return: | 625941d05fdd1c0f98dc0395 |
def __str__(self): <NEW_LINE> <INDENT> return "[{:s}] {:d}/{:d}".format(__class__.__name__, self.__width, self.__height) | makes object readable | 625941d0d268445f265b4fcf |
def get_expire_after(request): <NEW_LINE> <INDENT> if EXPIRE_AFTER_CUSTOM_SESSION_KEY is None: <NEW_LINE> <INDENT> return EXPIRE_AFTER <NEW_LINE> <DEDENT> expire_after_value = request.session.get( EXPIRE_AFTER_CUSTOM_SESSION_KEY ) <NEW_LINE> if isinstance(expire_after_value, int) and expire_after_value > 0: <NEW_LINE> ... | Calculate EXPIRE_AFTER value while accounting for
custom/user-defined value | 625941d0097d151d1a222fbb |
def sendMailNotification(email, path, level): <NEW_LINE> <INDENT> msg = "EOS quota exceeded (or over %s%%) for %s." % (WARNING, path) <NEW_LINE> msg += " Please investigate it ASAP." <NEW_LINE> command = 'echo "%s" | ' % msg <NEW_LINE> command += 'mail -s "%s: eos quota for %s"' % (level, path) <NEW_LINE> command += ' ... | Sends an email to the list of recipients provided as argument
reporting the EOS path which is about to face problems. | 625941d04a966d76dd551171 |
def test_empty(self): <NEW_LINE> <INDENT> p = Project() <NEW_LINE> assert isinstance(p, Project) <NEW_LINE> assert len(p.samples) == 0 | Verify that an empty Project instance can be created | 625941d045492302aab5e425 |
def shell_set_title(): <NEW_LINE> <INDENT> global cmd_shell_buffer <NEW_LINE> if cmd_shell_buffer: <NEW_LINE> <INDENT> weechat.buffer_set(cmd_shell_buffer, 'title', '%s.py %s | "q": close buffer | Working dir: %s' % (SCRIPT_NAME, SCRIPT_VERSION, os.getcwd())) | Set title on shell buffer (with working directory). | 625941d04e4d5625662d4539 |
def createActions(self): <NEW_LINE> <INDENT> pass <NEW_LINE> self.setDefaultActionsValues() | Create qt actions | 625941d071ff763f4b5497ee |
def checkPoint(self, point): <NEW_LINE> <INDENT> gtx, ltx = self.isIn(point, (0, 0, 0), 0) <NEW_LINE> gty, lty = self.isIn(point, (0, 0, 0), 1) <NEW_LINE> gtz, ltz = self.isIn(point, (0, 0, 0), 2) <NEW_LINE> intersects = set() <NEW_LINE> if gtx and gty and gtz: <NEW_LINE> <INDENT> intersects = intersects.union(self.cel... | Which subtrees in the point in | 625941d030dc7b7665901ac8 |
def api(host="localhost", port=80, routes={}, actionsmap=None, locales_dir=None): <NEW_LINE> <INDENT> from moulinette.interfaces.api import Interface as Api <NEW_LINE> m18n.set_locales_dir(locales_dir) <NEW_LINE> try: <NEW_LINE> <INDENT> Api( routes=routes, actionsmap=actionsmap, ).run(host, port) <NEW_LINE> <DEDENT> e... | Web server (API) interface
Run a HTTP server with the moulinette for an API usage.
Keyword arguments:
- host -- Server address to bind to
- port -- Server port to bind to
- routes -- A dict of additional routes to add in the form of
{(method, uri): callback} | 625941d0435de62698dfddaf |
def comparison_to_original_and_gt_datasets(samples, real_samples, ground_truth_samples, ground_truth_probs): <NEW_LINE> <INDENT> aux = np.unique(samples,axis=1,return_counts=True) <NEW_LINE> sim_samples_probs = aux[1]/np.sum(aux[1]) <NEW_LINE> sim_samples_unique = aux[0] <NEW_LINE> print(sim_samples_unique.shape) <NEW_... | auxiliary function for evaluate_approx_distribution that computes the prob in the training data set, in the ground truth dataset and in the generated dataset | 625941d0099cdd3c635f0dbd |
def get_email(email): <NEW_LINE> <INDENT> connection, cursor = connect_db() <NEW_LINE> cursor.execute("SELECT * FROM users WHERE email='{email}';".format(email=email)) <NEW_LINE> username = cursor.fetchall() <NEW_LINE> disconnect_db(connection,cursor) <NEW_LINE> return username | Check if there is already an account with that email. | 625941d0cdde0d52a9e53196 |
def next_link(city, dimension): <NEW_LINE> <INDENT> return 'http://localhost:5000/{city}/{dimension}' .format(city=city.replace('"', ''), dimension='<{}>'.format(dimension)) | Produce a valid link to get deeper into the hierarchy of a city's
dimensions
:param city: (string) name of the city
:param dimension: (string) URI of a dimension of the city
:return: (string) a link for redirection purposes | 625941d00a366e3fb873e97d |
def random(self): <NEW_LINE> <INDENT> result = self.db.zrangebyscore(REDIS_KEY, MAX_SCORE, MAX_SCORE) <NEW_LINE> if len(result): <NEW_LINE> <INDENT> return choice(result) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = self.db.zrevrange(REDIS_KEY, 0, 100) <NEW_LINE> if len(result): <NEW_LINE> <INDENT> return cho... | 随机获取有效代理,首先尝试获取最高分数代理,如果最高分数不存在,则按照排名获取,否则异常
:return: 随机代理 | 625941d04c3428357757c489 |
def close(self): <NEW_LINE> <INDENT> self.logger.info("Closing all workers") <NEW_LINE> for worker in self.workers: <NEW_LINE> <INDENT> worker.terminate() <NEW_LINE> worker.join() <NEW_LINE> <DEDENT> self.logger.info("All workers killed") <NEW_LINE> self.logger.info("Terminating") | Terminates all child processes (workers and shared memory manager). | 625941d0462c4b4f79d1d833 |
def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.logs = [] | Intitialize a file object
Attributes
----------
path : str
Path to the folder | 625941d0d8ef3951e324369f |
def download_base(self): <NEW_LINE> <INDENT> self.renew_tree('remote', self.db_control.get_remote_storage()) | Performs downloading standart base from json.
:return: None | 625941d0187af65679ca5281 |
def processEnded(self, reason): <NEW_LINE> <INDENT> self._getDeferred().callback(self.buffer) | Fire the Deferred at self.deferred with the data collected
from the L{ConchTestForwardingPort} connection, if any. | 625941d08a349b6b435e82d6 |
def update_from_ipif(self, ipifdata): <NEW_LINE> <INDENT> data = copy.deepcopy(ipifdata) <NEW_LINE> data.pop("@id", None) <NEW_LINE> data.pop("id", None) <NEW_LINE> if self.person.id == data["person"]["@id"]: <NEW_LINE> <INDENT> self.person.update_from_ipif(data.pop("person")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE... | Update Factoid from IPIF conform json-like dict.
| 625941d07d847024c06be41e |
def setUp(self): <NEW_LINE> <INDENT> self.new_user = Credentials(1,"winnie","mwikali") | Setting up the structure before each test | 625941d063b5f9789fde7248 |
def predict(self, x_test, n_samples=20, temperature=1.0): <NEW_LINE> <INDENT> pred = self.sample(x_test, n_samples, temperature=temperature) <NEW_LINE> return pred.mean(0), pred.var(0) | Given `x_test`, return pred mean and var.
Args:
x_test (Tensor): (N, *)
n_samples (int): # samples to estimate the mean and var
Returns:
pred_mean, pred_var | 625941d0be7bc26dc91cd761 |
def main(): <NEW_LINE> <INDENT> print(__doc__) | Function to be called when file executed via terminal. | 625941d023849d37ff7b31f1 |
def __init__(self, v1, v2): <NEW_LINE> <INDENT> self.data=[] <NEW_LINE> x=-1 <NEW_LINE> for x in range(0,min(len(v1),len(v2))): <NEW_LINE> <INDENT> self.data.append(v1[x]) <NEW_LINE> self.data.append(v2[x]) <NEW_LINE> <DEDENT> if x == len(v1)-1: <NEW_LINE> <INDENT> for y in range(x+1,len(v2)): <NEW_LINE> <INDENT> self.... | Initialize your data structure here.
:type v1: List[int]
:type v2: List[int] | 625941d05510c4643540f545 |
def compute_gradients(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._opt.compute_gradients(*args, **kwargs) | Compute gradients of "loss" for the variables in "var_list".
This simply wraps the compute_gradients() from the real optimizer.
Args:
*args: Arguments for compute_gradients().
**kwargs: Keyword arguments for compute_gradients().
Returns:
A list of (gradient, variable) pairs. | 625941d066656f66f7cbc30d |
def get_mime(self, path, isdir): <NEW_LINE> <INDENT> if isdir: <NEW_LINE> <INDENT> file_type = FOLDER <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_type = mimetypes.guess_type(path)[0] <NEW_LINE> if not file_type: <NEW_LINE> <INDENT> file_type = UNKNOWN <NEW_LINE> <DEDENT> <DEDENT> return file_type | 猜测文件类型, 根据它的文件扩展名 | 625941d05fc7496912cc3ae0 |
def to_json(self, attrs=None): <NEW_LINE> <INDENT> tmp = {} <NEW_LINE> if type(attrs) is not list: <NEW_LINE> <INDENT> return(self.__dict__) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in attrs: <NEW_LINE> <INDENT> if i in self.__dict__: <NEW_LINE> <INDENT> tmp[i] = self.__dict__[i] <NEW_LINE> <DEDENT> <DEDENT>... | return in dictionary form | 625941d09c8ee82313fbb8d8 |
def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/LinkedIn/Companies/CompaniesFollowed') | Create a new instance of the CompaniesFollowed Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 625941d05510c4643540f546 |
def grok_filter(app): <NEW_LINE> <INDENT> return GrokMiddleware(app, conf) | @app the next middleware in the pipeline. | 625941d0cc40096d61595ab3 |
def is_valid(self): <NEW_LINE> <INDENT> return self.range[0] > -1 and self.range[1] > -1 | Checks if the range is a valid range or not.
A valid range is greater than INVALID_RANGE in both sides of the range.
:return: | 625941d01f037a2d8b946360 |
def __init__(self, sta1intf, sta2intf, snr=10): <NEW_LINE> <INDENT> self.sta1intf = sta1intf <NEW_LINE> self.sta2intf = sta2intf <NEW_LINE> self.snr = snr | Describes a link between two interfaces using the SNR
:param sta1intf: Instance of WmediumdIntfRef
:param sta2intf: Instance of WmediumdIntfRef
:param snr: Signal Noise Ratio as int
:type sta1intf: WmediumdIntfRef
:type sta2intf: WmediumdIntfRef
:type snr: int | 625941d0a8ecb033257d322f |
def isValidSudoku(self, board): <NEW_LINE> <INDENT> row = [[0] * 9] * 9 <NEW_LINE> col = [[0] * 9] * 9 <NEW_LINE> for i in range(0, 3): <NEW_LINE> <INDENT> for j in range(0, 3): <NEW_LINE> <INDENT> box = [0] * 9 <NEW_LINE> for k in range(0, 3): <NEW_LINE> <INDENT> for l in range(0, 3): <NEW_LINE> <INDENT> if board[k + ... | :type board: List[List[str]]
:rtype: bool | 625941d03317a56b86939dba |
def get_excution_time(session, cmd): <NEW_LINE> <INDENT> out = session.cmd_output(cmd) <NEW_LINE> try: <NEW_LINE> <INDENT> return float(re.search(r"real\s+\dm(.*)s", out).group(1)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> exceptions.TestError("Unable to read realtime, cmd output: %s" % out) | This function is used to measure the real execution time of
the command in guest through shell command "time".
:param session: Guest session
:param cmd: Commands to execute
:return: The real execution time | 625941d0379a373c97cfaca7 |
def waits_for_score(submission): <NEW_LINE> <INDENT> return submission.compilation_outcome != "fail" and not submission.scored() | Return if submission could be scored but it currently is
not.
submission (Submission): the submission to check. | 625941d07b180e01f3dc495f |
def brief_report(net_value, benchmark, riskfree_rate, freq): <NEW_LINE> <INDENT> assert len(net_value) == len( benchmark), '\'net_value\' should have the same length as \'benchmark\'' <NEW_LINE> ret = cal_ret(net_value) <NEW_LINE> benchmark_ret = cal_ret(benchmark) <NEW_LINE> alpha = cal_rawalpha(net_value, benchmark, ... | 输入策略的净值等数据,对策略的基本状况做一个简报
内容包含:
粗略alpha,粗略beta,最大回撤,最大回撤起始期,夏普比率,信息比率
@param:
net_value: 策略净值数据,要求为pd.Series格式
benchmark: 对比基准净值数据,要求为pd.Series格式
riskfree_rate: 无风险利率
freq: 数据的频率,例如日净值数据对应250,月净值数据对应12 | 625941d023e79379d52ee6c6 |
def GetMemUsed(self): <NEW_LINE> <INDENT> return _snap.TLFlt_GetMemUsed(self) | GetMemUsed(TLFlt self) -> int
Parameters:
self: TLFlt const * | 625941d0a4f1c619b28b019a |
def parse_threadsafe_override(value): <NEW_LINE> <INDENT> return parse_per_module_option( value, boolean_action.BooleanParse, lambda _: True, 'Invalid threadsafe override: %r', None, 'Expected "module:threadsafe_override": %r', None, 'Duplicate threadsafe override value for module %s') | Returns the parsed value for the --threadsafe_override flag.
Args:
value: A str containing the flag value for parse. The format should follow
one of the following examples:
1. "False" - All modules override the YAML threadsafe configuration
as if the YAML contained False.
2. "default... | 625941d0379a373c97cfaca8 |
def test_create_vpnservice_with_limited_params(self): <NEW_LINE> <INDENT> resource = 'vpnservice' <NEW_LINE> cmd = vpnservice.CreateVPNService(test_cli20.MyApp(sys.stdout), None) <NEW_LINE> subnet = 'mysubnet-id' <NEW_LINE> router = 'myrouter-id' <NEW_LINE> tenant_id = 'mytenant-id' <NEW_LINE> my_id = 'my-id' <NEW_LINE... | vpn-service-create with limited params. | 625941d015fb5d323cde0c73 |
def p_clause_assertions(p): <NEW_LINE> <INDENT> p[0] = p[1:] | clause_assertions : _ASSERTIONS_ expr_PLUSSemicolon
| 625941d0d10714528d5ffe47 |
def get_hm_rating_xls(xls_path): <NEW_LINE> <INDENT> data = xlrd.open_workbook(xls_path) <NEW_LINE> table = data.sheets()[0] <NEW_LINE> rating_file = table.cell(1, 0).value.strip() <NEW_LINE> b_col = table.col_values(1) <NEW_LINE> hm_ratings = [] <NEW_LINE> for i in range(1, len(b_col)): <NEW_LINE> <INDENT> if type(b_c... | excel中获取rank列表
数据格式为:第一列第二行为检索文书名,第二列为被检索文书的人工评价等级
:param xls_path:
:return: query_filename, [lable1, lable2, ...] | 625941d076d4e153a657ec94 |
def getPref(self,value,default,valuetype="Unsigned"): <NEW_LINE> <INDENT> p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View") <NEW_LINE> if valuetype == "Unsigned": <NEW_LINE> <INDENT> c = p.GetUnsigned(value,default) <NEW_LINE> r = float((c>>24)&0xFF)/255.0 <NEW_LINE> g = float((c>>16)&0xFF)/255.0 <NEW_LIN... | retrieves a view pref value | 625941d07047854f462a156c |
def derivative(P): <NEW_LINE> <INDENT> p=Polynome([]) <NEW_LINE> for i in range(1,P.deg+1): <NEW_LINE> <INDENT> p[i-1]=P[i]*i <NEW_LINE> <DEDENT> return p | Renvoie le polynôme dérivé de P.
Exemples:
>>> X = Polynome([0,1])
>>> derivative(X**2)
2*X
>>> derivative(5*X**3 - 6*X +3)
15*X**2 - 6 | 625941d08a43f66fc4b541c7 |
def __init__(self, value, *args): <NEW_LINE> <INDENT> super(If, self).__init__(value, *args) <NEW_LINE> self.name = 'if' | Initialize. | 625941d016aa5153ce3625da |
def _fetch_ismearw(self, xml): <NEW_LINE> <INDENT> entry = self._find( xml, './/parameters/separator[@name="electronic"]/' 'separator[@name="electronic smearing"]/' 'i[@name="ISMEAR"]' ) <NEW_LINE> if entry is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ismear = self._convert_i(entry) <NEW_LINE> return is... | Fetch and set ismear using etree.
Parameters
----------
xml : object
An ElementTree object to be used for parsing.
Returns
-------
ismear : int
If ISMEAR is found it is returned.
Notes
-----
Determines which smearing factor is used on the electrons. | 625941d00383005118ecf745 |
def SmoothLeakyRelu(slope): <NEW_LINE> <INDENT> return lambda x: smooth_leaky_relu(x, alpha=slope) | Smooth Leaky ReLU activation function.
Args:
slope (float): slope to control degree of non-linearity.
Returns:
Lambda function for computing smooth Leaky ReLU. | 625941d056b00c62f0f147bc |
def generate_hash(string): <NEW_LINE> <INDENT> byte_string = string.encode() <NEW_LINE> hashed_string = bcrypt.hashpw(byte_string, bcrypt.gensalt()) <NEW_LINE> return hashed_string.decode() | Generate a cryptographic hash from a string.
:param str string: A string to generate the hash from
:returns str: The generated hash | 625941d060cbc95b062c66a6 |
def construct_perceptron(weights, bias): <NEW_LINE> <INDENT> def perceptron(input): <NEW_LINE> <INDENT> a = sum((weights[i] * input[i]) for i in range(len(input))) + bias <NEW_LINE> return 1 if a >= 0 else 0 <NEW_LINE> <DEDENT> return perceptron | Returns a perceptron function using the given parameters. | 625941d09b70327d1c4e0f38 |
def on_modified(self, event): <NEW_LINE> <INDENT> pass | Called when a file or directory is modified.
:param event:
Event representing file/directory modification.
:type event:
:class:`DirModifiedEvent` or :class:`FileModifiedEvent` | 625941d0097d151d1a222fbc |
def condense_lines(code): <NEW_LINE> <INDENT> m = len(code) <NEW_LINE> s = '' <NEW_LINE> r = [] <NEW_LINE> i = 0 <NEW_LINE> c = 0 <NEW_LINE> while i < m: <NEW_LINE> <INDENT> if code[i].endswith(' \\\n'): <NEW_LINE> <INDENT> s = s + ' ' + code[i][:-2].strip() <NEW_LINE> c = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Take an array of code, join lines ending with a \, and return | 625941d0c4546d3d9de72b97 |
def copy1(data): <NEW_LINE> <INDENT> copied = data <NEW_LINE> return copied | Returns a copy of the given list of data
Preconditions:
:param data: a list
Return:
a copy of the given data | 625941d0287bf620b61d3bc6 |
def resize_embedded_gui(self, hwnd): <NEW_LINE> <INDENT> assert self._as_parameter_ <NEW_LINE> width = (c_int)() <NEW_LINE> height = (c_int)() <NEW_LINE> zzub_plugin_resize_embedded_gui(self, hwnd, width, height) <NEW_LINE> return width.value, height.value | Request resize of the embedded user interface.
The plugin receives a suggested target size in the width and height parameters, but can choose to resize itself to any size and return the final width and height in the respective output parameters. These could differ from the target size when the user interface has a mini... | 625941d02eb69b55b151ca13 |
def get_num_wallets(self): <NEW_LINE> <INDENT> if self.num_wallets is None: <NEW_LINE> <INDENT> self.get_pct_bitcoind_wallets() <NEW_LINE> <DEDENT> return self.num_wallets | Return the int number of unique wallets in this block.
Does not include coinbase transaction. | 625941d026068e7796caee43 |
def contains(self, coordinate): <NEW_LINE> <INDENT> pixel = coordinate.to_pixel(self.wcs) <NEW_LINE> return 0.0 <= pixel.x < self.xsize and 0.0 <= pixel.y < self.ysize | This function ...
:param coordinate:
:return: | 625941d03c8af77a43ae3904 |
def num_powers_with(self, centres): <NEW_LINE> <INDENT> return self.final_year_scs.filter(count=centres).count() | Returns the number of powers that own the specified number of supply centres. | 625941d0dc8b845886cb5698 |
def get_book_dict(**keywords): <NEW_LINE> <INDENT> book = get_book(**keywords) <NEW_LINE> return book.to_dict() | Obtain a dictionary of two dimensional arrays
It accepts the same parameters as :meth:`~pyexcel.get_book`
but return a dictionary instead. | 625941d07d43ff24873a2e03 |
def cb0(self): <NEW_LINE> <INDENT> print('cb') | Callback function without callback value. | 625941d097e22403b379d0fd |
def test_wrong_imbalance_passed(self): <NEW_LINE> <INDENT> bar_gen = ds.ConstImbalanceBars(metric='cum_buy_volume', expected_imbalance_window=10, exp_num_ticks_init=100, analyse_thresholds=False, batch_size=10000) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> bar_gen.batch_run(self.path, verbose=Fa... | Tests ValueError raise when wrong imbalance was passed | 625941d099fddb7c1c9de4f4 |
def create(name, store, **kwargs): <NEW_LINE> <INDENT> pass | Create a new flag with the given name and, optionally, extra data,
persisted in the given store. | 625941d0c432627299f04da9 |
def _guess_the_number(actual): <NEW_LINE> <INDENT> prompt = 'Guess a number between 1 and 10: ' <NEW_LINE> last_guess = None <NEW_LINE> while True: <NEW_LINE> <INDENT> guess = input(prompt) <NEW_LINE> print(guess) <NEW_LINE> if actual > guess: <NEW_LINE> <INDENT> if last_guess and last_guess >= guess and last_guess < a... | >>> sys.stdin = _raw([1, 7, 4, 8, 5])
>>> _guess_the_number(5)
Guess a number between 1 and 10: 1
Higher: 7
Lower: 4
Higher: 8
Lower: 5
Yes, it's 5
>>> sys.stdin = _raw([6, 7, 7, 4, 5])
>>> _guess_the_number(5)
Guess a number between 1 and 10: 6
Lower: 7
7 isn't lower than 6!
Lower: 7
7 isn't lower than 7!
Lower: 4
Hi... | 625941d021a7993f00bc7e54 |
def _redirect_empty_clusters(self, empty_clusters): <NEW_LINE> <INDENT> for e in empty_clusters: <NEW_LINE> <INDENT> assert (self.label_bank != e).all().item(), "Cluster #{} is not an empty cluster.".format(e) <NEW_LINE> max_cluster = np.bincount( self.label_bank, minlength=self.num_classes).argmax().ite... | Re-direct empty clusters. | 625941d0b57a9660fec339e7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.