code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def kbits(n): <NEW_LINE> <INDENT> for i in xrange(0, 2**n): <NEW_LINE> <INDENT> yield '{:0{n}b}'.format(i, n=n) | Generator of all numbers of size n bits.
Return:
a generator objective | 625941d263f4b57ef00012ce |
def unmount_fs(module, filesystem): <NEW_LINE> <INDENT> unmount_cmd = module.get_bin_path('unmount', True) <NEW_LINE> if not module.check_mode: <NEW_LINE> <INDENT> rc, unmount_out, err = module.run_command("%s %s" % (unmount_cmd, filesystem)) <NEW_LINE> if rc != 0: <NEW_LINE> <INDENT> module.fail_json(msg="Failed to ru... | Unmount a file system. | 625941d23317a56b86939e0d |
def calcRatios(a, b): <NEW_LINE> <INDENT> return [n / d for (n, d) in zip(a, b)] | Calculate the ratio of a over b, where a and b are both a list of numpy arrays
with the same dimensions (i.e. length of list and length of numpy arrays) | 625941d23539df3088e2e502 |
def _human_bytes(size): <NEW_LINE> <INDENT> power = 2**10 <NEW_LINE> n = 0 <NEW_LINE> power_of_n = {0: 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'} <NEW_LINE> while size > power: <NEW_LINE> <INDENT> size /= power <NEW_LINE> n += 1 <NEW_LINE> <DEDENT> value = "{:.2f} {}".format(size, power_of_n[n]) <NEW_LINE> return value | Return the given bytes as a human friendly KB, MB, GB, or TB string | 625941d2435de62698dfde04 |
def __init__(self, group_name, group_id, members): <NEW_LINE> <INDENT> self.group_name = group_name <NEW_LINE> self.group_id = group_id <NEW_LINE> self.members = members <NEW_LINE> self.bot_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> self.tags = self.load_tags() | :param group_name: name of the group
:param group_id: id of the group
:param members: list of members of the group | 625941d2bd1bec0571d907e6 |
def log_deletion(self, request, object, object_repr): <NEW_LINE> <INDENT> from .models import LogEntry, DELETION <NEW_LINE> return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(object).pk, object_id=object.pk, object_repr=object_repr, action_flag=DELETION, ) | Log that an object will be deleted. Note that this method must be
called before the deletion.
The default implementation creates an admin LogEntry object. | 625941d2bd1bec0571d907e7 |
def on_response(self, response, decorator=None, request=None): <NEW_LINE> <INDENT> decorator = decorator or self.finder(Mock()) <NEW_LINE> request = request or RequestFactory().get("/") <NEW_LINE> @decorator <NEW_LINE> def view(request): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> return view(request) | Apply given decorator to dummy view, return given response. | 625941d25510c4643540f599 |
def test_get_all_available_lotteries_out_of_time(client): <NEW_LINE> <INDENT> with mock.patch('api.routes.api.get_time_index', side_effect=OutOfHoursError()): <NEW_LINE> <INDENT> resp = client.get('/lotteries/available') <NEW_LINE> <DEDENT> assert [] == resp.get_json() <NEW_LINE> with mock.patch('api.routes.api.get_tim... | test proper infomation is returned from the API
when it is out of time
target_url: /lotteries/available | 625941d226238365f5f0f026 |
def getConnection(): <NEW_LINE> <INDENT> conn = socket.socket() <NEW_LINE> conn.connect((IP_ADDRESS, PORT)) <NEW_LINE> return conn | Функция получения связи с модулем
Возвращает активный сокет | 625941d24428ac0f6e5ba9aa |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not IntentCategory.objects.filter(intent_label=self.intent_label): <NEW_LINE> <INDENT> super().save(*args, **kwargs) | ensures the unique key | 625941d22c8b7c6e89b35977 |
def get_properties(self): <NEW_LINE> <INDENT> return self.props.copy() | Returns a dictionary containing all the properties of the layer.
The returned dictionary contains all colors, labels, etc. set by the
user. This method is used for saving layers, or passing a layer to
the copy-paste-function or the drag-and-drop function. | 625941d25e10d32532c5f0de |
def _new_with_changes(self, data, offset, shape=None, dtype=None, strides=None, queue=_copy_queue, allocator=None): <NEW_LINE> <INDENT> fast = True <NEW_LINE> size = self.size <NEW_LINE> if shape is None: <NEW_LINE> <INDENT> shape = self.shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fast = False <NEW_LINE> size =... | :arg data: *None* means allocate a new array. | 625941d25fdd1c0f98dc03eb |
def effective_n_jobs(self, n_jobs): <NEW_LINE> <INDENT> if n_jobs == 0: <NEW_LINE> <INDENT> raise ValueError('n_jobs == 0 in Parallel has no meaning') <NEW_LINE> <DEDENT> elif mp is None or n_jobs is None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif n_jobs < 0: <NEW_LINE> <INDENT> n_jobs = max(mp.cpu_count() ... | Determine the number of jobs which are going to run in parallel | 625941d291af0d3eaac9bbd1 |
def customize_compiler_for_nvcc(self): <NEW_LINE> <INDENT> self.src_extensions.append('.cu') <NEW_LINE> default_compiler_so = self.compiler_so <NEW_LINE> super = self._compile <NEW_LINE> def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): <NEW_LINE> <INDENT> print(extra_postargs) <NEW_LINE> if os.path.splite... | inject deep into distutils to customize how the dispatch
to gcc/nvcc works.
If you subclass UnixCCompiler, it's not trivial to get your subclass
injected in, and still have the right customizations (i.e.
distutils.sysconfig.customize_compiler) run on it. So instead of going
the OO route, I have this. Note, it's kindof... | 625941d2460517430c39433a |
def getEngines (self): <NEW_LINE> <INDENT> return self.engines | Returns list of engine dicts | 625941d2187af65679ca52d7 |
def test_fails_and_outputs_json(self): <NEW_LINE> <INDENT> self.fail(submission.return_json()) | This test should fail and print json | 625941d29c8ee82313fbb92d |
def test_syntactic_parsing(self): <NEW_LINE> <INDENT> well_formed_expressions = [ '(-(Axa & (Rx ^ Rx)) ^ Caz)', '($x(Px) & Tx)', '$x((Px & Tx))', 'Pa', 'Abx' ] <NEW_LINE> assert all([grammar.parse_expression_with_grammar(e) for e in well_formed_expressions]) <NEW_LINE> not_well_formed_expressions = [ '(-(Axsa & (Rx ^ R... | Test if lark grammar recognizes wff | 625941d27c178a314d6ef618 |
def pathSum(self, root, sum): <NEW_LINE> <INDENT> ret = 0 <NEW_LINE> if not root : <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if sum == root.val: <NEW_LINE> <INDENT> ret += 1 <NEW_LINE> <DEDENT> ret += self.pathSum(root.left,sum) if root.left else 0 <NEW_LINE> ret += self.pathSum(root.right,sum) if root.right e... | :type root: TreeNode
:type sum: int
:rtype: int | 625941d238b623060ff0afa5 |
def merge(a, b): <NEW_LINE> <INDENT> x = next(a) <NEW_LINE> y = next(b) <NEW_LINE> while True: <NEW_LINE> <INDENT> if x < y: <NEW_LINE> <INDENT> yield x <NEW_LINE> x = next(a) <NEW_LINE> <DEDENT> elif y < x: <NEW_LINE> <INDENT> yield y <NEW_LINE> y = next(b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield x <NEW_LI... | >>> def sequence(start, step):
... while True:
... yield start
... start += step
>>> a = sequence(2, 3) # 2, 5, 8, 11, 14, ...
>>> b = sequence(3, 2) # 3, 5, 7, 9, 11, 13, 15, ...
>>> result = merge(a, b) # 2, 3, 5, 7, 8, 9, 11, 13, 14, 15
>>> [next(result) for _ in range(10)]
[2, 3, 5, 7, 8, 9, 11,... | 625941d24527f215b584c60d |
def null_space(M, k, k_skip=1, eigen_solver='arpack', tol=1E-6, max_iter=100, random_state=None): <NEW_LINE> <INDENT> if eigen_solver == 'auto': <NEW_LINE> <INDENT> if M.shape[0] > 200 and k + k_skip < 10: <NEW_LINE> <INDENT> eigen_solver = 'arpack' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> eigen_solver = 'dense' <... | Find the null space of a matrix M.
Parameters
----------
M : {array, matrix, sparse matrix, LinearOperator}
Input covariance matrix: should be symmetric positive semi-definite
k : int
Number of eigenvalues/vectors to return
k_skip : int, default=1
Number of low eigenvalues to skip.
eigen_solver : {'auto... | 625941d21f5feb6acb0c4d06 |
def cname_remove(args): <NEW_LINE> <INDENT> info = host_info_by_name(args.name) <NEW_LINE> hostname = info['name'] <NEW_LINE> alias = clean_hostname(args.alias) <NEW_LINE> if not info['cnames']: <NEW_LINE> <INDENT> cli_warning("\"{}\" doesn't have any CNAME records.".format(hostname)) <NEW_LINE> <DEDENT> for cname in i... | Remove CNAME record.
| 625941d207d97122c4178a45 |
def get_ancestry_with_http_info(self, ancestry_name, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = ['ancestry_name', 'with_vulnerabilities', 'with_features'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append... | get_ancestry # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_ancestry_with_http_info(ancestry_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str ancestry_name: (required)
:param b... | 625941d2ad47b63b2c50a137 |
def test_purge_sources(self, mocker): <NEW_LINE> <INDENT> mock = mocker.patch('udata.harvest.actions.purge_sources') <NEW_LINE> purge_harvest_sources() <NEW_LINE> mock.assert_called_once_with() | It should purge from DB sources flagged as deleted | 625941d2442bda511e8be5cf |
def on_counterclockwise(self): <NEW_LINE> <INDENT> pass | Called when the wheel is rotated counterclockwise | 625941d2596a897236089c77 |
@app.route('/user', methods=['POST']) <NEW_LINE> def add_user(): <NEW_LINE> <INDENT> user_num = len(conn.execute("SELECT UserId from USERS").fetchall()) <NEW_LINE> name = random.choice(["bob","alice","ken","donald","joe","yustynn","wim","bella"]) <NEW_LINE> add = conn.cursor() <NEW_LINE> add.execute('''INSERT INTO USER... | Add a new user to db and call graph.update | 625941d24c3428357757c4df |
def __init__(self, opt): <NEW_LINE> <INDENT> self.display_id = opt.display_id <NEW_LINE> self.use_html = opt.is_train and opt.html <NEW_LINE> self.win_size = opt.display_winsize <NEW_LINE> self.name = opt.experiment_name <NEW_LINE> self.opt = opt <NEW_LINE> self.saved = False <NEW_LINE> if self.display_id > 0 and not s... | Superclass of task-specific visualizer
:param opt: | 625941d2d10714528d5ffe9c |
@app.route('/contact/<string:name>', methods=['PUT']) <NEW_LINE> def update_contact(name): <NEW_LINE> <INDENT> res = data_store.update_contact(name, request.form) <NEW_LINE> return make_response(res['description'], res['status']) | This endpoint updates the contact by a unique name. | 625941d201c39578d7e74ff3 |
def juggler_longest(): <NEW_LINE> <INDENT> D = {1:0} <NEW_LINE> rec = -1 <NEW_LINE> for n in naturals(1): <NEW_LINE> <INDENT> ctr = n <NEW_LINE> length = 0 <NEW_LINE> while ctr not in D: <NEW_LINE> <INDENT> ctr = _juggler_step(ctr) <NEW_LINE> length += 1 <NEW_LINE> <DEDENT> D[n] = D[ctr] + length <NEW_LINE> if D[n] > r... | Greatest Juggler Length: Positive integers that set a record for length of their Juggler sequence
OEIS A094679 | 625941d291f36d47f21ac6ab |
def coherence_infractions_histoinfractions(): <NEW_LINE> <INDENT> infractionhisto = read_table('infractionhisto') <NEW_LINE> infraction = read_table('infraction') <NEW_LINE> infraction.rename(columns={'id':'infraction_id'}, inplace=True) <NEW_LINE> infractionhisto = infractionhisto[['id', 'infraction_id', 'compterenduv... | on regarde si les infractions sont dans histoinfraction et inversement | 625941d20fa83653e4657172 |
def _get_item(self, model_id): <NEW_LINE> <INDENT> return db_accessor.get_item_by_id(Model, model_id) | Get an item from its ID | 625941d2287bf620b61d3c1a |
def filter_profiles_grid(self, column_name, filter_item): <NEW_LINE> <INDENT> is_filtered = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: filter profiles grid') <NEW_LINE> self._system_admin_page.filter_profiles_grid(column_name, filter_item) <NEW_LINE> is_filtered = True <NEW_LINE> <DEDENT> except ... | Returning filter profiles grid
Implementing logging for filter profiles grid functionality
:param column_name:
:param filter_item:
:return: True/False | 625941d2d6c5a10208144203 |
def evaluate_source_bucket_list(drivename, patterns): <NEW_LINE> <INDENT> logging.info("Evaluating the source bucket list for drive '%s'." % drivename) <NEW_LINE> rcloneCommand = ['rclone'] <NEW_LINE> rcloneSubCommand = ['lsjson'] <NEW_LINE> rcloneOptions = [] <NEW_LINE> rcloneLogOption = ['--log-file=' + s3b_logging.l... | Evaluates the list of source buckets that shall be backed up.
The existing buckets are queried and then compared to the configured bucket names and patterns.
Whenever there is a match, the bucket is added to the source bucket list. | 625941d2236d856c2ad44994 |
def read(self, source_path): <NEW_LINE> <INDENT> text = codecs.open(source_path, encoding='utf').read() <NEW_LINE> md = Markdown(extensions=self.extensions) <NEW_LINE> content = md.convert(text) <NEW_LINE> return content | Parse content and metadata of markdown files | 625941d26fb2d068a760f256 |
def _get_query_string(data): <NEW_LINE> <INDENT> params = {} <NEW_LINE> for param in data: <NEW_LINE> <INDENT> if param != 'Signature': <NEW_LINE> <INDENT> params[param] = data[param] <NEW_LINE> <DEDENT> <DEDENT> keys = sorted(params.keys()) <NEW_LINE> values = map(params.get, keys) <NEW_LINE> query_string = urlencode(... | Creates the query string.
@param data: Data of the request.
@return: Query String. | 625941d2cb5e8a47e48b7c60 |
def _get_userinfo(self): <NEW_LINE> <INDENT> if not hasattr(self, "_userinfo"): <NEW_LINE> <INDENT> self._userinfo = {} <NEW_LINE> if self.user is not None: <NEW_LINE> <INDENT> u = self.user <NEW_LINE> if u.email: <NEW_LINE> <INDENT> self._userinfo["email"] = u.email <NEW_LINE> <DEDENT> if u.get_full_name(): <NEW_LINE>... | Get a dictionary that pulls together information about the poster
safely
This dict will have ``name`` and possibly ``email`` fields. | 625941d24d74a7450ccd437b |
def _set_func(self, func): <NEW_LINE> <INDENT> self._func = func <NEW_LINE> self._is_generator = _isgeneratorfunction(self._func) <NEW_LINE> self.func_doc = getattr(func, "func_doc", None) <NEW_LINE> if self.func_doc is None: <NEW_LINE> <INDENT> self.func_doc = getattr(func, "__doc__", None) | sets the function for this evalnode - only to be used by sub-classes
that need to re-set the function after construction. | 625941d28da39b475bd6512d |
def get_entry_content(entry): <NEW_LINE> <INDENT> candidates = entry.get('content', []) <NEW_LINE> if 'summary_detail' in entry: <NEW_LINE> <INDENT> candidates.append(entry.summary_detail) <NEW_LINE> <DEDENT> for candidate in candidates: <NEW_LINE> <INDENT> if hasattr(candidate, 'type'): <NEW_LINE> <INDENT> if 'html' i... | Select the best content from an entry | 625941d25166f23b2e1a5311 |
def create_department(self, parent_id, name, custom_id=None, leader_open_id=None, leader_user_id=None, create_group_chat=False): <NEW_LINE> <INDENT> url = self._gen_request_url('/open-apis/contact/v1/department/add') <NEW_LINE> body = { 'name': name, 'parent_id': parent_id, } <NEW_LINE> body = join_dict(body, [ ('id', ... | 新增部门
:type self: OpenLark
:param parent_id: 父部门 ID
:type parent_id: str
:param name: 部门名称
:type name: str
:param name: 部门名称
:type name: str
:param custom_id: 自定义部门 ID。
该字段企业内必须唯一,不区分大小写,长度为 1 ~ 64 个字符。只能由数字、字母和“_-@.”四种字符组成,且第一个字符必须是数字或字母。
创建部门时指定的 ID 后续不允许修改,不指定该字段由系统自动生成 ID,系统生成的 ID 仅允许修改一次。
:type custom_id: ... | 625941d223e79379d52ee71b |
def test_endElement_property_prodstate(t): <NEW_LINE> <INDENT> t.irm.context = create_autospec(t.irm.context) <NEW_LINE> t.irm.curattrs['id'] = 'prodstate' <NEW_LINE> t.irm.endElement('property') <NEW_LINE> t.irm.context.return_value.setProdState.assert_called_with( int(t.charvalue) ) | if the id is 'prodstate' cary its value over in context
| 625941d2009cb60464c63569 |
def impacted_cities_table(self, row_count=5): <NEW_LINE> <INDENT> table_data = self.sorted_impacted_cities(row_count) <NEW_LINE> table_body = [] <NEW_LINE> header = TableRow(['', self.tr('Name'), self.tr('Affected (x 1000)'), self.tr('Intensity')], header=True) <NEW_LINE> for row_data in table_data: <NEW_LINE> <INDENT>... | Return a table object of sorted impacted cities.
:param row_count:optional maximum number of cities to show. Default
is 5.
The cities will be listed in the order computed by
sorted_impacted_cities
but will only list in the following format:
+------+--------+-----------------+-----------+
| Icon | Name | People... | 625941d2b830903b967e9ac2 |
def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): <NEW_LINE> <INDENT> if stats.ships_left > 0: <NEW_LINE> <INDENT> stats.ships_left -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stats.game_active = False <NEW_LINE> <DEDENT> aliens.empty() <NEW_LINE> bullets.empty() <NEW_LINE> create_fleet(ai_setting... | Respond to ship being hit by alien. | 625941d25fdd1c0f98dc03ec |
def rmdir(self, key: str): <NEW_LINE> <INDENT> raise NotImplementedError() | Delete folder based on key
:param key: str: The key to folder to delete
example::
db.rmdir(folder) # Deletes folder with key
| 625941d25fc7496912cc3b36 |
def getCloseCallback(self): <NEW_LINE> <INDENT> return _AriaPy.ArSocket_getCloseCallback(self) | getCloseCallback(self) -> ArFunctor | 625941d2004d5f362079a4ea |
def get_output(self, channel): <NEW_LINE> <INDENT> return float(self.srs.query('LAMP?'+str(channel))) | Return the output voltage of the given channel.
Parameters
----------
channel : int
The integer identifying the channel, only T0, AB, CD, EF, GH, are valid. | 625941d2cc0a2c11143dd048 |
def domain_tuple(url): <NEW_LINE> <INDENT> parsed_url = urlparse(url) <NEW_LINE> Domain = namedtuple("Domain", "full_address, name") <NEW_LINE> return Domain(f"{parsed_url.scheme}://{parsed_url.netloc}/", parsed_url.netloc) | Returns namedtuple with full domain address and domain name of given url. | 625941d2dd821e528d63b360 |
def project_array(coordinates, srcp='latlong', dstp='wintri'): <NEW_LINE> <INDENT> p1 = pyproj.Proj(proj=srcp, datum='WGS84') <NEW_LINE> p2 = pyproj.Proj(proj=dstp, datum='WGS84') <NEW_LINE> fx, fy = pyproj.transform(p1, p2, coordinates[:,0], coordinates[:,1]) <NEW_LINE> return np.dstack([fx, fy])[0] | Project a numpy (n,2) array in projection srcp to projection dstp
Returns a numpy (n,2) array. | 625941d23cc13d1c6d3c7532 |
def get_utc_stamp(): <NEW_LINE> <INDENT> return str(int(round(time.mktime(datetime.datetime.now(pytz.utc).timetuple()) * 1000))) | 产生毫秒级时间戳-UTC时间
:return:
Examples:
| ${time_stamp}= | Get Utc Stamp |
=>
| ${time_stamp} = 1535596350000 | 625941d294891a1f4081bc62 |
def __init__(self, fmt_settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.fmt_settings = fmt_settings <NEW_LINE> self.prev_image = pg.image.load('images/star.bmp') <NEW_LINE> self.image = pg.transform.scale(self.prev_image, (10, 10)) <NEW_LINE> self.rect = self.ima... | Initiliaze the star and set its starting position | 625941d230dc7b7665901b1e |
def test_parent_doesnt_exist(self): <NEW_LINE> <INDENT> key = models.InstanceGroupManager( key=instance_group_managers.get_instance_group_manager_key( 'base-name', 'revision', 'zone', ), ).put() <NEW_LINE> instance_group_managers.create(key) <NEW_LINE> self.failIf(key.get().url) | Ensures nothing happens when the parent doesn't exist. | 625941d210dbd63aa1bd2d5c |
def get_access_levels(self): <NEW_LINE> <INDENT> return current.deployment_settings.get_aaa_access_levels() | This returns an OrderedDict of access levels and their uid as
the key, e.g., {reader: "Reader",}
@return: OrderedDict | 625941d257b8e32f52483653 |
def __init__(self, source, loglevel=logging.INFO, logname="Log", logstream=sys.stdout, datatype=ccData): <NEW_LINE> <INDENT> if isinstance(source, str): <NEW_LINE> <INDENT> self.filename = source <NEW_LINE> self.isstream = False <NEW_LINE> <DEDENT> elif isinstance(source, list) and all([isinstance(s, str) for s in sour... | Initialise the Logfile object.
This should be called by a ubclass in its own __init__ method.
Inputs:
source - a single logfile, a list of logfiles, or input stream | 625941d20a50d4780f66704b |
def getRoomContent(self, roomName): <NEW_LINE> <INDENT> return self.__roomNameMapRoomContent.get(roomName) | room content getter | 625941d2fbf16365ca6f637f |
def unsubscribe(self, channel_name, subscriber): <NEW_LINE> <INDENT> self.subscribers[channel_name][subscriber] -= 1 <NEW_LINE> if self.subscribers[channel_name][subscriber] <= 0: <NEW_LINE> <INDENT> del self.subscribers[channel_name][subscriber] <NEW_LINE> <DEDENT> self.subscriber_count[channel_name] -= 1 <NEW_LINE> i... | Unsubscribes a subscriber from the redis channel.
Unsubscribes the redis client from the channel
if there are no subscribers left. | 625941d23539df3088e2e503 |
def print_scene_description(self): <NEW_LINE> <INDENT> print(str(self.worldmap.get(self.player.getX(), self.player.getY()))) <NEW_LINE> x = self.player.getX() <NEW_LINE> y = self.player.getY() <NEW_LINE> nth = self.worldmap.get(x, y - 1) <NEW_LINE> if nth != 0: <NEW_LINE> <INDENT> print("\nTo the north: {}".format(nth.... | Tell the user where they are | 625941d291af0d3eaac9bbd2 |
def clear_lbaas_data(self, throw_on_fail=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while self.vip_ids: <NEW_LINE> <INDENT> vip = self.vip_ids.pop() <NEW_LINE> self.LOG.debug('Deleting VIP: ' + str(vip)) <NEW_LINE> self.api.delete_vip(vip) <NEW_LINE> <DEDENT> while self.member_ids: <NEW_LINE> <INDENT> member ... | :type throw_on_fail: bool
:return: | 625941d23d592f4c4ed1d224 |
def lmhash(password=b''): <NEW_LINE> <INDENT> if not config.useLMhash(): <NEW_LINE> <INDENT> return lmhash_locked() <NEW_LINE> <DEDENT> return passlib_lmhash.hash(password).encode('ascii').upper() | Generates lanman password hash for a given password.
Note that the author thinks LanMan hashes should be banished from
the face of the earth. | 625941d2a79ad161976cc2fe |
def run(self): <NEW_LINE> <INDENT> previous_time = time.time() <NEW_LINE> while self.running: <NEW_LINE> <INDENT> current_time = time.time() <NEW_LINE> elapsed_time = current_time - previous_time <NEW_LINE> user_input = self.fetch_input() <NEW_LINE> self.process_input(user_input) <NEW_LINE> self.update(elapsed_time) <N... | Main game loop | 625941d2b545ff76a8913fce |
def run(self, query: str, **kwargs) -> StatementResult: <NEW_LINE> <INDENT> with self.session() as session: <NEW_LINE> <INDENT> return session.run(query, parameters=kwargs) | Execute a query.
Opens a new session and runs query on it with **kwargs used for
parameter substition.
:param str query:
Query to execute. May contain variables enclosed in curly braces
for variable substitution.
:param kwargs:
Keywoard arguments used for variable substitution in query.
:returns neo4j.v1.... | 625941d2d268445f265b5026 |
def update_user_by_username1(self, request, username, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.update_user_by_username1_with_http_info(request, username, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = ... | Update profile by username # noqa: E501
Updates profile with a user with given username # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_user_by_username1(request, username, async_req=True)
>>> result = thre... | 625941d27b25080760e39611 |
def test_setitem_strkey_commakeyerror(self, real_comma_table): <NEW_LINE> <INDENT> headers = list(real_comma_table[0].keys()) <NEW_LINE> row_count = len(real_comma_table) <NEW_LINE> col_count = len(headers) <NEW_LINE> assert row_count > 0 and col_count > 0 <NEW_LINE> bogus_field_col = [self.SOME_STRING] * row_count <NE... | Checks to see whether setting an item with a `str` key in
a `CommaTable` properly fails if the key in question does
not correspond to a valid column name. | 625941d27b180e01f3dc49b4 |
def handler(event, context): <NEW_LINE> <INDENT> if not event['Records']: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> records = [formatter(record, delimiter) for record in event['Records']] <NEW_LINE> response = firehose_client.put_record_batch( DeliveryStreamName=firehose_stream_name, Records=records) <NEW_LINE> ... | Main lambda handler.
The handler grabs events from Kinesis and forwards their content to
Firehose after formatting them.
Parameters
----------
event: dict
Contains Records grabbed from the Kinesis stream. | 625941d2d164cc6175782f06 |
def create_format_(self): <NEW_LINE> <INDENT> return self._graph.create_format_() | Create all sparse matrices allowed for the graph.
By default, we create sparse matrices for a graph only when necessary.
In some cases we may want to create them immediately (e.g. in a
multi-process data loader), which can be achieved via this API.
Examples
--------
The following example uses PyTorch backend.
>>> i... | 625941d2e8904600ed9f20e6 |
def apply(self): <NEW_LINE> <INDENT> r, r1, r2 = ['None', 'default', 'None'] <NEW_LINE> r = self.tree.current_fullpath() <NEW_LINE> r1 = self.config.itemData(self.config.currentIndex()) <NEW_LINE> if type(r1) == type(''): <NEW_LINE> <INDENT> r1 = str(r1) <NEW_LINE> <DEDENT> if self.w.isIO: <NEW_LINE> <INDENT> r2 = self... | Reads the comboboxes content and translated in a list to be sent to the server. | 625941d2a8370b7717052a57 |
def __init__(self, unicorn='gunicorn', unicorn_bin=None, gunicorn_bin=None, pidfile=None, boot_timeout=30, args=''): <NEW_LINE> <INDENT> self.unicorn_bin = unicorn_bin <NEW_LINE> self.gunicorn_bin = gunicorn_bin <NEW_LINE> if unicorn_bin: <NEW_LINE> <INDENT> self.unicorn = unicorn_bin <NEW_LINE> <DEDENT> elif gunicorn_... | Creates a new Herder instance.
unicorn - the type of unicorn to herd; either 'unicorn' or 'gunicorn'
(Default: gunicorn)
unicorn_bin - path of specific unicorn to run
(Default: None)
gunicorn_bin - path of specific gunicorn to run
(Default: None)
pidfile - path o... | 625941d2be7bc26dc91cd7b7 |
def test_labgroup_destroy(self): <NEW_LINE> <INDENT> response = self.client.delete(reverse(self.view_name, args=[self.labgroup_2.id])) <NEW_LINE> labgroups = LabGroup.objects.all() <NEW_LINE> self.assertTrue(self.labgroup_1 in labgroups) <NEW_LINE> self.assertTrue(self.labgroup_2 not in labgroups) <NEW_LINE> self.asser... | Tests that a labgroup is properly destroyed. | 625941d24d74a7450ccd437c |
def initializeTrees(self): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print("MCTree is initializing the tree with empty arrays") <NEW_LINE> <DEDENT> self.tree[-1] = [] <NEW_LINE> for Idx in xrange(len(self.gens)): <NEW_LINE> <INDENT> self.tree[Idx] = [] <NEW_LINE> self.treeElectron[Idx] = [] <NEW_LINE> se... | To initialize the tree safely, in case of a Gen Particle structure that references parents with larger Idx. | 625941d232920d7e50b2838a |
def _find_common_ancestor(self, edest, esrc): <NEW_LINE> <INDENT> assert edest.UUID.text == esrc.UUID.text, (edest.UUID.text, esrc.UUID.text) <NEW_LINE> cmp_lastmod = self._cmp_lastmod(edest, esrc) <NEW_LINE> if cmp_lastmod == 0: <NEW_LINE> <INDENT> return edest <NEW_LINE> <DEDENT> edesthist = getattr(edest, 'History',... | Find most recent common historical ancestor to two entries. | 625941d2bde94217f3682fa9 |
def table_exists(table_name, conn): <NEW_LINE> <INDENT> import re <NEW_LINE> cur = conn.cursor() <NEW_LINE> sql = "show tables;" <NEW_LINE> cur.execute(sql) <NEW_LINE> tables = [cur.fetchall()] <NEW_LINE> table_list = re.findall('(\'.*?\')', str(tables)) <NEW_LINE> table_list = [re.sub("'", '', each) for each in table_... | 判断表是否存在
:param table_name:
:param conn:
:return: | 625941d2e64d504609d749f8 |
def get_szr_class(annot, n_tpt): <NEW_LINE> <INDENT> szr_class = np.zeros(n_tpt, dtype='int8') <NEW_LINE> onset_text = ['szr onset', 'sz onset'] <NEW_LINE> offset_text = ['szr offset', 'sz offset'] <NEW_LINE> annot_text = list() <NEW_LINE> for a in annot: <NEW_LINE> <INDENT> temp = a['text'].lower() <NEW_LINE> annot_te... | Creats a numpy array that indicates for each time point if it is in a seizure or not according to annotations.
onset_text and offset_text lists below indicate the annotation strings used to mark seizure onset and offset.
Inputs:
annot: The dict of lay file annotations
n_tpt: The number of time points in the clip | 625941d2377c676e91272361 |
def delete_acl(self, sg): <NEW_LINE> <INDENT> if not self.sg_enabled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not sg: <NEW_LINE> <INDENT> msg = _('Invalid or Empty Security Group Specified') <NEW_LINE> raise arista_exc.AristaSecurityGroupError(msg=msg) <NEW_LINE> <DEDENT> direction = ['ingress', 'egress'] <NE... | Deletes an ACL from Arista Switch.
Deals with multiple configurations - such as multiple switches | 625941d2507cdc57c6306e95 |
def handle_bbox_msg(self, bbox_msg): <NEW_LINE> <INDENT> self.latest_detection_time = rospy.get_rostime() <NEW_LINE> print("Bboxes detected at", self.latest_detection_time.to_sec()) <NEW_LINE> self.detected_bboxes = bbox_msg | saves the latest bbox detections and latest detection time
| 625941d21f037a2d8b9463b6 |
def fit(self, Z, classes=None): <NEW_LINE> <INDENT> self._classes_ = np.unique(classes) <NEW_LINE> return self._spark_fit(SparkLinearSVC, Z) | Fit the model according to the given training data.
Parameters
----------
Z : TupleRDD or DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of available classes
Returns
-------
self : object
Returns self. | 625941d229b78933be1e5863 |
def find_by_fields(self, table, queryset={}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.start_con() <NEW_LINE> with self.con.cursor() as cursor: <NEW_LINE> <INDENT> querrys = "" <NEW_LINE> for k, v in queryset.items(): <NEW_LINE> <INDENT> querrys += "{} = '{}' and ".format(k, v) <NEW_LINE> <DEDENT> sql = "selec... | 从数据库里查询 符合多个条件的记录
Args:
table: 表名字 str
queryset : key 字段 value 值 dict
return:
成功: [dict] 保存的记录
失败: -1 | 625941d2ab23a570cc25033c |
def setUp2(self): <NEW_LINE> <INDENT> pass | Legacy method, use setUp in subclasses instead. | 625941d276d4e153a657ecea |
def get_camera(self, camera_id: str) -> Dict[str, str]: <NEW_LINE> <INDENT> for home_id in self.cameras: <NEW_LINE> <INDENT> if camera_id in self.cameras[home_id]: <NEW_LINE> <INDENT> return self.cameras[home_id][camera_id] <NEW_LINE> <DEDENT> <DEDENT> return {} | Get camera data. | 625941d25fcc89381b1e1879 |
def _decrypt_app_helper(self, app_id, decrypt_type): <NEW_LINE> <INDENT> @_requires_ios_binary(self, "clutch") <NEW_LINE> def _clutch_decrypt_app_helper(app_id, decrypt_type): <NEW_LINE> <INDENT> from socket import timeout <NEW_LINE> scrounger_clutch_log_file = "/tmp/scrounger-clutch.log" <NEW_LINE> try: <NEW_LINE> <IN... | Decrypts an app and returns the result output
:param str app_id: the id of the app to be decrypted
:param str decrypt_type: the type of decryption to be done - either
binary only (-b) or packed into ipa (-d)
:return: returns the output of the decryption | 625941d2d268445f265b5027 |
def decode(arg): <NEW_LINE> <INDENT> packet = arg.decode().split(" ") <NEW_LINE> packet = decode_dictionary[packet[0]](packet) <NEW_LINE> if packet is None: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> return packet | decode the argument into a packet
:param arg: a string representation of a packet
:return: a packet class of Type | 625941d23539df3088e2e504 |
def __init__(self, len_get_object): <NEW_LINE> <INDENT> self._len_get_object = len_get_object <NEW_LINE> self._index = -1 <NEW_LINE> self._max_index = len(self._len_get_object) - 1 | The class constructor | 625941d21b99ca400220ac6a |
def plot_edep_distribution(events, filename="edep_distribution.png"): <NEW_LINE> <INDENT> edep_511 = [] <NEW_LINE> edep_prompt =[] <NEW_LINE> for event in events: <NEW_LINE> <INDENT> edep_511.append(event[0].edep) <NEW_LINE> edep_511.append(event[1].edep) <NEW_LINE> edep_prompt.append(event[2].edep) <NEW_LINE> <DEDENT>... | Plots distribution of the energy deposited for annihilation and prompt gammas.
:param events: List of events.
:param filename: Name of the file with the plot.
:return: nothing | 625941d297e22403b379d153 |
def delete_image(self): <NEW_LINE> <INDENT> self.delete() | This method is used to delete an Image instance from the database by calling delete manager. | 625941d2fb3f5b602dac384d |
def Uninitialize( self, Channel): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = self.__m_dllBasic.CAN_Uninitialize(Channel) <NEW_LINE> return TPCANStatus(res) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print ("Exception on PCANBasic.Uninitialize") <NEW_LINE> raise | Uninitializes one or all PCAN Channels initialized by CAN_Initialize
Remarks:
Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Returns:
A TPCANStatus error code | 625941d2aad79263cf390bfb |
def regrid(f=None, x=None, y=None, xnew=None, ynew=None): <NEW_LINE> <INDENT> regrid_f = deepcopy(f) <NEW_LINE> regrid_x = deepcopy(x) <NEW_LINE> regrid_y = deepcopy(y) <NEW_LINE> fieldout = [] <NEW_LINE> if regrid_x[0] > regrid_x[-1]: <NEW_LINE> <INDENT> regrid_x = regrid_x[::-1] <NEW_LINE> regrid_f = np.fliplr(regrid... | | regrid - bilinear interpolation of a grid to new grid locations
|
|
| f=None - original field
| x=None - original field x values
| y=None - original field y values
| xnew=None - new x points
| ynew=None - new y points
|
:Returns:
field values at requested locations
|
| | 625941d25510c4643540f59b |
def slice_strip(MAT, width, ppm): <NEW_LINE> <INDENT> NotImplemented | NotImplemented | 625941d2507cdc57c6306e96 |
def fit(self, x: Union[np.ndarray, pd.DataFrame], y: Union[np.ndarray, pd.DataFrame], debug: bool=False) -> None: <NEW_LINE> <INDENT> max_its = self.params['max_its'] <NEW_LINE> learning_rate = self.params['learning_rate'] <NEW_LINE> conv_thresh = self.params['conv_thresh'] <NEW_LINE> conv_steps = self.params['conv_ste... | Fit model.
:param x: Features.
:param y: Labels.
:param debug: If true, print information on each iteration. | 625941d20a50d4780f66704c |
def _gl_alg(window_size, hop, fft_size=4096): <NEW_LINE> <INDENT> syn_w = signal.hamming(window_size) / np.sqrt(fft_size) <NEW_LINE> syn_w_prod = syn_w ** 2. <NEW_LINE> syn_w_prod.shape = (window_size, 1) <NEW_LINE> redundancy = int(window_size / hop) <NEW_LINE> env = np.zeros((window_size, 1)) <NEW_LINE> for k in rang... | LSEE-MSTFT algorithm for computing the synthesis window.
According to: Daniel W. Griffin and Jae S. Lim, `Signal estimation from modified short-time Fourier transform,` IEEE Transactions on Acoustics, Speech and Signal Processing, vol. 32, no. 2, pp. 236-243, Apr 1984.
:param window_size: Synthesis window si... | 625941d201c39578d7e74ff4 |
def healpix_header_odict(nside,nest=False,ordering='RING',coord=None, partial=True): <NEW_LINE> <INDENT> hdr = odict([]) <NEW_LINE> hdr['PIXTYPE']=odict([('name','PIXTYPE'), ('value','HEALPIX'), ('comment','HEALPIX pixelisation')]) <NEW_LINE> ordering = 'NEST' if nest else 'RING' <NEW_LINE> hdr['ORDERING']=odict([('nam... | Mimic the healpy header keywords. | 625941d2167d2b6e31218d4f |
def hyperparameters(self): <NEW_LINE> <INDENT> self.param_optimizer = list(self.model.named_parameters()) <NEW_LINE> no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] <NEW_LINE> optimizer_parameters = [ {"params": [p for n, p in self.param_optimizer if not any(nd in n for nd in no_decay)], "weight_decay": 0.001... | This method fix the parameters and makes a filter over to exclude LayerNorm and biases | 625941d2099cdd3c635f0e14 |
def input_pin(self, address, pin): <NEW_LINE> <INDENT> if len(pin) > self.MAX_PIN_LENGTH or len(pin) < self.MIN_PIN_LENGTH: <NEW_LINE> <INDENT> raise Exception("Pin code must be within range") <NEW_LINE> <DEDENT> logging.info("Cert: Waiting for PIN request") <NEW_LINE> assertThat(self._hci_event_stream).emits(HciMatche... | Pretend to answer the pairing dialog as a user | 625941d2a8ecb033257d3286 |
def build_keyboard(self, rlist): <NEW_LINE> <INDENT> self.keyboard = [] <NEW_LINE> for r in rlist: <NEW_LINE> <INDENT> self.keyboard.append([InlineKeyboardButton(r, callback_data=rlist[r])]) <NEW_LINE> <DEDENT> reply_markup = InlineKeyboardMarkup(self.keyboard) <NEW_LINE> return reply_markup | this builds a keyboard telegram object
from a list passed to args | 625941d28c3a873295158575 |
def filterByCompilability(indexList): <NEW_LINE> <INDENT> return filter(lambda index: index[4] == 1, indexList) | returns an index list with only indices of compilable files | 625941d25e10d32532c5f0e0 |
def shortestPath(self, grid: List[List[int]], k: int) -> int: <NEW_LINE> <INDENT> pass | put solution here | 625941d296565a6dacc8f884 |
def get_short_interest(self, symbols, lang=None): <NEW_LINE> <INDENT> params = MultipleQuoteParams() <NEW_LINE> params.symbols = symbols <NEW_LINE> params.lang = get_enum_value(lang) if lang else get_enum_value(self._lang) <NEW_LINE> request = OpenApiRequest(QUOTE_SHORTABLE_STOCKS, biz_model=params) <NEW_LINE> response... | 获取美股的做空数据
:param symbols: 股票代号列表
:param lang: 语言支持: zh_CN,zh_TW,en_US
:return: pandas.DataFrame 对象,各 column 含义如下:
symbol: 证券代码
settlement_date: 收集信息的时间
short_interest: 未平仓做空股数
avg_daily_volume: 过去一年的日均成交量
days_to_cover: 回补天数。使用最近一次获取的未平仓做空股数/日均成交量得到
percent_of_float: 未平仓股数占流通股本的比重 | 625941d2b5575c28eb68e1ba |
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): <NEW_LINE> <INDENT> self.proxy = (proxytype, addr.encode(), port, rdns, username.encode() if username else None, password.encode() if password else None) | setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (I... | 625941d2711fe17d82542523 |
def __init__(self, config: TorchDistributedConfig, app_id: int, run_id: int): <NEW_LINE> <INDENT> super().__init__(config, app_id, run_id) <NEW_LINE> self.server = DistributedTrainingServer(self.num_executors) <NEW_LINE> self.results = [] | Initializes the server for initial training setup communication and log collection.
:param config: Experiment config.
:param app_id: Maggy application ID.
:param run_id: Maggy run ID. | 625941d2091ae35668667116 |
def filter_2D_conv(img, kernel_size): <NEW_LINE> <INDENT> coeff = kernel_size * kernel_size <NEW_LINE> kernel = np.ones((kernel_size, kernel_size), np.float32) / coeff <NEW_LINE> return cv2.filter2D(img, -1, kernel) | Convolve a kernel with an image. We apply an averaging filter on an image.
:param img: image to be convolved.
:param kernel_size: size of our convolution filter
:return: convolved image | 625941d238b623060ff0afa7 |
def view(args): <NEW_LINE> <INDENT> print(_dump(_load(_config_file()))) | Prints out the config file. | 625941d24527f215b584c60f |
def make_build(self): <NEW_LINE> <INDENT> build_graph = BuildGraph( self.rule_dependency_graph, dependency_registery=self.dependency_registery, config=self.config) <NEW_LINE> return build_graph | Constructs a new build graph by adding the jobs and following the
build_context's rules | 625941d21f5feb6acb0c4d08 |
def change_color(self): <NEW_LINE> <INDENT> self.color = self.color_map[self.color] <NEW_LINE> self.image.fill(COLORS[self.color]) <NEW_LINE> if self.visited: <NEW_LINE> <INDENT> self.add_visited() <NEW_LINE> <DEDENT> if self.coordinates: <NEW_LINE> <INDENT> self.add_coordinates() | Changes the color of the Square to the next color according to self.color_map.
Additionally, adds an X in the square if self.visited is True. | 625941d2d18da76e23532691 |
def finishUnserialization(self, *args): <NEW_LINE> <INDENT> return _MEDCouplingCorba.MEDCouplingConstOnTimeInterval_finishUnserialization(self, *args) | finishUnserialization(self, ivec tinyInfoI, dvec tinyInfoD, svec tinyInfoS)
1 | 625941d28da39b475bd6512e |
def check_for_battle(self): <NEW_LINE> <INDENT> if self.switch_to_battle and self.allow_battles and not self.done: <NEW_LINE> <INDENT> self.player.location = self.player.get_tile_location() <NEW_LINE> self.update_game_data() <NEW_LINE> self.next = 'battle' <NEW_LINE> self.done = True | Check if the flag has been made true, indicating
to switch state to a battle. | 625941d2bf627c535bc13388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.