code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def tree(self, rows: List[List]) -> ArborParser: <NEW_LINE> <INDENT> self.arbor = self.arbor_class() <NEW_LINE> self.positions = dict() <NEW_LINE> edges = [] <NEW_LINE> for node, proximal, pos1, pos2, pos3, *_ in rows: <NEW_LINE> <INDENT> self.positions[node] = np.array([pos1, pos2, pos3]) <NEW_LINE> if proximal: <NEW_...
Parse skeleton from either response
625941c9bde94217f3682e6b
def set_sut(self): <NEW_LINE> <INDENT> if self.systems == 'all': <NEW_LINE> <INDENT> self.res = self.resources['resources'] <NEW_LINE> return <NEW_LINE> <DEDENT> _active, _res = list(), list() <NEW_LINE> try: <NEW_LINE> <INDENT> for sut in self.resources['resources']: <NEW_LINE> <INDENT> if sut['name'] in self.systems:...
Set the systems under test.
625941c98e71fb1e9831d823
def data(self)->dict: <NEW_LINE> <INDENT> return self.data
Return a dictionary with values of lists {1:[], 2:[],...}
625941c9090684286d50ed5e
def _get_varpars(self): <NEW_LINE> <INDENT> params = self.mats_eval.identify_parameters() <NEW_LINE> varset = {} <NEW_LINE> for key, par in list(params.items()): <NEW_LINE> <INDENT> par_val = getattr(self.mats_eval , key) <NEW_LINE> varset[key] = VariedParam(mats_eval=self.mats_eval, varname=key) <NEW_LINE> <DEDENT> re...
reset the varpar list according to the current mats_eval object.
625941c9293b9510aa2c3310
def _random_snake(self): <NEW_LINE> <INDENT> self._current_snake_index = random.randint(0, self.NUM_SNAKES - 1) <NEW_LINE> self._current_snake = self._snakes[self._current_snake_index] <NEW_LINE> self._current_snake_frame_index = 0 <NEW_LINE> self._current_snake_color = self.SNAKE_COLORS[random.randint(0, self.NUM_SNAK...
Updates the internal state with a new random snake.
625941c973bcbd0ca4b2c0f0
def __hash__(self): <NEW_LINE> <INDENT> return hash(str(self))
Hash function required for creating sets of Names
625941c9cc0a2c11143dcf0a
def __call__(self, shape, dtype=K.floatx(), partition_info=None): <NEW_LINE> <INDENT> del partition_info <NEW_LINE> init_range = 1.0 / np.sqrt(shape[1]) <NEW_LINE> return tf.random.uniform(shape, -init_range, init_range, dtype=dtype)
Initialization for dense kernels. This initialization is equal to tf.variance_scaling_initializer(scale=1.0/3.0, mode='fan_out', distribution='uniform'). It is written out explicitly here for clarity. Args: shape: shape of variable dtype: dtype of variable partition_info: unused Retur...
625941c97b180e01f3dc4878
def prepare_city(data): <NEW_LINE> <INDENT> city = data['city'] <NEW_LINE> save_del(city, 'class') <NEW_LINE> data = city['data'] <NEW_LINE> save_del(city, 'data') <NEW_LINE> if data: <NEW_LINE> <INDENT> save_del(data, ['_location', 'location', 'dc']) <NEW_LINE> city.update(data)
Remove some properties and flatten out city data
625941c991f36d47f21ac56b
def import_data(filename='albums_data.txt'): <NEW_LINE> <INDENT> data_list = [] <NEW_LINE> with open (filename, "r") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> data_list.append(line.strip().split(",")) <NEW_LINE> <DEDENT> <DEDENT> return data_list
Import data from a file to a list. Expected returned data format: ["David Bowie", "Low", "1977", "rock", "38:26"], ["Britney Spears", "Baby One More Time", "1999", "pop", "42:20"], ...] :param str filename: optional, name of the file to be imported :returns: list of lists representing albums' data :rtype:...
625941c985dfad0860c3aed4
def minimum_dominating_set_driver_nodes(self, graph='structural', max_search=5, keep_self_loops=True, *args, **kwargs): <NEW_LINE> <INDENT> self._check_compute_variables(sg=True) <NEW_LINE> if graph == 'structural': <NEW_LINE> <INDENT> dg = self.structural_graph(*args, **kwargs) <NEW_LINE> <DEDENT> elif graph == 'effec...
The minimun set of necessary driver nodes to control the network based on Minimum Dominating Set (MDS) theory. Args: max_search (int) : Maximum search of additional variables. Defaults to 5. keep_self_loops (bool) : If self-loops are used in the computation. Returns: (list) : A list-of-lists with MDS solu...
625941c963b5f9789fde715f
def _intersects(x, windows): <NEW_LINE> <INDENT> for window in windows: <NEW_LINE> <INDENT> if x>= window[0] and x <= window[1]: <NEW_LINE> <INDENT> return window <NEW_LINE> <DEDENT> <DEDENT> return None
Returns the first interval/window where x intersects, or None
625941c9a219f33f346289e5
def __init__(self, vectors, indices, length=0): <NEW_LINE> <INDENT> super(SparseMatrix, self).__init__(vectors) <NEW_LINE> self.indices = indices <NEW_LINE> self.length = length
'length' is the number of rows of the matrix - the number of entries in 'vectors' is just the number of non-zero rows You can assume that the number of entries in values and indices is the same.
625941c9a8370b771705291a
def __init__(__self__, *, administrative: Optional[pulumi.Input[bool]] = None, annotations: Optional[pulumi.Input[Mapping[str, Any]]] = None, builtin: Optional[pulumi.Input[bool]] = None, context: Optional[pulumi.Input[str]] = None, default_role: Optional[pulumi.Input[bool]] = None, description: Optional[pulumi.Input[s...
Input properties used for looking up and filtering RoleTempalte resources. :param pulumi.Input[bool] administrative: Administrative role template :param pulumi.Input[Mapping[str, Any]] annotations: Annotations of the resource :param pulumi.Input[bool] builtin: Builtin role template :param pulumi.Input[str] context: Con...
625941c9925a0f43d2549ef0
def attention_lm_prepare_decoder(targets, hparams): <NEW_LINE> <INDENT> if hparams.prepend_mode == "prepend_inputs_full_attention": <NEW_LINE> <INDENT> decoder_self_attention_bias = ( common_attention.attention_bias_prepend_inputs_full_attention( common_attention.embedding_to_padding(targets))) <NEW_LINE> <DEDENT> else...
Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal alignments
625941c98da39b475bd64fec
def load_datasets_tira_evaluation(test_dataset_main_directory, preset_key): <NEW_LINE> <INDENT> PRESETS_DICTIONARY = {'PAN18_English': {'dataset_name': 'PAN 2018 English', 'xmls_subdirectory': 'en/text', 'truth_subpath': 'en/truth.txt', }, 'PAN18_Spanish': {'dataset_name': 'PAN 2018 Spanish', 'xmls_subdirectory': 'es/t...
Load the PAN dataset for **Tira** evaluation. This function loads the PAN training and test dataset and truth by calling the *ProcessDataFiles* module twice, then passes them along with Author IDs of the test dataset.
625941c932920d7e50b28249
def load_table(path: str, **kwargs) -> pd.DataFrame: <NEW_LINE> <INDENT> if is_csv(path): <NEW_LINE> <INDENT> return load_csv(str(path), **kwargs) <NEW_LINE> <DEDENT> elif is_excel(path): <NEW_LINE> <INDENT> return load_xls(str(path), **kwargs)
Smartly load the table whether it's a csv or excel file.
625941c956ac1b37e626424a
def shows_setlists_tiph(self): <NEW_LINE> <INDENT> return self.get(params={'method': 'pnet.shows.setlists.tiph', 'format': self.FORMAT})
"Today In Phish History": returns the setlist of a show from the current day and month in Phish history. :return: API response object of show setlists.
625941c9a8ecb033257d3147
def _pairwise_distances(embeddings, other_embeddings=None, squared=False): <NEW_LINE> <INDENT> if other_embeddings is None: <NEW_LINE> <INDENT> dot_product = tf.matmul(embeddings, tf.transpose(embeddings)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dot_product = tf.matmul(embeddings, tf.transpose(other_embeddings)) ...
Compute the 2D matrix of distances between all the embeddings. Args: embeddings: tensor of shape (batch_size, embed_dim) squared: Boolean. If true, output is the pairwise squared euclidean distance matrix. If false, output is the pairwise euclidean distance matrix. Returns: pairwise_distances...
625941c96e29344779a6268c
def test_system_status_add_processes(self, test_system_status): <NEW_LINE> <INDENT> test_system_status.system_status.add_processes('proc1') <NEW_LINE> assert 'proc1' in test_system_status.system_status._processes
Test that adding a process to SystemStatus works correctly.
625941c93eb6a72ae02ec555
def write (self): <NEW_LINE> <INDENT> self.states.write_states (self.params.states_filename) <NEW_LINE> self.intersections.write_intersections (self.params.intersections_file) <NEW_LINE> return
method to save everything to default filenames as supplied in the params file
625941c9a934411ee375170d
def buildIndex(corpuspath): <NEW_LINE> <INDENT> startTime = datetime.now() <NEW_LINE> postings = {} <NEW_LINE> num_docs = 0 <NEW_LINE> norm_factors = [] <NEW_LINE> doc_titles = [] <NEW_LINE> doc_ids = [] <NEW_LINE> i_doc = 0 <NEW_LINE> for foldername in os.listdir(corpuspath): <NEW_LINE> <INDENT> if foldername != 'AA':...
path -> dict Input : corpuspath Output : {'num_docs','posting_list','norm_factor','doc_titles','doc_ids'} Description : returns the inverted index generated from the wikipedia corpus (AA folder) along with document ids, document titles and their normalization constants
625941c9e5267d203edcdd18
def evaluate(model, num_episodes=100): <NEW_LINE> <INDENT> env = model.get_env() <NEW_LINE> all_episode_rewards = [] <NEW_LINE> for i in range(num_episodes): <NEW_LINE> <INDENT> episode_rewards = [] <NEW_LINE> done = False <NEW_LINE> obs = env.reset() <NEW_LINE> env.render() <NEW_LINE> while not done: <NEW_LINE> <INDEN...
Evaluate a RL agent :param model: (BaseRLModel object) the RL Agent :param num_episodes: (int) number of episodes to evaluate it :return: (float) Mean reward for the last num_episodes
625941c938b623060ff0ae67
def SetFeatureImage(self, *args): <NEW_LINE> <INDENT> return _itkBinaryStatisticsOpeningImageFilterPython.itkBinaryStatisticsOpeningImageFilterIUC3IF3_SetFeatureImage(self, *args)
SetFeatureImage(self, itkImageF3 input)
625941c956b00c62f0f146d3
def get_next_generation(self) -> Grid: <NEW_LINE> <INDENT> new_greed = self.create_grid(False) <NEW_LINE> for i in range(self.rows): <NEW_LINE> <INDENT> for j in range(self.cols): <NEW_LINE> <INDENT> if self.curr_generation[i][j]: <NEW_LINE> <INDENT> if sum(self.get_neighbours((i, j))) in [2, 3]: <NEW_LINE> <INDENT> ne...
Получить следующее поколение клеток. Returns ---------- out : Grid Новое поколение клеток.
625941c92ae34c7f2600d1ab
def extract_content(html) : <NEW_LINE> <INDENT> h = html2text.HTML2Text() <NEW_LINE> return h.handle(html)
Extract the main text content of a page.
625941c9a4f1c619b28b00b5
def getErrorSentence(self): <NEW_LINE> <INDENT> errorSentence = [] <NEW_LINE> for datum in self.data: <NEW_LINE> <INDENT> if datum.hasError(): <NEW_LINE> <INDENT> errorSentence.append(datum.error) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> errorSentence.append(datum.word) <NEW_LINE> <DEDENT> <DEDENT> return errorSen...
Returns a list of strings with the sentence containing all the errors.
625941c991af0d3eaac9ba92
def scale(requestContext, seriesList, factor): <NEW_LINE> <INDENT> for series in seriesList: <NEW_LINE> <INDENT> series.tags['scale'] = factor <NEW_LINE> series.name = "scale(%s,%g)" % (series.name,float(factor)) <NEW_LINE> series.pathExpression = series.name <NEW_LINE> for i,value in enumerate(series): <NEW_LINE> <IND...
Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint by the constant provided at each point. Example: .. code-block:: none &target=scale(Server.instance01.threads.busy,10) &target=scale(Server.instance*.threads.busy,10)
625941c963f4b57ef0001195
def get_removed_jobs(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> jobs=self.removed_jobs <NEW_LINE> self.removed_jobs=[] <NEW_LINE> self.lock.release() <NEW_LINE> return jobs[:]
retrieves the list of removed jobs, clearing out the list in the process
625941c97c178a314d6ef4d8
def path_raw(element: Element): <NEW_LINE> <INDENT> if element is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> p = parent(element) <NEW_LINE> if p is not None: <NEW_LINE> <INDENT> return path_raw(p) + '/' + element.tag <NEW_LINE> <DEDENT> return element.tag
get tag path using recursive function, only contains raw tag for example result: html/body/div/div/ul/li :param element: :return:
625941c93d592f4c4ed1d0ea
def __init__(self, *args): <NEW_LINE> <INDENT> this = _lldb.new_SBData(*args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.this = this
__init__(self) -> SBData __init__(self, SBData rhs) -> SBData
625941c9cdde0d52a9e530ad
def load_cifar(flatten=True, labels=False): <NEW_LINE> <INDENT> def extract(name): <NEW_LINE> <INDENT> print('extracting data from {}'.format(name)) <NEW_LINE> h = tar.extractfile(name) <NEW_LINE> if sys.version_info < (3, ): <NEW_LINE> <INDENT> d = pickle.load(h) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d = pickl...
Load the CIFAR10 image dataset.
625941c931939e2706e4cee6
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkRegionalMaximaImageFilterIUL3IUL3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkRegionalMaximaImageFilterIUL3IUL3 Create a new object of the class itkRegionalMaximaImageFilterIUL3IUL3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non na...
625941c90a366e3fb873e894
def encode_single_bit(bit, state): <NEW_LINE> <INDENT> G1 = [1, 1, 1, 0, 0, 1] <NEW_LINE> G2 = [0, 1, 1, 0, 1, 1] <NEW_LINE> out_g1 = bit <NEW_LINE> for index_g1, val in enumerate(state): <NEW_LINE> <INDENT> if 1 == G1[index_g1]: <NEW_LINE> <INDENT> out_g1 = int(bool(val) ^ bool(out_g1)) <NEW_LINE> <DEDENT> <DEDENT> ou...
Encodes single input bit into two output bits. Requires the state of the delay line (6 previous bits).
625941c95fdd1c0f98dc02ad
def search(isamAppliance, userID, force=False, check_mode=False): <NEW_LINE> <INDENT> ret_obj = get_all(isamAppliance) <NEW_LINE> return_obj = isamAppliance.create_return_object() <NEW_LINE> for obj in ret_obj['data']: <NEW_LINE> <INDENT> if obj['userID'] == userID: <NEW_LINE> <INDENT> logger.info("Found user {0}".form...
Search device id by userId
625941c9090684286d50ed5f
def convert_skip_exceptions(method): <NEW_LINE> <INDENT> @functools.wraps(method) <NEW_LINE> def _wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = method(*args, **kwargs) <NEW_LINE> <DEDENT> except StopEverything: <NEW_LINE> <INDENT> raise unittest.SkipTest("StopEverything!") <NEW_LINE> <...
A decorator for test methods to convert StopEverything to SkipTest.
625941c94d74a7450ccd423e
def weighted_std(self,values,weights): <NEW_LINE> <INDENT> average = np.average(values, weights=weights) <NEW_LINE> variance = np.average((values-average)**2, weights=weights) <NEW_LINE> return np.sqrt(variance)
Return the weighted average and standard deviation. values, weights -- Numpy ndarrays with the same shape.
625941c924f1403a92600be2
def get_output_folder(parent_dir, env_name): <NEW_LINE> <INDENT> os.makedirs(parent_dir, exist_ok = True) <NEW_LINE> experiment_id = 0 <NEW_LINE> for folder_name in os.listdir(parent_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(parent_dir, folder_name)): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> t...
return save folder
625941c9be383301e01b5501
@ServiceManagementRoute.route('/services') <NEW_LINE> def get_services(): <NEW_LINE> <INDENT> result_list = util.getServiceList() <NEW_LINE> return jsonify({'ServicesInfo': result_list})
return: the services list include basic information
625941c9eab8aa0e5d26dbd2
def station_stats(df): <NEW_LINE> <INDENT> print('\nCalculating The Most Popular Stations and Trip...\n') <NEW_LINE> start_time = time.time() <NEW_LINE> most_common_startst = df['Start Station'].value_counts() <NEW_LINE> print("most common start station is :", most_common_startst.index[0]) <NEW_LINE> most_common_endst ...
Displays statistics on the most popular stations and trip.
625941c93317a56b86939cd5
def test_fwhm(): <NEW_LINE> <INDENT> disp = 0.01223 <NEW_LINE> x = np.arange(1430.,1435., 0.01223) <NEW_LINE> y = np.random.normal(1e-13,0.3e-13, x.shape) <NEW_LINE> sigma = 0.2 <NEW_LINE> mu = 1433. <NEW_LINE> ampl = 1e-12 <NEW_LINE> y += ampl*np.exp(-(x-mu)**2./(0.5 * sigma**2.)) <NEW_LINE> yerr = np.ones_like(y) * 3...
Test the FWHM of convolved models First generate some artifical data test need to be close to final to make sure Sherpa finds a good fit. The FWHM of the a convolved Gaussian should be smaller than that of a stand-alone Gaussian. The difference has to be 6.5 pix.
625941c9a17c0f6771cbe0cb
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> i, j, k = m - 1, n - 1, m + n - 1 <NEW_LINE> while k >= 0: <NEW_LINE> <INDENT> if j == -1 or (i >= 0 and nums1[i] > nums2[j]): <NEW_LINE> <INDENT> nums1[k] = nums1[i] <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums1[k] = nums2[j] <NEW_LINE> j...
:type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
625941c9925a0f43d2549ef1
def release_write(self): <NEW_LINE> <INDENT> self._writers -= 1 <NEW_LINE> self._writerList.remove(threading.get_ident()) <NEW_LINE> self._read_ready.notifyAll() <NEW_LINE> self._read_ready.release()
Release a write lock.
625941c9b5575c28eb68e07a
def new_document(): <NEW_LINE> <INDENT> rs.DocumentModified(False) <NEW_LINE> rs.Command('_-New _None') <NEW_LINE> sc.doc.Views.Redraw()
Brute-force new document, discard all unsaved changes.
625941c9a05bb46b383ec89d
def __init__(self): <NEW_LINE> <INDENT> self.register_cache =[ (self.ALS_GAIN_x2 << ALS_SM_SHIFT) | (self.ALS_INTEGRATION_100ms << ALS_IT_SHIFT) | (self.ALS_PERSISTENCE_1 << ALS_PERS_SHIFT) | (0 << ALS_INT_EN_SHIFT) | (0 << ALS_SD_SHIFT), 0x0000, 0xffff, (self.ALS_POWER_MODE_3 << PSM_SHIFT) | (0 << PSM_EN_SHIFT) ]
! @brief Module init
625941c9a17c0f6771cbe0cc
def _update_central_params(self): <NEW_LINE> <INDENT> r <NEW_LINE> for key, value in self.param_dict.items(): <NEW_LINE> <INDENT> if key in self.central_occupation_model.param_dict: <NEW_LINE> <INDENT> self.central_occupation_model.param_dict[key] = value
Private method to update the model parameters.
625941c9be7bc26dc91cd67c
def findMaxLength(self, nums): <NEW_LINE> <INDENT> diff = best = 0 <NEW_LINE> first = {} <NEW_LINE> for i, b in enumerate(nums): <NEW_LINE> <INDENT> add = 1 if b == 1 else -1 <NEW_LINE> if -diff - add in first: <NEW_LINE> <INDENT> best = max(best, i - first[-diff - add] + 1) <NEW_LINE> <DEDENT> if -diff not in first: <...
:type nums: List[int] :rtype: int
625941c999fddb7c1c9de40c
def simple_stats(self): <NEW_LINE> <INDENT> self.tourny_types() <NEW_LINE> self.profit() <NEW_LINE> self.create_array() <NEW_LINE> self.avg_win = np.mean(self.data[0][0]) <NEW_LINE> self.avg_cost = np.mean(self.data[1][0]) <NEW_LINE> self.avg_place = np.mean(self.data[2][0]) <NEW_LINE> self.avg_players = np.mean(self.d...
Using numpy to calculate simple statistics.
625941c97d43ff24873a2d1b
def p_ConditionalAndExpression( p ): <NEW_LINE> <INDENT> pass
ConditionalAndExpression : ConditionalAndExpression OP_LAND InclusiveOrExpression | InclusiveOrExpression
625941c9b7558d58953c4f90
def get_source_link(file, line, display_text="[source]", **kwargs)->str: <NEW_LINE> <INDENT> link = f"{SOURCE_URL}{file}#L{line}" <NEW_LINE> if display_text is None: return link <NEW_LINE> return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>'
Returns github link for given file
625941c907f4c71912b114fc
def controll(self, ticket): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.buffer[ticket] <NEW_LINE> del self.buffer[ticket] <NEW_LINE> self._fwrite(data) <NEW_LINE> ticket += 1 <NEW_LINE> return self.controll(ticket) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return ticket
RECURSIVE try to write ticket seq to file if a valid sequence @integer ticket: number of packet @return integer
625941c9596a897236089b3c
def ZInitializeClass(cls): <NEW_LINE> <INDENT> initClass(cls) <NEW_LINE> return cls
Use AccessControl.class_init.InitializeClass as a class decorator.
625941c9435de62698dfdcc7
def evaluate(stack, x, constants): <NEW_LINE> <INDENT> forward_eval = _forward_eval(stack, x, constants) <NEW_LINE> return forward_eval[-1].reshape((-1, 1))
Evaluate an equation Evaluate the equation associated with an Agraph, at the values x. Parameters ---------- stack : Nx3 numpy array of int. The command stack associated with an equation. N is the number of commands in the stack. x : MxD array of numeric. Values at which to evaluate the equations....
625941c94e696a04525c94c6
def __init__( self, username: str, password: str, auth_url: str, auth_version: str, tenant_name: str, tenant_domain_id: str, service_region: str, domain_name: str, node_name: Optional[str] = None, ) -> None: <NEW_LINE> <INDENT> self.driver = get_openstack_driver( username=username, password=password, auth_url=auth_url,...
Initialize the instance using the provided information. The co Args: username: The name of the user to be set for the session. password: The password of the provided user. auth_url: The endpoint that can authenticate the user. auth_version: The version to be used for authentication. tenant...
625941c9a79ad161976cc1c0
def _random_user_agent(): <NEW_LINE> <INDENT> firefox_version_max = 61 <NEW_LINE> chrome_version_list = ["59.0.3071", "60.0.3112", "61.0.3163", "62.0.3202", "63.0.3239", "64.0.3282", "65.0.3325", "66.0.3359", "67.0.3396", "68.0.3423"] <NEW_LINE> windows_version_dict = { "Windows 2000": "Windows NT 5.0", "Windows XP": "...
Get a random valid Firefox or Chrome user agent Common firefox user agent "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0" Common chrome user agent "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" Common IE user agent ...
625941c92eb69b55b151c929
def test_GradientBoostingClassifier_max_features(*data): <NEW_LINE> <INDENT> X_train,X_test,y_train,y_test=data <NEW_LINE> fig=plt.figure() <NEW_LINE> ax=fig.add_subplot(1,1,1) <NEW_LINE> max_features=np.linspace(0.01,1.0) <NEW_LINE> testing_scores=[] <NEW_LINE> training_scores=[] <NEW_LINE> for features in max_feature...
test the performance with different max_features :param data: train_data, test_data, train_value, test_value :return: None
625941c99f2886367277a908
def move(self, direction: str) -> int: <NEW_LINE> <INDENT> newhead_i = self.snake[-1][0] + self.direct[direction][0] <NEW_LINE> newhead_j = self.snake[-1][1] + self.direct[direction][1] <NEW_LINE> if not (0 <= newhead_i < self.m and 0 <= newhead_j < self.n) or [newhead_i, newhead_j] in self.snake and [newhead_i, newhea...
Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body.
625941c923e79379d52ee5df
def __init__(self, build_event): <NEW_LINE> <INDENT> self._build_event = build_event <NEW_LINE> self.id = build_event['detail']['build-id'] <NEW_LINE> self.project_name = build_event['detail']['project-name'] <NEW_LINE> self.status = build_event['detail']['build-status']
Create new Build helper object.
625941c945492302aab5e33d
def __init__(self): <NEW_LINE> <INDENT> self.unconfirmed_transactions = [] <NEW_LINE> self.chain = [] <NEW_LINE> self.create_genesis_block()
Constructor for the `BlockChain` class.
625941c9460517430c394202
def scheme_optimized_eval(expr, env, tail=False): <NEW_LINE> <INDENT> if scheme_symbolp(expr): <NEW_LINE> <INDENT> return env.lookup(expr) <NEW_LINE> <DEDENT> elif self_evaluating(expr): <NEW_LINE> <INDENT> return expr <NEW_LINE> <DEDENT> if tail: <NEW_LINE> <INDENT> return Thunk(expr, env) <NEW_LINE> <DEDENT> else: <N...
Evaluate Scheme expression EXPR in environment ENV. If TAIL, returns an Thunk object containing an expression for further evaluation.
625941c97cff6e4e81117a01
def __init__(self: "Area", window_width: int = 500, window_height: int = 500, player_obj: "Snake"=None, enemies: "Group"=None): <NEW_LINE> <INDENT> area_base.Area.__init__(self, window_width, window_height, player_obj, enemies) <NEW_LINE> self.is_checkpoint = False <NEW_LINE> self._initialize_area1_walls_and_railings()
Initializes the attributes of an Area4_1 object.
625941c99f2886367277a909
def execute(self): <NEW_LINE> <INDENT> ilcPath = '' <NEW_LINE> if 'ConfigPath' not in self.arguments: <NEW_LINE> <INDENT> LOG.warn('No CS ConfigPath defined') <NEW_LINE> return S_ERROR('JobPathResoulution Failure') <NEW_LINE> <DEDENT> LOG.verbose('Attempting to resolve job path for ILC') <NEW_LINE> job = self.arguments...
Given the arguments from the JobPathAgent, this function resolves job optimizer paths according to ILC VO policy.
625941c999cbb53fe6792c61
def load_resource_definitions(self, src): <NEW_LINE> <INDENT> result = None <NEW_LINE> path = os.path.normpath(src) <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <INDENT> self.fail(msg="Error accessing {0}. Does the file exist?".format(path)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(path, 'r') as f: ...
Load the requested src path
625941c9fff4ab517eb2f4b7
def get_my_all_books_data(self): <NEW_LINE> <INDENT> logger.info("Getting data of all your books...") <NEW_LINE> r = self.session.get(self.account_data.my_books_url, headers=self.account_data.req_headers, timeout=10) <NEW_LINE> if r.status_code is not 200: <NEW_LINE> <INDENT> message = "Cannot open {}, http GET status ...
Gets data from all available ebooks
625941c930dc7b76659019e2
def setUp(self): <NEW_LINE> <INDENT> self.pod = ProjectObjectDict.example() <NEW_LINE> self.temp_directory = tempfile.mkdtemp()
Create a few ProjectObjects for use in the ProjectObjectDict.
625941c9e5267d203edcdd19
def calculate_packing(request, id, quantity=None, with_properties=False, as_string=False, template_name="lfs/catalog/packing_result.html"): <NEW_LINE> <INDENT> product = Product.objects.get(pk=id) <NEW_LINE> if quantity is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> quantity = request.POST.get("quantity") <NEW_L...
Calculates the actual amount of pieces to buy on base on packing information.
625941c932920d7e50b2824a
def candidate_score(self, instance, word, v_cand, v_pos, v_neut, v_neg, v_kill): <NEW_LINE> <INDENT> if np.linalg.norm(v_cand) < 0.1: <NEW_LINE> <INDENT> return (-1000.0, [], "No vectors for word") <NEW_LINE> <DEDENT> sim_pos = v_pos.dot(v_cand) <NEW_LINE> sim_neut = v_neut.dot(v_cand) <NEW_LINE> sim_neg = v_neg.dot(v_...
return (score, matched_positive_words, msg)
625941c95fc7496912cc39f9
def H_grad(mu, state): <NEW_LINE> <INDENT> x = state[0] <NEW_LINE> y = state[1] <NEW_LINE> z = state[2] <NEW_LINE> px = state[3] <NEW_LINE> py = state[4] <NEW_LINE> pz = state[5] <NEW_LINE> grad = np.empty(6) <NEW_LINE> r1 = np.sqrt((x + mu) * (x + mu) + y * y + z * z) <NEW_LINE> r2 = np.sqrt((x + mu - 1) * (x + mu - 1...
calculates normalized gradient of hamiltonian for scrtbp; used for initial var_state in ofli
625941c976d4e153a657ebac
def finish_job(self, job): <NEW_LINE> <INDENT> index = next((i for i in range(len(self.jobs_running)) if self.jobs_running[i].id == job.id), -1) <NEW_LINE> if index >= 0: <NEW_LINE> <INDENT> self.jobs_running.pop(index) <NEW_LINE> self.jobs_done.append(job) <NEW_LINE> log_traffic('%s - Moved %s from running to done.' %...
Finishes a running job. Removes it from the running jobs list and adds it to the done jobs list. Args: job (WorkerJob): the job to put into state 'done'
625941c96fece00bbac2d7b9
def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.climb_dir(*args, *kwargs)
Call climb_dir if Inspector is directly called.
625941c9009cb60464c6342d
def xpathSubstringBeforeFunction(self, nargs): <NEW_LINE> <INDENT> libxml2mod.xmlXPathSubstringBeforeFunction(self._o, nargs)
Implement the substring-before() XPath function string substring-before(string, string) The substring-before function returns the substring of the first argument string that precedes the first occurrence of the second argument string in the first argument string, or the empty string if the first argument string does no...
625941c9cc40096d615959cc
def morse_epsilon(self): <NEW_LINE> <INDENT> return self.pair_type.parameters['coeffs'][0]
Set default value, if epsilon is not set at initialisation.
625941c907f4c71912b114fd
def codesCellSelected(self): <NEW_LINE> <INDENT> x = self.tableWidget_codes.currentRow() <NEW_LINE> y = self.tableWidget_codes.currentColumn() <NEW_LINE> if y == self.CODE_COLOR_COLUMN: <NEW_LINE> <INDENT> Dialog_colorselect = QtGui.QDialog() <NEW_LINE> ui = Ui_Dialog_colorselect(self.freecode[x]['color']) <NEW_LINE> u...
When colour or memo cells are selected in the table widget, open a memo dialog or colour selector dialog
625941c97d847024c06be336
def __init__( self, operation = None, csPath = None ): <NEW_LINE> <INDENT> OperationHandlerBase.__init__( self, operation, csPath ) <NEW_LINE> gMonitor.registerActivity( "ReplicateAndRegisterAtt", "Replicate and register attempted", "RequestExecutingAgent", "Files/min", gMonitor.OP_SUM ) <NEW_LINE> gMonitor.registerAct...
c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler
625941c9627d3e7fe0d68eca
def SetWakeTime(self, time): <NEW_LINE> <INDENT> self.last_time = self.GetCurrentTime() <NEW_LINE> logging.debug('Current epoch time: %s' % self.last_time) <NEW_LINE> wakealarm_fh = open('/sys/class/rtc/rtc0/wakealarm', 'wb', 0) <NEW_LINE> try: <NEW_LINE> <INDENT> wakealarm_fh.write('0\n'.encode('ascii')) <NEW_LINE> wa...
Get the current epoch time from /sys/class/rtc/rtc0/since_epoch then add time and write our new wake_alarm time to /sys/class/rtc/rtc0/wakealarm. The math could probably be done better but this method avoids having to worry about whether or not we're using UTC or local time for both the hardware and system clocks.
625941c9d4950a0f3b08c3cb
def ll_expectation_helper(ctm, T_primary_aug, root, disease_data=None): <NEW_LINE> <INDENT> total_tree_length = T_primary_aug.size(weight='weight') <NEW_LINE> primary_info = _mjp.get_history_statistics(T_primary_aug, root=root) <NEW_LINE> dwell_times, root_state, transitions = primary_info <NEW_LINE> post_root_distn = ...
Get contributions to the expected log likelihood of the compound process. The primary process trajectory is fully observed, but the binary tolerance states are unobserved. Parameters ---------- ctm : CompoundToleranceModel Information about the evolutionary process. T_primary_aug : x x root : integer The ...
625941c960cbc95b062c65be
def check(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_output(["cutadapt", "--version"], stderr=subprocess.STDOUT) <NEW_LINE> return True <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> raise ToolNotFoundException
Checks if cutadapt is installed
625941c98a349b6b435e81ee
def get_baud_rates(): <NEW_LINE> <INDENT> result = [] <NEW_LINE> result.append("2400") <NEW_LINE> result.append("4800") <NEW_LINE> result.append("9600") <NEW_LINE> result.append("19200") <NEW_LINE> result.append("38400") <NEW_LINE> result.append("57600") <NEW_LINE> result.append("115200") <NEW_LINE> result.append("2304...
List of baud rates. :return: List of available baud rates.
625941c96aa9bd52df036e1f
def _set_expanded_menus(): <NEW_LINE> <INDENT> names = [] <NEW_LINE> result = db_query( "SELECT menu_name FROM {menu_links} " + "WHERE expanded != 0 GROUP BY menu_name") <NEW_LINE> while True: <NEW_LINE> <INDENT> n = db_fetch_array(result) <NEW_LINE> if not n: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> names.a...
Helper function to update a list of menus with expanded items
625941c95f7d997b87174b12
def exclude_file(patterns, info): <NEW_LINE> <INDENT> return info.is_dir or not self.match(patterns, info.name)
Pattern match info.name.
625941c9cb5e8a47e48b7b27
def execute(hst, usr, passwd, cmd): <NEW_LINE> <INDENT> ssh = paramiko.SSHClient() <NEW_LINE> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> try: <NEW_LINE> <INDENT> ssh.connect(hst, 22, usr, passwd) <NEW_LINE> stdin, stdout, stderr = ssh.exec_command(cmd) <NEW_LINE> output = stdout.read().strip()...
Executes command on ssh server and returns output
625941c98e71fb1e9831d825
def test_design_folders_id_delete(self): <NEW_LINE> <INDENT> pass
Test case for design_folders_id_delete Delete a model instance by {{id}} from the data source.
625941c93539df3088e2e3c6
def analyze(self, X): <NEW_LINE> <INDENT> raise NotImplementedError()
Analyze the behavior of model on input `X`. :param X: Input as expected by model.
625941c9a79ad161976cc1c1
def _run(self, image, image_filename: str = '') -> None: <NEW_LINE> <INDENT> write_path = f'{self.write_path}/{image_filename.split(".")[0]}' <NEW_LINE> file_type = image_filename.split('.')[-1] <NEW_LINE> if not os.path.exists(write_path): <NEW_LINE> <INDENT> os.makedirs(write_path) <NEW_LINE> <DEDENT> for iteration i...
Run the style transfer algorithm on the image. Writes images to the write path.
625941c9bde94217f3682e6d
def __init__(self, raw_log_path = raw_log_path, json_usrs_log_path = json_usrs_log_path, conn = conn, bucket_filters = bucket_filters, file_filters = file_filters): <NEW_LINE> <INDENT> super(PowerSamplerLogImporter, self).__init__(raw_log_path, json_usrs_log_path, conn, bucket_filters, file_filters) <NEW_LINE> logger =...
init Arguments: - `raw_log_path`: raw data path - `json_usrs_log_path`: json data path - `conn`: connection to S3 - `bucket_filters`: bucket filters - `file_filters`: file filters
625941c9eab8aa0e5d26dbd3
def test_simple(self): <NEW_LINE> <INDENT> ciphertexts = Ciphertexts() <NEW_LINE> ciphertexts.load("tests/crypto01") <NEW_LINE> key = XorCracker(ciphertexts).crack() <NEW_LINE> decrypted = ciphertexts.tostring(ciphertexts.size()-1, key) <NEW_LINE> self.assertEqual(decrypted, '#Z#na Hollywood": "#miem pisac i czytac, al...
Test the most basic example
625941c9d8ef3951e32435b9
def open(self, filename=None): <NEW_LINE> <INDENT> filename = filename or self.config['journal'] <NEW_LINE> if not os.path.exists(filename): <NEW_LINE> <INDENT> util.prompt("[Journal '{0}' created at {1}]".format(self.name, filename)) <NEW_LINE> self._create(filename) <NEW_LINE> <DEDENT> text = self._load(filename) <NE...
Opens the journal file defined in the config and parses it into a list of Entries. Entries have the form (date, title, body).
625941c9ad47b63b2c509ffb
def confirm_yes(intent_request): <NEW_LINE> <INDENT> session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {} <NEW_LINE> checkingReservation = {} <NEW_LINE> if try_ex(lambda: json.loads(session_attributes['currentReservation'])) is not None: <NEW_LINE> <INDENT>...
Performs dialog management and fulfillment for booking a car. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be used to guide conversation
625941c966673b3332b9210c
def field(obj): <NEW_LINE> <INDENT> method_list=[] <NEW_LINE> for method_name in dir(obj): <NEW_LINE> <INDENT> if method_name[0:2] != '__': <NEW_LINE> <INDENT> if callable(getattr(obj, method_name)): <NEW_LINE> <INDENT> method_list.append(method_name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> attr_list = list(obj.__dict__....
field returns the fields of an object's instance Parameters ---------- obj: instance (mandatory) instance of a class containing fields Returns ------- tuple of list attr_list, method_list = field(instance) attr_list = ['attribute1', 'attribute2',...] method_list = ['method1', 'method2',...]
625941c985dfad0860c3aed6
def add_edge_query_response(edges): <NEW_LINE> <INDENT> print(edges) <NEW_LINE> query_response = db_objects.graph_db().AQLQuery( add_edge_query(edges) ).response <NEW_LINE> if query_response['error']: <NEW_LINE> <INDENT> return {"is successful execution": False} <NEW_LINE> <DEDENT> print(json.dumps(query_response, inde...
Add a dependent concept. [description] Parameters ---------- id : string Id to be assigned to new edge. fromNode : string Id of the concept. toNode : string Id of the to concept. context_id : string Id of the context to which the dependent concept has to be added. uid : string Id of the user who a...
625941c9046cf37aa974cdc4
def exploiter(state_q_values, trial): <NEW_LINE> <INDENT> return max(state_q_values, key=state_q_values.get)
An exploiter always returns the action with the largest Q value. The trial is also ignored.
625941c963d6d428bbe4456b
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EntryAlumniStatusItem): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c9f7d966606f6aa07f
def paginate(object_list, page_size, page_num): <NEW_LINE> <INDENT> page_num = page_num or 1 <NEW_LINE> paginator = Paginator(object_list, page_size) <NEW_LINE> try: <NEW_LINE> <INDENT> page = paginator.page(page_num) <NEW_LINE> <DEDENT> except PageNotAnInteger: <NEW_LINE> <INDENT> return Page([], 1, paginator) <NEW_LI...
Takes an object_list, page_size, page_num and paginates the object list.
625941c93eb6a72ae02ec557
def truncateStr(s, l, postfix='…'): <NEW_LINE> <INDENT> if len(s) > l: <NEW_LINE> <INDENT> k = l - len(postfix) <NEW_LINE> s = s[:k] + postfix <NEW_LINE> <DEDENT> return s
Truncate string with the specified length @s — input string @l — length of output string
625941c966673b3332b9210d
def elevation(coord, lat, lst): <NEW_LINE> <INDENT> assert isinstance(coord, SkyCoord) <NEW_LINE> assert isinstance(lat, float) <NEW_LINE> assert isinstance(lst, float) <NEW_LINE> if lst < 0. or lst > 24.: <NEW_LINE> <INDENT> raise ValueError("lst must be in range 0 <= lst < 24, " "not {}".format(lst)) <NEW_LINE> <DEDE...
Given a celestial coordinate and observatory latitude, calculate the celestial coordinate's elevation given an LST. Parameters ---------- coord: astropy.coordinates.SkyCoord Object's RA/DEC lat: float Observatory latitude in degrees lst: float Local sideral time in hours Returns ------- Elevation as an as...
625941c930dc7b76659019e3
def sentenceIntersection(self, s1,s2): <NEW_LINE> <INDENT> w1 = self.wordFrequency(s1) <NEW_LINE> w2 = self.wordFrequency(s2) <NEW_LINE> key1 = w1.keys() <NEW_LINE> key2 = w2.keys() <NEW_LINE> if (len(key1) == 0) or (len(key2) == 0): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sum1Sq = su...
Intersection of two sentences
625941c9a934411ee375170f
def __init__(self, database, initial, diversification=None, intensification=None, tabu_limit=None, allow_swap='never', **kwargs): <NEW_LINE> <INDENT> super().__init__(database, initial, **kwargs) <NEW_LINE> if allow_swap not in ['always', 'dynamic', 'never']: <NEW_LINE> <INDENT> raise ValueError('allow_swap value %s is...
Standard implementation of TABU The only non-standard part is the dynamic enabling option of the swap operations. Parameters ---------- database: the database object (required) initial: the initial solution, this will not be mutated (required) verbose: if true, progress information will be printed to stdout ...
625941c926238365f5f0eee9
@coroutine <NEW_LINE> def ring_buffer(next, window, covering): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buffer = [None]*(window*10) <NEW_LINE> write_index = 0 <NEW_LINE> read_index = 0 <NEW_LINE> data_size = 0 <NEW_LINE> offset = window - covering <NEW_LINE> while True : <NEW_LINE> <INDENT> input = yield <NEW_LINE>...
Ring buffer inside a coroutine that allows to bufferize received data Hand send it to next method when window size is reached. A covering size can be set to include this amount of the previous data with the next send. :param next: next coroutine to send data :param window: data size to send :param covering: data size s...
625941c9187af65679ca519a
def draw_frame(surface, frame, opacity=255): <NEW_LINE> <INDENT> global LINE_COLORS <NEW_LINE> frame_rect = frame.get_enclosing_rect(10, 16, 10) <NEW_LINE> frame_surface = pygame.Surface((frame_rect.width, frame_rect.height)) <NEW_LINE> pos_delta = (-frame_rect.left, -frame_rect.top) <NEW_LINE> for line in frame.lines(...
draws all the points, lines and circles in a frame
625941c9442bda511e8be495
def processMultiplierSegment(segment, source_dir_band, wind_prj, bear_prj, dst_band): <NEW_LINE> <INDENT> band_numbers_for_indices_in_geotiff = [2, 3, 1, 6, 5, 7, 8, 4, 2] <NEW_LINE> indices = { 0: {'dir': 'n', 'min': 0., 'max': 22.5}, 1: {'dir': 'ne', 'min': 22.5, 'max': 67.5}, 2: {'dir': 'e', 'min': 67.5, 'max': 112....
Calculates local wind multiplier data by image segments and writes to corresponding segment of output file :param segment: image segment specified by [x_offset, y_offset, width, height, segment_count, total_segments] :param source_dir_band: 8 band array representing wind mulitpliers dat...
625941c929b78933be1e5729
def parse_sentence(self, sentence): <NEW_LINE> <INDENT> sent = Sentence(sentence) <NEW_LINE> sent.extract_edge_features(type='test') <NEW_LINE> dec = self.model_head.decision_function(sent.edge_features) <NEW_LINE> min_values = np.amin(dec, axis=0) <NEW_LINE> max_values = np.amax(dec, axis=0) <NEW_LINE> score_pred = (d...
tag a single tokenized and pos tagged sentence sentence: [[tkn1, tag1], [tkn2, tag2], ...] return the parsed with the same data format 4 tab separated fields per line
625941c991af0d3eaac9ba94