code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def close_all(self): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> child.close_all() <NEW_LINE> <DEDENT> self.close()
Recursively close everything.
625941f0ad47b63b2c50a51b
def to_internal_value(self, value): <NEW_LINE> <INDENT> converted = datetime.fromtimestamp(float('%s' % value)) <NEW_LINE> return super(DateTimeFieldWihTZ, self).to_representation(converted)
deserialize a timestamp to a DateTime value :param value: the timestamp value :return: a django DateTime value
625941f0566aa707497f4afc
def process_log_file(cur, filepath): <NEW_LINE> <INDENT> df = pd.read_json(filepath, lines = True) <NEW_LINE> df = df.loc[df['page'] == 'NextSong'] <NEW_LINE> df['ts'] = df['ts'].astype(int) <NEW_LINE> df['datetime'] = pd.to_datetime(df['ts'], unit='ms') <NEW_LINE> t = df[['datetime', 'ts']].copy() <NEW_LINE> t['year']...
Processes the .json log file. Args: param1 (cur): Cursor param2 (filepath): Filepath to the json files eg 'data/log_data' Returns: Count of rows processed
625941f02eb69b55b151ce53
def new_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/netflow/monitor/{monitor_name}/disable-log-by-destination/ip/{ipv4-addr}" <NEW_LINE> f_dict = {} <NEW_LINE> f_dict["ipv4-addr"] = "" <NEW_LINE> f_dict["monitor_name"] = module.params["monitor_name"] <NEW_LINE> return url_base.format(**f_dict)
Return the URL for creating a resource
625941f056b00c62f0f14bf8
def tabulate_results(self): <NEW_LINE> <INDENT> self._add_server_data() <NEW_LINE> for result_heap in self._per_model_sorted_results.values(): <NEW_LINE> <INDENT> while not result_heap.empty(): <NEW_LINE> <INDENT> self._tabulate_measurements(result_heap.next_best_result())
The function called at the end of all runs FOR ALL MODELs that compiles all results and dumps the data into tables for exporting.
625941f063d6d428bbe44a8c
def test_queue_task(self): <NEW_LINE> <INDENT> scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT) <NEW_LINE> scan_job.save() <NEW_LINE> scan_job.sources.add(self.source) <NEW_LINE> self.assertEqual(scan_job.status, ScanTask.CREATED) <NEW_LINE> tasks = scan_job.tasks.all() <NEW_LINE> self.assertEqual(len(tasks), 0...
Test create queue state change.
625941f091f36d47f21aca94
def fightMenu (): <NEW_LINE> <INDENT> print ("Select what you would like to do") <NEW_LINE> print ("1. Shoot") <NEW_LINE> print ("2. View Health") <NEW_LINE> print ("3. View enemy Health") <NEW_LINE> print ("4. Run Away") <NEW_LINE> print ("5. Heal")
a function that displays your options while in a fight
625941f0f9cc0f698b140b91
def _hdfs_exists(hdfs_client, b_path): <NEW_LINE> <INDENT> return hdfs_client.exists(b_path)
Determine if a HDFS path exists
625941f085dfad0860c3b3f8
def smooth_weighted_MA_matrix(Y, window_len=11, window='hanning', args=[]): <NEW_LINE> <INDENT> Ys = np.zeros(Y.shape) <NEW_LINE> for i in range(Y.shape[1]): <NEW_LINE> <INDENT> Ys[:, i] = smooth_weighted_MA(Y[:, i], window_len, window, args) <NEW_LINE> <DEDENT> return Ys
Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal...
625941f0aad79263cf390fe5
def subsets(self, nums): <NEW_LINE> <INDENT> if nums: <NEW_LINE> <INDENT> nums1 = nums[:-1] <NEW_LINE> res = self.subsets(nums1) <NEW_LINE> res1 = [e[:] for e in res] <NEW_LINE> for e in res1: <NEW_LINE> <INDENT> e.append(nums[-1]) <NEW_LINE> <DEDENT> res += res1 <NEW_LINE> return res <NEW_LINE> <DEDENT> else: <NEW_LIN...
:type nums: List[int] :rtype: List[List[int]]
625941f050812a4eaa59c8b6
def init_session(self, session_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> uid = self.firebase.get_user_uid_from_session(session_id) <NEW_LINE> self.session["firebase_session_id"] = session_id <NEW_LINE> self.session["firebase_uid"] = uid <NEW_LINE> db_user = self.get_user_by_uid(uid, reimport=True) <NEW_LINE> if...
Authentication helper to retrieve the firebase user info from firebase session id
625941f050485f2cf553d337
def parse_apply_to_field(self, value, request, **kwargs): <NEW_LINE> <INDENT> value = value.lower() <NEW_LINE> if value == 'all': <NEW_LINE> <INDENT> return WebHookTarget.APPLY_TO_ALL <NEW_LINE> <DEDENT> elif value == 'custom': <NEW_LINE> <INDENT> return WebHookTarget.APPLY_TO_SELECTED_REPOS <NEW_LINE> <DEDENT> elif va...
Parse the apply_to field from a human-readable value. Args: value (unicode): The value to parse. request (django.http.HttpRequest): The HTTP request. **kwargs (dict): Additional keyword arguments. Returns: unicode: A value that the ``WebHookTarget`` model expects for its ...
625941f08e7ae83300e4b56a
def rad(n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return reduce((lambda x, y: x * y), set(prime_factors(n)))
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 2^3 × 3^2 × 7, so rad(504) = 2 × 3 × 7 = 42.
625941f023849d37ff7b3626
def configure(self, arguments): <NEW_LINE> <INDENT> self._informat = arguments.deltaf_from <NEW_LINE> self._inchannels = CHANNELS[self._informat]
Configure algorithm using comand line arguments. Parameters ---------- arguments: Namespace parsed command line arguments
625941f0925a0f43d254a418
def cursor_contains(cursor, loc): <NEW_LINE> <INDENT> start = cursor.extent.start <NEW_LINE> end = cursor.extent.end <NEW_LINE> if start.file is None and loc.file is not None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if start.file is not None and loc.file is None: <NEW_LINE> <INDENT> return False <NEW_LINE>...
Return whether the cursor extends around the location.
625941f0d58c6744b42581f9
def FixupAsmjs(filename): <NEW_LINE> <INDENT> with open(filename, "r") as infile: <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile(delete=False) as tmpfile: <NEW_LINE> <INDENT> tmpfilename = tmpfile.name <NEW_LINE> for line in infile: <NEW_LINE> <INDENT> if (False and re.search("if \(Module\['postRun'\]\)", line)):...
Applies various fixups as necessary to an Asm.js file, including: 1. Initialize argv from the URL, e.g. http://host/asmjs.html?arg1&arg2&arg3 2. (currently disabled) Try to close the tab/window when main() completes to facilitate scripting.
625941f0090684286d50f28b
def setup_physical_bridges(self, bridge_mappings): <NEW_LINE> <INDENT> self.phys_brs = {} <NEW_LINE> self.int_ofports = {} <NEW_LINE> self.phys_ofports = {} <NEW_LINE> if self.hybrid_mode: <NEW_LINE> <INDENT> super(GBPOvsAgent, self).setup_physical_bridges(bridge_mappings)
Override parent setup physical bridges. Only needs to be executed in hybrid mode. If not in hybrid mode, only the existence of the integration bridge is assumed.
625941f0a17c0f6771cbe5ea
def __getitem__(self, cmd): <NEW_LINE> <INDENT> def caller(args, kwargs): <NEW_LINE> <INDENT> arg_str = '{0} '.format(cmd) <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> arg_str += '{0} '.format(arg) <NEW_LINE> <DEDENT> for key, val in kwargs.items(): <NEW_LINE> <INDENT> arg_str += '{0}={1} '.format(key, val) <NEW_LIN...
Return the function call to simulate the salt local lookup system
625941f094891a1f4081c047
def predictions(dataframe): <NEW_LINE> <INDENT> features = dataframe[['rain', 'Hour', 'meantempi','minpressurei','meanwindspdi']] <NEW_LINE> dummy_units = pandas.get_dummies(dataframe['UNIT'], prefix='unit') <NEW_LINE> features = features.join(dummy_units) <NEW_LINE> values = dataframe['ENTRIESn_hourly'] <NEW_LINE> m =...
The NYC turnstile data is stored in a pandas dataframe called weather_turnstile. Using the information stored in the dataframe, let's predict the ridership of the NYC subway using linear regression with gradient descent. You can download the complete turnstile weather dataframe here: https://www.dropbox.com/s/meyki2wl...
625941f092d797404e304728
def test_install_hook_raises_unknown_hook(self): <NEW_LINE> <INDENT> hooks = Hooks() <NEW_LINE> self.assertRaises(UnknownHook, self.applyDeprecated, one_five, hooks.install_hook, 'silly', None)
install_hook should raise UnknownHook if a hook is unknown.
625941f0a8ecb033257d3666
def log(user, union_uid, union_name, cur_num, union_level): <NEW_LINE> <INDENT> action = game_define.EVENT_ACTION_UNION_EXIT <NEW_LINE> log_lst = action_base.log_base(user) <NEW_LINE> log_lst.append(str(action)) <NEW_LINE> log_lst.append(str(union_uid)) <NEW_LINE> log_lst.append(str(union_name)) <NEW_LINE> log_lst.appe...
输出日志
625941f0442bda511e8be9ab
def add_gaussian_noise(self, std): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> if self._lazy: <NEW_LINE> <INDENT> from dask.array.random import normal <NEW_LINE> kwargs["chunks"] = self.data.chunks <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from numpy.random import normal <NEW_LINE> <DEDENT> noise = normal(loc=0, sca...
Add Gaussian noise to the data. The operation is performed in-place i.e. the data of the signal is modified. This method requires a float data type, otherwise numpy raises a ``TypeError``. Parameters ---------- std : float The standard deviation of the gaussian noise. Note: ----- This method uses ``numpy.rando...
625941f0d164cc61757832eb
def test_filter_text_arg_str_escape(): <NEW_LINE> <INDENT> def _get_drawtext_text_repr(text): <NEW_LINE> <INDENT> args = (ffmpeg .input('in') .drawtext('a{}b'.format(text)) .output('out') .get_args() ) <NEW_LINE> assert args[:3] == ['-i', 'in', '-filter_complex'] <NEW_LINE> assert args[4:] == ['-map', '[s0]', 'out'] <N...
Test string escaping of normal filter args (e.g. ``text`` param of ``drawtext`` filter).
625941f0de87d2750b860334
def get( self, resource_group_name, name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}' <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_gro...
Gets a Redis cache (resource description). :param resource_group_name: The name of the resource group. :type resource_group_name: str :param name: The name of the Redis cache. :type name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside th...
625941f015fb5d323cde10b4
def create_table(self): <NEW_LINE> <INDENT> os.mkdir(self.__destination) <NEW_LINE> self.__table = wt.Table(self.__destination) <NEW_LINE> self.__table.read_schema(self.__schema) <NEW_LINE> self.__table.set_db_cache_size(self.__db_cache_size) <NEW_LINE> self.__table.open("w") <NEW_LINE> self.__column_map = {} <NEW_LINE...
Creates the table and reads the column information for the VCF reader.
625941f03d592f4c4ed1d5f9
def getBibliography(self, keys=None, fmt="plaintext", style="unsrtalpha", enc=None, objects=False): <NEW_LINE> <INDENT> if self.library is None: <NEW_LINE> <INDENT> raise ValueError("No library has been loaded, yet.") <NEW_LINE> <DEDENT> style_cls = pybtex.plugin.find_plugin('pybtex.style.formatting', style) <NEW_LINE>...
This function creates a formatted bibliography according to the defined parameters using Pybtex. Specify your desired output format using the "fmt" parameter. Supported formats are defined by Pybtex and the parameter is only passed on to the plugin search function: latex, html, plaintext and markdown. The "style" param...
625941f0236d856c2ad44d7e
def test03(self): <NEW_LINE> <INDENT> self._test('1966-04-10', '1966.04.10') <NEW_LINE> self._test('1971-07-01', '1971.7.1') <NEW_LINE> self._test('1966-04-10', '10.04.1966') <NEW_LINE> self._test('1971-07-01', '1.7.1971') <NEW_LINE> self._test('1966-04-10', '10.04.66') <NEW_LINE> self._test('1971-07-01', '1.7.71')
Tests with a dot as separator.
625941f0004d5f362079a8ca
def _read_applications(self): <NEW_LINE> <INDENT> query = self.base.sack.query() <NEW_LINE> packages = query.available() <NEW_LINE> _names = [] <NEW_LINE> for pkg in packages: <NEW_LINE> <INDENT> if pkg.name in _names: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self._is_app(pkg): <NEW_LINE> <INDENT> self._add_...
Update the list of available applications
625941f015baa723493c4516
def test_update_task(self): <NEW_LINE> <INDENT> def single_run(a_id, a_args): <NEW_LINE> <INDENT> models.update_job_status_task(a_id, a_args) <NEW_LINE> return Job.objects.get(pk=job.id) <NEW_LINE> <DEDENT> def last_update_of(a_job): <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> return a_job.updated <NEW_LINE> <DEDEN...
Test local in-process execution.
625941f0be7bc26dc91cdb90
def __str__(self): <NEW_LINE> <INDENT> str_fmt = ('Date: {}\n' 'Task Name: {}\n' 'First Name: {}\n' 'Last Name: {}\n' 'Time Spent: {}\n' 'Notes: {}') <NEW_LINE> return str_fmt.format(self.date, self.task_name, self.first_name, self.last_name, self.time_elapsed, self.notes)
Prints out readable task request
625941f060cbc95b062c6adf
@click.group(cls=DefaultGroup, default='shipyard_default') <NEW_LINE> @click.option( '--context-marker', 'context_marker', help='Specifies a UUID (8-4-4-4-12 format) that will be used to correlate' ' logs, transactions, etc. in downstream activities triggered by this' ' interaction. If not specified, Shipyard will supp...
COMMAND: shipyard DESCRIPTION: The base shipyard command supports options that determine cross-CLI behaviors. These options are positioned immediately following the shipyard command. FORMAT: shipyard [--context-marker=<uuid>] [--os_{various}=<value>] [--debug/--no-debug] [--output-format=<json,yaml,raw] [--verbosit...
625941f04e696a04525c99e9
def minus(y, x): <NEW_LINE> <INDENT> return x-y
Return the subtraction of two numbers.
625941f024f1403a926010fd
def open(self, name, mode='r'): <NEW_LINE> <INDENT> if mode not in ('r', 'w'): <NEW_LINE> <INDENT> raise ValueError("open() requires mode 'r' or 'w'") <NEW_LINE> <DEDENT> if not self.fp: <NEW_LINE> <INDENT> raise RuntimeError('Attempt to read archive that was already closed') <NEW_LINE> <DEDENT> if isinstance(name, sel...
Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or an ArchiveInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. open() is also a context manager and supports the with statement:: with ArchiveFile('archive.file') as ...
625941f0d18da76e23532a79
def test_exit_no_tag_in_branch_name(cli_runner, mock_commit_msg_file, monkeypatch): <NEW_LINE> <INDENT> class MockBranch: <NEW_LINE> <INDENT> name = "no-tag-in-branch-name" <NEW_LINE> <DEDENT> monkeypatch.setattr(Repo, "active_branch", MockBranch()) <NEW_LINE> mock_commit_msg_file.write_text("DUMMY") <NEW_LINE> result ...
Assert exit code 0 if no tag found in branch name.
625941f02ae34c7f2600d6cc
def on_click(self): <NEW_LINE> <INDENT> pass
The button has been clicked.
625941f0e5267d203edce231
def part_string(part, i): <NEW_LINE> <INDENT> if part == 'dev': <NEW_LINE> <INDENT> timestamp = get_git_changeset() <NEW_LINE> if timestamp: <NEW_LINE> <INDENT> s = 'dev%s' % timestamp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = 'dev' <NEW_LINE> <DEDENT> if i > 0: <NEW_LINE> <INDENT> s = '.' + s <NEW_LINE> <DEDEN...
Convert a version number part into a string for concatentation. Makes the following transformations: * Any number into a string: 1 -> '1' * Any tuple into flat concatenated string: ('a', 2) -> 'a2' * The string 'dev' in to a dvelopment version number: dev'-> dev20130412121314 Also ...
625941f06fece00bbac2dce1
def test_method(self): <NEW_LINE> <INDENT> for meth in [SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]: <NEW_LINE> <INDENT> Context(meth) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> Context(SSLv2_METHOD) <NEW_LINE> <DEDENT> except (Error, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.assertRaises(TypeErro...
:py:obj:`Context` can be instantiated with one of :py:obj:`SSLv2_METHOD`, :py:obj:`SSLv3_METHOD`, :py:obj:`SSLv23_METHOD`, or :py:obj:`TLSv1_METHOD`.
625941f0d99f1b3c44c67b20
def cosine_distance(memory_matrix, cos_keys): <NEW_LINE> <INDENT> memory_norm = torch.norm(memory_matrix, 2, 2) <NEW_LINE> keys_norm = torch.norm(cos_keys, 2, 1) <NEW_LINE> normalized_mem = torch.div(memory_matrix, memory_norm.expand_as(memory_matrix) + 1e-8) <NEW_LINE> normalized_keys = torch.div(cos_keys, keys_norm.e...
compute the cosine similarity between keys to each of the memory slot. Parameters: ---------- memory_matrix: Tensor (batch_size, mem_slot, mem_size) the memory matrix to lookup in keys: Tensor (batch_size, mem_size, number_of_keys) the keys to query the memory with strengths: Tensor (batch_size, number_of_key...
625941f04f6381625f114fd7
def _parse_duration(self, line, meta): <NEW_LINE> <INDENT> m = re.match('Duration: ([^,]*),.*bitrate: (\\d*).*', line) <NEW_LINE> if not m: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> duration = m.group(1) <NEW_LINE> bitrate = m.group(2) <NEW_LINE> if re.match('\\d{2}:\\d{2}:\\d{2}.\\d{1,2}', duration): <NEW_LI...
>>> p = FFmpegOutputParser() >>> meta = Dict() not matched: >>> m = p._parse_duration('', meta) >>> hasattr(meta, 'duration') False >>> hasattr(meta, 'bitrate') False normal situation: >>> p._parse_duration('Duration: 01:30:15.66, start: 3.000000, bitrate: 99 kb/s', meta) >>> meta.duration 5415660 >>> meta.kbps 99 n...
625941f04527f215b584c9ed
def test_sendmoremoney(self): <NEW_LINE> <INDENT> letters = "S E N D M O R Y".split() <NEW_LINE> prolog = Prolog() <NEW_LINE> sendmore = Functor("sendmore") <NEW_LINE> prolog.consult(example_path("sendmoremoney/money.pl")) <NEW_LINE> X = Variable() <NEW_LINE> call(sendmore(X)) <NEW_LINE> r = X.value <NEW_LINE> val = {}...
Runs the sendmoremoney example:: S E N D M O R E + ------- M O N E Y So, what should be the values of S, E, N, D, M, O, R, Y if they are all distinct digits.
625941f0dc8b845886cb5ad3
def get_satellite_fact_sheet(name): <NEW_LINE> <INDENT> from operator import methodcaller <NEW_LINE> return SatelliteFactSheet( *map(methodcaller('get', name), SatellitesData.__dict__.itervalues()) )
input a string name of a satellite, and get its SatelliteFactSheet
625941f0462c4b4f79d1dc6b
def onHit(**bvalues): <NEW_LINE> <INDENT> pass
function (source) { if (!source.volatiles['dynamax']) return; for (var _i = 0, _a = source.foes(); _i < _a.length; _i++) { var pokemon = _a[_i]; this.boost({ spa: -1 }, pokemon); } }
625941f0097d151d1a2233f2
def subprocess_get(cmd, shell: bool = True, input=None): <NEW_LINE> <INDENT> data, _ = subprocess_sp(cmd, shell=shell, input=input) <NEW_LINE> return data
A simple subprocess call with no return code capturing. :param cmd: The command to execute. :param shell: Whether to use a shell or not for the execution of the command. :param input: If there is any input needed for that command to stdin. :return: The data which the subprocess returns.
625941f063d6d428bbe44a8d
def fully_connected(x, num_output_units, activation_fn=None, weight_init=initializers.xavier_initializer(), bias_init=standard_ops.constant_initializer(0.), name=None, weight_collections=(ops.GraphKeys.WEIGHTS,), bias_collections=(ops.GraphKeys.BIASES,), output_collections=(ops.GraphKeys.ACTIVATIONS,), weight_regulariz...
Adds the parameters for a fully connected layer and returns the output. A fully connected layer is generally defined as a matrix multiply: `y = f(w * x + b)` where `f` is given by `activation_fn`. If `activation_fn` is `None`, the result of `y = w * x + b` is returned. This op creates `w` and optionally `b`. Bias (`b...
625941f0a4f1c619b28b05c7
def vecNDtoint(self, state): <NEW_LINE> <INDENT> assert isinstance(state, np.ndarray) <NEW_LINE> idx = 0 <NEW_LINE> state_j = 0 <NEW_LINE> for j in range(0,dims-1): <NEW_LINE> <INDENT> state_j = self.bound_value(state[j],self.state_mins[j],self.state_maxs[j]) <NEW_LINE> idx = idx + np.prod(self._N[j+1:]) * round( (s...
Converts a continuous state vector to a discrete state integer Args: state (numpy.ndarray) : Current state of the environment. numpy.ndarray((dims,)) Returns: (int) : Discretised state index. Comments:
625941f0cc0a2c11143dd42d
def test_evaluate_value_with_nested_variables(): <NEW_LINE> <INDENT> obj = { 'variables': { 'var2': { 'value': '{{ var2 }}-modified' } }, 'str-key': '{{ var1 }}', 'int-key': 2, 'nested-key': { 'nested-key1': { 'value': '{{ var1 }}', 'template': True }, 'variables': { 'var1': { 'value': '{{ var1 }}-modified' } }, 'neste...
Should evaluate value by parsing templates. :return:
625941f066673b3332b9262d
def check_file(name, folder=False): <NEW_LINE> <INDENT> if folder: <NEW_LINE> <INDENT> return os.path.isdir(name) <NEW_LINE> <DEDENT> return os.path.isfile(name)
Check if file exist Args: name: folder: :returns bool if existing
625941f031939e2706e4d3fe
def get_layer_mean(data, depth, mesh, timeslice=None): <NEW_LINE> <INDENT> ind_depth, ind_noempty, ind_empty = ind_for_depth(depth, mesh) <NEW_LINE> data_mean=np.zeros(shape=(mesh.n2d)) <NEW_LINE> if timeslice is None: <NEW_LINE> <INDENT> data_mean[ind_noempty]=data[:,ind_depth[ind_noempty]].mean(axis=0) <NEW_LINE> <DE...
Return mean over the model depth that is closest to specified depth.
625941f0bde94217f3683388
def read_line(self): <NEW_LINE> <INDENT> self.comm.readline()
Blocks until newline is received.
625941f04e696a04525c99ea
def clear(self): <NEW_LINE> <INDENT> return _fife.UintVector_clear(self)
clear(UintVector self)
625941f007d97122c4178e35
def create_snap_packaging( config_data: Dict[str, Any], parts_config: project_loader.PartsConfig, project_options: Project, snapcraft_yaml_path: str, original_snapcraft_yaml: Dict[str, Any], snapcraft_schema: Dict[str, Any]) -> str: <NEW_LINE> <INDENT> _update_yaml_with_extracted_metadata(config_data, parts_config) <NE...
Create snap.yaml and related assets in meta. Create the meta directory and provision it with snap.yaml in the snap dir using information from config_data. Also copy in the local 'snap' directory, and generate wrappers for hooks coming from parts. :param dict config_data: project values defined in snapcraft.yaml. :ret...
625941f05fdd1c0f98dc07d2
def getNonInstallableProfiles(self): <NEW_LINE> <INDENT> return [ 'sinar.foi:uninstall', ]
Hide uninstall profile from site-creation and quickinstaller.
625941f0442bda511e8be9ac
def issue_delete_issue_reaction(self, owner, repo, index, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.issue_delete_issue_reaction_with_http_info(owner, repo, index, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (...
Remove a reaction from an issue # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.issue_delete_issue_reaction(owner, repo, index, async_req=True) >>> result = thread.get() :param async_req bool :param str owner: own...
625941f0fff4ab517eb2f9dc
def isMediaFile(filename): <NEW_LINE> <INDENT> if re.search(r'(^|[\W_])(?<!shomin.)(sample\d*)[\W_]', filename, re.I): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if re.search(r'^RARBG\.\w+\.(mp4|avi|txt)$', filename, re.I): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if filename.startswith('._'): <NE...
Check if named file may contain media :param filename: Filename to check :return: True if this is a known media file, False if not
625941f0f548e778e58cdb1c
@pytest.mark.parametrize('file', ('-', ('/dev/null', '-'), ('-', '/dev/null'))) <NEW_LINE> def test_early_script_file(file): <NEW_LINE> <INDENT> proc = Spidermonkey(early_script_file=file) <NEW_LINE> stdout, stderr = proc.communicate('print("World")') <NEW_LINE> assert (stdout, stderr) == ('World\n', '') <NEW_LINE> ass...
Test that an early script file is executed as expected.
625941f06fece00bbac2dce2
def custom_abort_pecan(errors): <NEW_LINE> <INDENT> details = dict(errors=[{'message': str(getattr(error, "message", error))} for error in errors]) <NEW_LINE> abort(400, detail=details, headers={'Content-Type': "application/json"})
Error_handler for with_schema Meant to be used with pecan transport. param errors: a list of validation exceptions
625941f030bbd722463cc366
def __new__(mcs, name, bases, attrs): <NEW_LINE> <INDENT> model = super().__new__(mcs, name, bases, attrs) <NEW_LINE> if model.__name__ != 'UserRoleAssignment' and 'UserRoleAssignment' in [b.__name__ for b in bases]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model._meta.get_field('role') <NEW_LINE> <DEDENT> except F...
Override to dynamically create foreign key for objects begotten from abstract class.
625941f0e8904600ed9f24d3
def update(self, cut_handle): <NEW_LINE> <INDENT> scale = 10.**cut_handle.precision <NEW_LINE> self.lower = math.floor(cut_handle.minimum.value * scale) <NEW_LINE> self.upper = math.ceil(cut_handle.maximum.value * scale) <NEW_LINE> self.enabled = True
Updates limits and enables cut.
625941f0cc40096d61595eea
def test_update_several_custom_fields(): <NEW_LINE> <INDENT> jp = JiraProxy(GOOD_VANILLA_ONDEMAND_CONFIG) <NEW_LINE> work_item = {"Summary" : "potash deposit extraction shifting towards foreign suppliers", "Assignee" : JIRA_DEV_USER, "Priority" : "Lowest", "Severity" : "Cosmetic", "RallyID" : 123453532, "Sup...
create a JIRA issue and update several custom fields
625941f08c0ade5d55d3ef5c
def reinit(self, env='default', **kwargs): <NEW_LINE> <INDENT> self.vis = visdom.Visdom(env=env, **kwargs) <NEW_LINE> return self
修改visdom的配置 :param env: :param kwargs: :return:
625941f0a8ecb033257d3667
def delete_nodes(label_selector: str = None, all: bool = False, rand: bool = False, count: int = None, grace_period_seconds: int = None, secrets: Secrets = None): <NEW_LINE> <INDENT> api = create_k8s_api_client(secrets) <NEW_LINE> v1 = client.CoreV1Api(api) <NEW_LINE> if label_selector: <NEW_LINE> <INDENT> ret = v1.lis...
Delete nodes gracefully. Select the appropriate nodes by label. Nodes are not drained beforehand so we can see how cluster behaves. Nodes cannot be restarted, they are really deleted. Please be careful when using this action. On certain cloud providers, you also need to delete the underneath VM instance as well after...
625941f0956e5f7376d71408
def quicksort(l): <NEW_LINE> <INDENT> if len(l) <= 1: <NEW_LINE> <INDENT> return l <NEW_LINE> <DEDENT> pivot = l[0] <NEW_LINE> less = [] <NEW_LINE> equal = [] <NEW_LINE> greater = [] <NEW_LINE> for e in l: <NEW_LINE> <INDENT> if e < pivot: <NEW_LINE> <INDENT> less.append(e) <NEW_LINE> <DEDENT> elif e == pivot: <NEW_LIN...
Sort list using quick sort. Complexity: O(n log n). Worst: O(n2) @param l list to sort. @returns sorted list.
625941f0e76e3b2f99f3ad9e
def get_site_offers(self): <NEW_LINE> <INDENT> date_based_offers = ConditionalOffer.active.filter( offer_type=ConditionalOffer.SITE) <NEW_LINE> nondate_based_offers = ConditionalOffer.objects.filter( offer_type=ConditionalOffer.SITE, start_date=None, end_date=None) <NEW_LINE> return list(chain(date_based_offers, nondat...
Return site offers that are available to all users
625941f0236d856c2ad44d7f
def _append_array_types(self, array_types): <NEW_LINE> <INDENT> for array in array_types: <NEW_LINE> <INDENT> if isinstance(array, basestring): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> array = getattr(gat, array) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> msg = ("Skipping {0} - not found in gnom...
append to self.array_types the input array_types. :param array_types: set of array_types to be appended :type array_types: set() The set contains either a name as a string, say: 'rise_vel' In this case, get the ArrayType from gnome.array_types.rise_vel Set elements could also be tuples, say: ('rise_vel': ArrayType())...
625941f03d592f4c4ed1d5fa
def add(self, key, value, timeout=None): <NEW_LINE> <INDENT> self.set(key, value, timeout) <NEW_LINE> return True
Fake atomic add method for memcache clients
625941f05f7d997b87175039
def getAllNetworkInfo(self): <NEW_LINE> <INDENT> networkInfoList = [] <NEW_LINE> mappingList = g_Platform.getIpAddressAndNICList() <NEW_LINE> for oneList in mappingList: <NEW_LINE> <INDENT> data = networkInfo() <NEW_LINE> data.NICNum = oneList[0] <NEW_LINE> data.ipAddress = oneList[1] <NEW_LINE> try: <NEW_LINE> <INDENT...
function: get all network info
625941f076d4e153a657f0cf
def _name_resolution(self, data): <NEW_LINE> <INDENT> self._complete_task(data, self.ui.lblNameResolution) <NEW_LINE> status = "" <NEW_LINE> passed = data[self._backend.PASSED_KEY] <NEW_LINE> if not passed: <NEW_LINE> <INDENT> status = self.tr("<font color='red'><b>Non-existent " "provider</b></font>") <NEW_LINE> <DEDE...
SLOT TRIGGER: self._backend.signaler.prov_name_resolution Sets the status for the name resolution check
625941f0d268445f265b540c
def turn_left(self): <NEW_LINE> <INDENT> self.current_dir = TURN_LEFT[self.current_dir]
turns the sprite one eighth turn to the left
625941f08c3a87329515895e
def test_users_update(self): <NEW_LINE> <INDENT> pass
Test case for users_update
625941f0d4950a0f3b08c8e3
def retry(self, failed_index, include_failed): <NEW_LINE> <INDENT> if not include_failed: <NEW_LINE> <INDENT> failed_index += 1 <NEW_LINE> <DEDENT> failed = self._tokens[failed_index:] <NEW_LINE> if not failed: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> state = self.__getstate__() <NEW_LINE> state['tokens'] = ...
Create new retry message with tokens from failed index.
625941f0097d151d1a2233f3
def install(domain, lazy=False): <NEW_LINE> <INDENT> if lazy: <NEW_LINE> <INDENT> def _lazy_gettext(msg): <NEW_LINE> <INDENT> return Message(msg, domain=domain) <NEW_LINE> <DEDENT> from six import moves <NEW_LINE> moves.builtins.__dict__['_'] = _lazy_gettext <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> localedir = '%s...
Install a _() function using the given translation domain. Given a translation domain, install a _() function using gettext's install() function. The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specific environment variab...
625941f01f037a2d8b946799
def extract_data(table): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for row in table.rows: <NEW_LINE> <INDENT> data.append([cell.text.strip() for cell in row.cells]) <NEW_LINE> <DEDENT> return data
Extract the data from a Word table. Returns a list of rows, each of which is a list of cell values as strings.
625941f0091ae356686674f1
def _remove_file_or_dir(path): <NEW_LINE> <INDENT> if path.is_dir(): <NEW_LINE> <INDENT> shutil.rmtree(bytes(path)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.remove(bytes(path))
:type path: Path
625941f038b623060ff0b38a
def line_search(self, oracle, x_k, d_k, previous_alpha=None): <NEW_LINE> <INDENT> return None
Finds the step size alpha for a given starting point x_k and for a given search direction d_k that satisfies necessary conditions for phi(alpha) = oracle.func(x_k + alpha * d_k). Parameters ---------- oracle : BaseSmoothOracle-descendant object Oracle with .func_directional() and .grad_directional() methods implem...
625941f001c39578d7e753d8
def get_last_move(history_moves, player): <NEW_LINE> <INDENT> if not history_moves: <NEW_LINE> <INDENT> return False, None <NEW_LINE> <DEDENT> if history_moves[-1].colour != opponent_of(player): <NEW_LINE> <INDENT> return False, None <NEW_LINE> <DEDENT> return True, history_moves[-1].move
Get the last move from the move history, checking it's by the opponent. This is a convenience function for use by move generators. history_moves -- list of History_move objects player -- player to play current move ('b' or 'w') Returns a pair (move_is_available, move) where move is (row, col), or None for a p...
625941f030c21e258bdfaa41
def interactors_url(name, interactors_url): <NEW_LINE> <INDENT> headers = { 'accept': 'application/json', 'content-type': 'text/plain', } <NEW_LINE> params = ( ('name', name), ) <NEW_LINE> url = 'https://reactome.org/ContentService/interactors/upload/tuple/url' <NEW_LINE> data = interactors_url <NEW_LINE> try: <NEW_LIN...
Send file via URL and get a summary associated with a token :param name: Name which identifies the sample :param interactors_url: A URL pointing to the Interactors file :return:
625941f0d7e4931a7ee9e4bc
def _clear_data(self, keep=[], **kwargs): <NEW_LINE> <INDENT> if not ('webshape' in keep or 'shape' in keep): <NEW_LINE> <INDENT> self.webshape = None <NEW_LINE> <DEDENT> if not ('input' in keep or 'inputdata' in keep): <NEW_LINE> <INDENT> self.inputdata = None <NEW_LINE> <DEDENT> if not ('output' in keep or 'outputdat...
Delete all data in this class. You could use keep to keep the variables you want to keep.
625941f0d7e4931a7ee9e4bd
def process_txt_record(template_record, zone_records): <NEW_LINE> <INDENT> new_record = {'type': 'TXT', 'name': template_record['host'], 'data' : template_record['data'], 'ttl': int(template_record['ttl'])} <NEW_LINE> for zone_record in zone_records: <NEW_LINE> <INDENT> zone_record_type = zone_record['type'].upper() <N...
Will process a txt record from a template. This results in marking zone_records for deletion, and returning the new record. A TXT record in the template will delete any CNAME in the zone of the same host value. It will delete TXT records in the zone according to the txtConflict settings.
625941f099fddb7c1c9de92b
def SetNetworkConnection(self, connection_type): <NEW_LINE> <INDENT> if not self._control_network_connection: <NEW_LINE> <INDENT> raise Exception('SetNetworkConnection can only be used with a TestDriver ' 'initalized with control_network_connection=True') <NEW_LINE> <DEDENT> self._network_connection = connection_type <...
Changes the emulated connection type. Args: connection_type: the connection type to use according to the dict near the top of the file OR a dictionary specifying the network conditions
625941f07c178a314d6efa06
def oknotP(n, k=4, l=1, eta_max=0): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> x = np.zeros((1, n+k)) <NEW_LINE> mid = np.linspace(-eta_max-l, eta_max, n-k+2) <NEW_LINE> delta = np.sum(l)/(n-k+2-1) <NEW_LINE> beg = mid[0] + np.arange(-1*(k-1), 0)*delta <NEW_LINE> endd = mid[-1] + np.arange(1, k)*delta <NEW_LINE>...
Generates a B-spline uniform periodic knot vector Parameters ---------- n: Scalar The number of defining polygon vertices k: Scalar Order of the basis function. order = degree + 1, so for a cubic, k = 4 l: Scalar Arbitrary length. eta_max: Scalar Max noise? Returns ------- x: 1D array The knot...
625941f0566aa707497f4afd
def _compute_related(self, records): <NEW_LINE> <INDENT> others = records.sudo() if self.related_sudo else records <NEW_LINE> if records.env != others.env: <NEW_LINE> <INDENT> copy_cache(records - records.filtered('id'), others.env) <NEW_LINE> <DEDENT> values = list(others) <NEW_LINE> for name in self.related[:-1]: <NE...
Compute the related field ``self`` on ``records``.
625941f07b25080760e399f2
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> from basicmodem.basicmodem import BasicModem as bm <NEW_LINE> name = config.get(CONF_NAME) <NEW_LINE> port = config.get(CONF_DEVICE) <NEW_LINE> modem = bm(port) <NEW_LINE> if modem.state == modem.STATE_FAILED: <NEW_LINE> <INDENT> _L...
Setup modem caller id sensor platform.
625941f0711fe17d825428fb
@markers.test_case("C591686") <NEW_LINE> @markers.highlighting <NEW_LINE> @markers.skip_test(reason="test mechanics covered by C591687") <NEW_LINE> def test_expanded_focussed_note_card_is_displayed_when_highlight_clicked(): <NEW_LINE> <INDENT> pass
Display the focussed note card after clicking a highlight.
625941f08a43f66fc4b545fc
def validate_options(self): <NEW_LINE> <INDENT> for opt_name, opt_value in self.get_options().items(): <NEW_LINE> <INDENT> opt = self.definition.get_option(opt_name) <NEW_LINE> validator = opt.get_validator() <NEW_LINE> if validator: <NEW_LINE> <INDENT> if not isinstance(validator, Validator): <NEW_LINE> <INDENT> if ca...
Validates the options @raise: InvalidOptionValue
625941f0090684286d50f28c
def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> if not hasattr(cls,"_object"): <NEW_LINE> <INDENT> cls._object = object.__new__(cls) <NEW_LINE> <DEDENT> return cls._object
使用new作为单例函数,函数实例化从new开始,而不是从__init__开始
625941f0aad79263cf390fe7
def addL(self,name,node1,node2,value=None): <NEW_LINE> <INDENT> sy = sympy.Symbol(name) <NEW_LINE> dict = {} <NEW_LINE> dict['k'] = 'l' <NEW_LINE> dict['n'] = name <NEW_LINE> dict['n1'] = node1 <NEW_LINE> dict['n2'] = node2 <NEW_LINE> dict['v'] = value <NEW_LINE> dict['sy'] = sy <NEW_LINE> self.components.append(dic...
Add a inductor to the circuit Parameters: name : Name of the inductor node1 : First node node2 : Second node value : Value of the inductor (Defaults to None) Return the inductor symbol
625941f050485f2cf553d339
def test_rec_mid_state_start(self): <NEW_LINE> <INDENT> log.info("============ START RECOVERED MID STATE START ================") <NEW_LINE> log.info("Recovered Mid State length %d", len(REC_RECORD_2_10)) <NEW_LINE> input_file = StringIO(REC_RECORD_2_10) <NEW_LINE> new_state = { Vel3dLWfpStateKey.POSITION: 479, Vel3dLW...
Test starting the parser in a state in the middle of processing
625941f08e7ae83300e4b56c
def handle_private_message(bot, update, user_data): <NEW_LINE> <INDENT> keyboard = [[InlineKeyboardButton("Kyllä / Yes", callback_data = "1"), InlineKeyboardButton("Ei / No", callback_data = "0")]] <NEW_LINE> markup = InlineKeyboardMarkup(keyboard) <NEW_LINE> user_data["msg"] = update.effective_message <NEW_LINE> updat...
Ask the user whether to forward their message to the public channel anonymously.
625941f04a966d76dd5515b3
@setHook(HOOK_STARTUP) <NEW_LINE> def startupEvent(): <NEW_LINE> <INDENT> setPinDir(GREEN_LED, True) <NEW_LINE> setPinDir(RED_LED, True) <NEW_LINE> setPinDir(BLUE_LED, True) <NEW_LINE> writePin(GREEN_LED, True) <NEW_LINE> writePin(RED_LED, True) <NEW_LINE> writePin(BLUE_LED, True) <NEW_LINE> setPinDir(TiltSwitch1 ,Fals...
This is hooked into the HOOK_STARTUP event
625941f07b25080760e399f3
@login_required <NEW_LINE> def createview(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = ShortDomainForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> cd = form.cleaned_data <NEW_LINE> owner = cd['owner'] if cd['owner'] else request.user.username <NEW_LINE> owne...
create new domain
625941f066673b3332b9262e
@csrf_exempt <NEW_LINE> @api_view(['GET']) <NEW_LINE> @permission_classes((IsAuthenticated,)) <NEW_LINE> def questionssort(request,type): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> if type == 'newest': <NEW_LINE> <INDENT> snippets = PostQuestion.objects.order_by('-time') <NEW_LINE> serializer =...
List all code snippets, or create a new snippet.
625941f094891a1f4081c049
def test_can_create_comment_201(self): <NEW_LINE> <INDENT> response = self.create_comment('POST', self.comment) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertIn('body', response.data)
Test whether API can create a comment successfully
625941f0d164cc61757832ed
def generate_random_state() -> GameState: <NEW_LINE> <INDENT> from random import shuffle <NEW_LINE> randomized_board_arr: List[int] = [i for i in range(N * N)] <NEW_LINE> shuffle(randomized_board_arr) <NEW_LINE> return GameState( board=tuple([ tuple([randomized_board_arr[j] for j in range(i, i + N)]) for i in range(0, ...
Generate a random valid puzzle state. Ret: PuzzleBoard
625941f03617ad0b5ed68494
def make_adder(n): <NEW_LINE> <INDENT> def adder(k): <NEW_LINE> <INDENT> return k+n <NEW_LINE> <DEDENT> return adder
return a function that take one argument k, and return k+n >>> add_three = make_adder(3) >>> add_three(4) 7
625941f0be383301e01b5a18
def pi_s(s_box, ur): <NEW_LINE> <INDENT> vr = 0 <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> uri = ur % (2 ** 4) <NEW_LINE> vri = s_box[uri] <NEW_LINE> vr = vr + (vri << (4 * i)) <NEW_LINE> ur = ur >> 4 <NEW_LINE> <DEDENT> return vr
分组代换操作 :param s_box:S盒参数 :param ur:输入比特串,16比特 :return:输出比特串,16比特
625941f0656771135c3ebe13
def average_assignment_written_score(self, assignment_id): <NEW_LINE> <INDENT> assignment = self.find_assignment(assignment_id) <NEW_LINE> if assignment.num_submissions == 0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> score_sum = self.db.query(func.coalesce(func.sum(Grade.score), 0.0)) .join(GradeCel...
Compute the average written score for an assignment. Parameters ---------- assignment_id : string the name of the assignment Returns ------- score : float The average written score
625941f096565a6dacc8fc67
def _idp_url(self, method): <NEW_LINE> <INDENT> if method in self.idp_mapping: <NEW_LINE> <INDENT> return self.idp + self.idp_mapping[method] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ValueError('Idp Mapping did not include path for %s' % method)
Returns the IdP URL for the requested method. :param method: The method name in the IdP mapping dict. :rtype: string :returns: The IdP URL
625941f0498bea3a759ba04b
def setup_ex(self, init_net, finish_net): <NEW_LINE> <INDENT> pass
Nets to be executed once at startup and finish.
625941f0be7bc26dc91cdb92
def plot_pr_curve(y_true, y_score, is_single_fig=False): <NEW_LINE> <INDENT> prec, rec, thresh = precision_recall_curve(y_true, y_score) <NEW_LINE> avg_prec = average_precision_score(y_true, y_score) <NEW_LINE> plt.title('AUPRC = {:.4f}'.format(avg_prec)) <NEW_LINE> plt.step(rec, prec, color='b', alpha=0.2, where='post...
Plot Precision Recall Curve and show AUPRC score
625941f0435de62698dfe1eb
def _calculate_fitness(self): <NEW_LINE> <INDENT> population_fitness = [] <NEW_LINE> for individual in self.population: <NEW_LINE> <INDENT> loss = 0 <NEW_LINE> for i in range(len(individual)): <NEW_LINE> <INDENT> letter_i1 = self.letters.index(individual[i]) <NEW_LINE> letter_i2 = self.letters.index(self.target[i]) <NE...
Calculates the fitness of each individual in the population
625941f02ae34c7f2600d6ce