code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, mi=0, value=0): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.last_clusters_info_loss = [] <NEW_LINE> self.mi = mi | :param mi: number of published clusters to be used to calculate Tau
:param value: the info_loss average of the last mi published clusters | 625941d0a219f33f34628acc |
def login_account(config, machine_auth, username=None, password=None): <NEW_LINE> <INDENT> if not config.username and not bitcoin_computer.has_mining_chip(): <NEW_LINE> <INDENT> logger.info(uxstring.UxString.signin_title) <NEW_LINE> <DEDENT> username = username or get_username_interactive() <NEW_LINE> password = passwo... | Log in a user into the two1 account
Args:
config (Config): config object used for getting .two1 information
username (str): optional command line arg to skip username prompt
password (str): optional command line are to skip password prompt | 625941d04527f215b584c5b9 |
def quic_graph_lasso_ebic_manual(X, gamma=0): <NEW_LINE> <INDENT> print("QuicGraphicalLasso (manual EBIC) with:") <NEW_LINE> print(" mode: path") <NEW_LINE> print(" gamma: {}".format(gamma)) <NEW_LINE> model = QuicGraphicalLasso( lam=1.0, mode="path", init_method="cov", path=np.logspace(np.log10(0.01), np.log10(1.0... | Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model
selection.
The EBIC criteria is built into InverseCovarianceEstimator base class
so we demonstrate those utilities here. | 625941d032920d7e50b28334 |
def imshow(img): <NEW_LINE> <INDENT> img = img/2 + 0.5 <NEW_LINE> npimg = img.numpy() <NEW_LINE> plt.imshow(np.transpose(npimg,(1,2,0))) <NEW_LINE> plt.show() | function to show images | 625941d044b2445a339321f9 |
def findWords(self, words): <NEW_LINE> <INDENT> row = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm']] <NEW_LINE> result = [] <NEW_LINE> for single_word in words: <NEW_LINE> <INDENT> single_word_lower = single_word.lower() <NEW_LINE... | :type words: List[str]
:rtype: List[str] | 625941d023e79379d52ee6c7 |
def _prepend_min(arr, pad_amt, num, axis=-1): <NEW_LINE> <INDENT> if pad_amt == 0: <NEW_LINE> <INDENT> return arr <NEW_LINE> <DEDENT> if num == 1: <NEW_LINE> <INDENT> return _prepend_edge(arr, pad_amt, axis) <NEW_LINE> <DEDENT> if num is not None: <NEW_LINE> <INDENT> if num >= arr.shape[axis]: <NEW_LINE> <INDENT> num =... | Prepend `pad_amt` minimum values along `axis`.
Parameters
----------
arr : ndarray
Input array of arbitrary shape.
pad_amt : int
Amount of padding to prepend.
num : int
Depth into `arr` along `axis` to calculate minimum.
Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
Axis along whic... | 625941d08c3a87329515851e |
def test_get_all_code_area(self): <NEW_LINE> <INDENT> article = self.create_article_with_code() <NEW_LINE> right_answer = ['print("Hello CodeCollect! I am Article")'] <NEW_LINE> my_answer = get_all_code_area(article, "python") <NEW_LINE> self.assertEqual(right_answer, my_answer) <NEW_LINE> article = self.create_article... | 测试获取笔记的代码块 | 625941d024f1403a92600cc9 |
def RemoveAll(self,*args): <NEW_LINE> <INDENT> pass | RemoveAll(self: TabControl)
Removes all the tab pages and additional controls from this tab control. | 625941d09c8ee82313fbb8d9 |
def detect_aes_ecb(data, blocksize=16): <NEW_LINE> <INDENT> row_scores = [] <NEW_LINE> for i, row in enumerate(data): <NEW_LINE> <INDENT> blocks = row.view(dtype=np.dtype([('data', (np.uint8, blocksize))])) <NEW_LINE> counts = np.unique(blocks, return_counts=True)[1] <NEW_LINE> most_repetition = counts.max() <NEW_LINE>... | Set 1 - Challenge 8
Returns index of AES ECB encoded row. | 625941d038b623060ff0af51 |
def get_latest_params(self): <NEW_LINE> <INDENT> return self._params | Returns the latest regression run paraneters, either from the train() method, or the feature_selection() one.
Returns:
parameters : pd.Series - dataframe of parameters | 625941d0d486a94d0b98e2a9 |
@login_required <NEW_LINE> def customer_create(request): <NEW_LINE> <INDENT> form = CustomerForm(request.POST or None) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> if form.is_valid(): <NEW_LINE> <INDENT> Customer.objects.create( name=form.cleaned_data.get('name'), bank_name=form.cleaned_data.get('bank_na... | This function is used to create Customer | 625941d0d268445f265b4fd1 |
def event_m10_10_111244(): <NEW_LINE> <INDENT> event_m10_10_x7(z150=60, z151=104163) <NEW_LINE> Quit() | OBJ: Satoshi Moonlight: Judgment of death | 625941d03617ad0b5ed6805b |
@app.template_filter() <NEW_LINE> def customEnumerate(value): <NEW_LINE> <INDENT> return enumerate(value) | A function to simply return the enumerated value of a list, as this is not in-built into jinja2.
:param value: The list
:return: The enumerated list | 625941d0a934411ee37517f7 |
def unpack(message): <NEW_LINE> <INDENT> return msgpack.unpackb(message, object_hook=_decode_datetime) | Unpack a binary msgpacked message. | 625941d0236d856c2ad4493f |
def __float__(self): <NEW_LINE> <INDENT> return _MEDCalculator.DataArrayDouble___float__(self) | __float__(self) -> double
1 | 625941d04f88993c3716c1ca |
def detect_author(tweets, tweet): <NEW_LINE> <INDENT> tweet_hashtags = extract_hashtags(tweet) <NEW_LINE> candidate_hashtags = {} <NEW_LINE> counts = {} <NEW_LINE> all_hashtags = helper_5(tweets) <NEW_LINE> unique_hashtags = helper_4(all_hashtags) <NEW_LINE> if tweet_hashtags != []: <NEW_LINE> <INDENT> for key, value i... | (dict of {str: list of tweet tuples}, str) -> str
Returns the probable author of a tweet based on the tweets passed in
as an argument (which is the output of read_tweets of some tweet data).
Probable author is found by retrieving the hashtags found in the tweet
and comparing that to each candidate's lists of all hasht... | 625941d03eb6a72ae02ec643 |
def extract_models(multi_model_PDB_file): <NEW_LINE> <INDENT> generated_output_files_prefix = generate_output_files_prefix( multi_model_PDB_file) <NEW_LINE> the_multi_file_stream = open(multi_model_PDB_file , "r") <NEW_LINE> model_number = 1 <NEW_LINE> new_file_text = "" <NEW_LINE> for line in the_multi_file_stream: <N... | This function takes a file containing several PDB-formatted structure models
and extracts each individual model. Saving each individual model to a
new file based on the name of the original file.
Arguments for the function are as follows:
* the file with PDB-formatted models. Requires the PDB file include
both ... | 625941d04d74a7450ccd4327 |
def __init__(self, timestamp=None, value=None, helper_observable_id=None): <NEW_LINE> <INDENT> self.timestamp = timestamp <NEW_LINE> self.value = value <NEW_LINE> self.helper_observable_id = helper_observable_id | :param timestamp:
:param value:
:param flag:
:param tags: | 625941d071ff763f4b5497f0 |
def set_cache_header(self): <NEW_LINE> <INDENT> if not self.server.development: <NEW_LINE> <INDENT> cache_time = 365 * 86400 <NEW_LINE> self.send_header( HTTP_HEADER_CACHE_CONTROL, "public, max-age={}".format(cache_time)) <NEW_LINE> self.send_header( HTTP_HEADER_EXPIRES, self.date_time_string(time.time()+cache_time)) | Add cache headers if not in development | 625941d030dc7b7665901aca |
def refresh_topics(self): <NEW_LINE> <INDENT> topic_list = rospy.get_published_topics() <NEW_LINE> if topic_list is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.topic_combox.clear() <NEW_LINE> for (name, type) in topic_list: <NEW_LINE> <INDENT> if type == 'trajectory_msgs/JointTrajectory': <NEW_LINE> <INDE... | Refresh topic list in the combobox | 625941d0cdde0d52a9e53198 |
def setAlphaToSlider(self): <NEW_LINE> <INDENT> index = self.imagelist.currentRow() <NEW_LINE> alpha=100 <NEW_LINE> if index >= 0: <NEW_LINE> <INDENT> alpha_fract = self.images[index].alpha <NEW_LINE> alpha = np.round(alpha_fract*100) <NEW_LINE> <DEDENT> self.alpha_sld.setValue(alpha) <NEW_LINE> log1("setAlphaFromSlide... | Takes the alpha value of the current image and sets that the slider. | 625941d066673b3332b921f5 |
def displayWait(): <NEW_LINE> <INDENT> print("Thank you. Just a moment please...") | prints the wait message | 625941d0566aa707497f46cb |
def flip_pil_img_and_boxes(img, boxes=None): <NEW_LINE> <INDENT> assert isinstance(img, Image.Image), "img should be PIL.Image" <NEW_LINE> w, h = img.size <NEW_LINE> flip_img = img.transpose(Image.FLIP_LEFT_RIGHT) <NEW_LINE> if boxes is not None: <NEW_LINE> <INDENT> flip_boxes = boxes.copy() <NEW_LINE> flip_boxes[:, 0]... | Flip PIL Images and Boxes
Args:
img: PIL Image
boxes: [N, 4] | 625941d030bbd722463cbf2a |
def apply_cwle_for_datasets(datasets, k=1): <NEW_LINE> <INDENT> if k <= 0: <NEW_LINE> <INDENT> raise ValueError('Iterations should be a positive integer. ' 'Found k={}'.format(k)) <NEW_LINE> <DEDENT> atom_arrays, adj_arrays, teach_signals = wle_io.load_dataset_elements(datasets) <NEW_LINE> for i in range(k): <NEW_LINE>... | Apply Concatenated Weisfeiler--Lehman embedding for the tuple of datasets.
This also applicalbe for the Gated-sum Weisfeiler--Lehman embedding.
Args:
datasets: tuple of dataset (usually, train/val/test),
each dataset consists of atom_array and
adj_array and teach_signal
k: int... | 625941d0e64d504609d749a4 |
def testCanberra2(self): <NEW_LINE> <INDENT> distance = D.Canberra(o2, t2) <NEW_LINE> actual = 2.0 <NEW_LINE> self.assertAlmostEqual(distance, actual, places=4) | Canberra for list (Test 1) | 625941d094891a1f4081bc0e |
def bin_quantities(x, y, bins, func, *args, **kwargs): <NEW_LINE> <INDENT> xx = x.ravel() <NEW_LINE> yy = y.ravel() <NEW_LINE> idx = np.digitize(xx, bins) <NEW_LINE> result = np.zeros(len(bins)) <NEW_LINE> for i in range(len(bins)): <NEW_LINE> <INDENT> if np.sum(idx == i) > 0: <NEW_LINE> <INDENT> result[i] = func(yy[id... | Perform a certain function on x-bins of a x/y relation.
Parameters
----------
x - n-D array
Array with the abcissa. If more than 1D, it will be flattened.
y - n-D array
Array with the coordinates. If more than 1D, it will be flattened.
bins - array-like (1D)
Values for the abcissa bins.
func - [numpy] functi... | 625941d0cc0a2c11143dcff4 |
def get_player_data(group, previous_round_data, current_round_data, self_pgr): <NEW_LINE> <INDENT> prdvs = ParticipantRoundDataValue.objects.for_group(group=group, round_data__in=[ previous_round_data, current_round_data], parameter__in=(get_player_status_parameter(), get_storage_parameter(), get_harvest_decision_param... | Returns a tuple ([list of player data dictionaries], { dictionary of this player's data })
FIXME: refactor this into its own class as opposed to an arcane data structure | 625941d073bcbd0ca4b2c1da |
def clean_axis(ax): <NEW_LINE> <INDENT> ax.get_xaxis().set_ticks([]) <NEW_LINE> ax.get_yaxis().set_ticks([]) <NEW_LINE> ax.set_axis_bgcolor('#ffffff') <NEW_LINE> for sp in ax.spines.values(): <NEW_LINE> <INDENT> sp.set_visible(False) | Remove ticks, tick labels, and frame from axis | 625941d091af0d3eaac9bb7d |
def setup_logging( default_path='logging.json', default_level=logging.INFO, env_key='LOG_CFG' ): <NEW_LINE> <INDENT> path = default_path <NEW_LINE> value = os.getenv(env_key, None) <NEW_LINE> if value: <NEW_LINE> <INDENT> path = value <NEW_LINE> <DEDENT> if os.path.exists(path): <NEW_LINE> <INDENT> with open(path, 'rt'... | Setup logging configuration
| 625941d07c178a314d6ef5c5 |
def test_10(self): <NEW_LINE> <INDENT> comp = {'test': 'success'} <NEW_LINE> obj_1 = CbKeyStore(passphrase='secret', dict=comp) <NEW_LINE> with self.assertRaises(CbKsPasswordError): <NEW_LINE> <INDENT> obj_2 = CbKeyStore(file=obj_1.file, passphrase='sacred') <NEW_LINE> <DEDENT> del obj_1 | Test Case 10:
Create a key store with crypto backend on a temporary file.
Test is passed if a second key store object using wrong credentials causes a
:py:exc:`~controlbeast.keystore.CbKsPasswordError` to be raised. | 625941d04f88993c3716c1cb |
def _to_object_dict(data): <NEW_LINE> <INDENT> return_dict = {OSIORegisteredRepos.git_url: data["git-url"], OSIORegisteredRepos.git_sha: data["git-sha"], OSIORegisteredRepos.email_ids: data.get('email-ids', 'dummy'), OSIORegisteredRepos.last_scanned_at: datetime.datetime.now() } <NEW_LINE> return return_dict | Convert the object of type JobToken into a dictionary. | 625941d07d847024c06be420 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr... | Returns the model properties as a dict | 625941d04a966d76dd551174 |
def qr2ascii(self, image): <NEW_LINE> <INDENT> string = '' <NEW_LINE> image = image.convert('L') <NEW_LINE> width, height = image.size <NEW_LINE> pix = image.load() <NEW_LINE> for i in range(0, width, STEP): <NEW_LINE> <INDENT> for j in range(0, height, STEP): <NEW_LINE> <INDENT> p = pix[i, j] <NEW_LINE> p = '██' if p ... | 从二维码图片生成ascii二维码 | 625941d0d486a94d0b98e2aa |
def writeData(self, data, scalarData=None): <NEW_LINE> <INDENT> nSamples = len(data) <NEW_LINE> if self.chunkSize == 0: <NEW_LINE> <INDENT> self.chunkSize = nSamples <NEW_LINE> self.grp.attrs['chunkSize'] = nSamples <NEW_LINE> <DEDENT> elif self.chunkSize is not None and nSamples != self.chunkSize: <NEW_LINE> <INDENT> ... | Write more data to the current dataset.
*data* : numpy array of data
scalarData : list of scalar datapoints to go in the scalarField specified
in constructor.
Returns: None | 625941d063b5f9789fde724a |
def main(): <NEW_LINE> <INDENT> wheel_no = int(sys.argv[1]) <NEW_LINE> wheel = wheels[wheel_no] <NEW_LINE> start = sys.argv[2] <NEW_LINE> step = int(sys.argv[3]) <NEW_LINE> message = "" <NEW_LINE> for m in sys.argv[4:]: <NEW_LINE> <INDENT> message += m <NEW_LINE> <DEDENT> result = process(wheel, start, step, message) <... | Process command line arguments and process a whole message | 625941d056ac1b37e6264332 |
def _fixdata(data): <NEW_LINE> <INDENT> for wositem in data: <NEW_LINE> <INDENT> if isinstance(getattr(wositem, 'AU', ''), str): <NEW_LINE> <INDENT> wositem.AU = [wositem.AU] <NEW_LINE> <DEDENT> if isinstance(getattr(wositem, 'AF', ''), str): <NEW_LINE> <INDENT> wositem.AF = [wositem.AF] <NEW_LINE> <DEDENT> if isinstan... | Data Preparation. | 625941d0fbf16365ca6f632a |
def remove(self, key: int) -> None: <NEW_LINE> <INDENT> self.values[key] = -1 | Removes the mapping of the specified value key if this map contains a mapping for the key | 625941d0dd821e528d63b30d |
def Convierto_a_Lista(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, QtSql.QSqlQuery): <NEW_LINE> <INDENT> l = [] <NEW_LINE> while obj.next(): <NEW_LINE> <INDENT> l.append(obj.record()) <NEW_LINE> <DEDENT> return l <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "No me diste un Query" | Recibe un QtSqlQuery y devuelve una Lista | 625941d023849d37ff7b31f4 |
def __str__(self): <NEW_LINE> <INDENT> return repr(self) | Return this Subsystem as a string. | 625941d038b623060ff0af52 |
@asyncio.coroutine <NEW_LINE> def fetch_tiles(urls, loop=None): <NEW_LINE> <INDENT> if __debug__: <NEW_LINE> <INDENT> logger.debug('fetching tiles...') <NEW_LINE> <DEDENT> tasks = (fetch_tile(u) for u in urls) <NEW_LINE> data = yield from asyncio.gather(*tasks, loop=loop, return_exceptions=True) <NEW_LINE> if __debug__... | Download map tiles for the collection of URLs.
This is asyncio coroutine.
Tile data for each URL is returned. If there was an error while
downloading a tile, then None is returned for given URL.
:param urls: Collection of URLs. | 625941d0d10714528d5ffe48 |
def saml_test_config(self, test_slug, **kwargs): <NEW_LINE> <INDENT> all_params = ['test_slug'] <NEW_LINE> all_params.append('callback') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpec... | get saml test configuration
### Get a SAML test configuration by test_slug.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>... | 625941d05510c4643540f548 |
def __init__(self, config, config_global): <NEW_LINE> <INDENT> if not self.config_defaults: <NEW_LINE> <INDENT> self.config_defaults = {} <NEW_LINE> <DEDENT> self.config = config <NEW_LINE> configdict.extend_deep(self.config, self.config_defaults.copy()) <NEW_LINE> self.config_global = config_global <NEW_LINE> self.val... | Init pattern. | 625941d06fece00bbac2d8a3 |
def __str__(self): <NEW_LINE> <INDENT> print("[Rectangle] ({}) {}/{} - {}/{}". format(self.id, self.x, self.y, self.width, self.height), end="") <NEW_LINE> return("") | overload of a method __str__ | 625941d03317a56b86939dbc |
def polyreloc(p, x, y=0.0): <NEW_LINE> <INDENT> truepoly = isinstance(p, poly1d) <NEW_LINE> r = np.atleast_1d(p).copy() <NEW_LINE> n = r.shape[0] <NEW_LINE> for ii in range(n, 1, -1): <NEW_LINE> <INDENT> for i in range(1, ii): <NEW_LINE> <INDENT> r[i] = r[i] - x * r[i - 1] <NEW_LINE> <DEDENT> <DEDENT> r[-1] = r[-1] + y... | Relocate polynomial
The polynomial `p` is relocated by "moving" it `x`
units along the x-axis and `y` units along the y-axis.
So the polynomial `r` is relative to the point (x,y) as
the polynomial `p` is relative to the point (0,0).
Parameters
----------
p : array-like, poly1d
vector or matrix of column vectors o... | 625941d023e79379d52ee6c8 |
def test_validUserIdInvalidPassword(self): <NEW_LINE> <INDENT> parentUsername, parentRegResultDict = self.toolBox.registerNewParent(8, '@brainquake.com', 'password') <NEW_LINE> parentId = parentRegResultDict['user']['id'] <NEW_LINE> oldPassword = "invalid" <NEW_LINE> resultDict = self.toolBox.changePassword(NEWPASSWORD... | Pass valid user Id and invalid password -- TC6 | 625941d0379a373c97cfacaa |
def __init__(self, name, setup_build, teardown_build, command, atomizer, max_executors, max_executors_per_slave): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.setup_build = setup_build <NEW_LINE> self.teardown_build = teardown_build <NEW_LINE> self.command = command <NEW_LINE> self.atomizer = atomizer <NEW_LINE... | :type name: str
:type setup_build: list[str] | None
:type teardown_build: list[str] | None
:type command: list[str]
:type atomizer: Atomizer
:type max_executors: int | None
:type max_executors_per_slave: int | None | 625941d0d10714528d5ffe49 |
def get_predicate_datatype_by_slug_uri(self, slug_uri): <NEW_LINE> <INDENT> datatype = 'xsd:string' <NEW_LINE> if (isinstance(self.context, dict) and isinstance(slug_uri, str)): <NEW_LINE> <INDENT> if not slug_uri in self.context: <NEW_LINE> <INDENT> return datatype <NEW_LINE> <DEDENT> for type_variant in ['@type', 'ty... | Looks up a predicate's datatype via the predicate slug URI. | 625941d091f36d47f21ac658 |
def densenet121(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> pattern = re.compile( r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var... | Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941d0bf627c535bc13333 |
def test_put_object_from_file_user_metadata(self): <NEW_LINE> <INDENT> user_metadata = {'company': '百度', 'work': 'develop'} <NEW_LINE> object_key = '测试文件'.encode('utf-8') <NEW_LINE> self.get_file(5) <NEW_LINE> response = self.bos.put_object_from_file(bucket=self.BUCKET, key=object_key, file_name=self.FILENAME, user_met... | test put_object_from_file user metadata | 625941d091af0d3eaac9bb7e |
def __init__(self, task_tree): <NEW_LINE> <INDENT> self.cb_group = ReentrantCallbackGroup() <NEW_LINE> self.name = f'tasknode_{TaskNode._count}' <NEW_LINE> self.task_tree = task_tree <NEW_LINE> self.subtask_goalhandles = {} <NEW_LINE> super().__init__(self.name) <NEW_LINE> TaskNode._count += 1 <NEW_LINE> self.action_se... | コンストラクタ
| 625941d055399d3f05588819 |
def detach(self, obj, topic=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._observers[topic].remove(obj) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise self.NotSuchTopic(topic) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise self.NotSuchObserver(obj) | Detach an object of a topic | 625941d007d97122c41789f1 |
def _oldload(self, j: Dict[str, Any]): <NEW_LINE> <INDENT> self.setDescription(j['description']) <NEW_LINE> for k in j['results]']: <NEW_LINE> <INDENT> rcs = j['results'][k] <NEW_LINE> for rc in rcs: <NEW_LINE> <INDENT> meta = rc[Experiment.METADATA] <NEW_LINE> for k in meta: <NEW_LINE> <INDENT> if k in [ Experiment.ST... | Load an old-format file.
In this format, all results were held in dicts keyed by a key synthesised from the
parameter names and values. Pending results were held as a mapping from job ids
to these synthetic keys.
:param j: the old-style JSON object | 625941d076e4537e8c3517d8 |
def load_from_file(self, cmdfile: Optional[str]) -> None: <NEW_LINE> <INDENT> if cmdfile is not None: <NEW_LINE> <INDENT> with open(cmdfile, "r") as fp: <NEW_LINE> <INDENT> for line in fp: <NEW_LINE> <INDENT> self.read_cmd(line) | Load an Aires command/input file by filename.
Parameters
----------
cmdfile: str
The absolute path to an Aires command or input file.
Returns
-------
None | 625941d04f6381625f114ba0 |
def set_matrix(self, key: str, val: np.ndarray): <NEW_LINE> <INDENT> self.set(key, encode_matlab(val)) | Sets an Eigen::Matrix or Eigen::Vector in Redis. | 625941d056b00c62f0f147be |
def compile(self, unused_target, **kwargs): <NEW_LINE> <INDENT> super(iOSFlavorUtils, self).compile(unused_target, **kwargs) <NEW_LINE> for app in ['dm', 'nanobench']: <NEW_LINE> <INDENT> self._py('package ' + app, self.m.vars.skia_dir.join('gn', 'package_ios.py'), args=[self.out_dir.join(app)]) | Build Skia with GN and sign the iOS apps | 625941d00a50d4780f666ff7 |
def move_it(self): <NEW_LINE> <INDENT> self.old_loc = self.location[:] <NEW_LINE> try: <NEW_LINE> <INDENT> color = self.color <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> color = BRIGHT_BLUE <NEW_LINE> <DEDENT> position, angle = get_ship_box(color,self.screen_half) <NEW_LINE> if (position == None) and... | Updates location based on current velocity. This location is to
scale with the exact location at the furthest out zoom | 625941d085dfad0860c3afc0 |
def as_np_matrix( self, use_np_ordering: bool = False, n_dim: int = 3, use_inverse: bool = False, to_px_idx: bool = False, ) -> Optional[np.ndarray]: <NEW_LINE> <INDENT> if self.is_linear: <NEW_LINE> <INDENT> if use_np_ordering is True: <NEW_LINE> <INDENT> order = slice(None, None, -1) <NEW_LINE> <DEDENT> else: <NEW_LI... | Creates a affine transform matrix as np.ndarray whether the center of rotation
is 0,0. Optionally in physical or pixel coordinates.
Parameters
----------
use_np_ordering: bool
Use numpy ordering of yx (napari-compatible)
n_dim: int
Number of dimensions in the affine matrix, using 3 creates a 3x3 array
use_inver... | 625941d066673b3332b921f6 |
def cacheAndReturnNew(self,key, itemlist): <NEW_LINE> <INDENT> if isinstance(self._cache, _SimpleCache): <NEW_LINE> <INDENT> return self.cacheAndReturnNewP(key, itemlist) <NEW_LINE> <DEDENT> elif isinstance(self._cache, dbcache): <NEW_LINE> <INDENT> return self.cacheAndReturnNewD(itemlist) | wrapper to cache data function, depends on cache type | 625941d00a50d4780f666ff8 |
def with_sandbox(datapath=None): <NEW_LINE> <INDENT> def decorator(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def setup_and_teardown(*args, **kwargs): <NEW_LINE> <INDENT> sandbox_path, fullpath = setup_danger_zone(datapath) <NEW_LINE> r = fn(*args, sandbox=sandbox_path, path=fullpath, **kwargs) <NEW_LINE> teardown_... | Decorator that sets up and tears down a writable sandbox. | 625941d026068e7796caee44 |
def test_stream_attr(): <NEW_LINE> <INDENT> @as_subprocess <NEW_LINE> def child(): <NEW_LINE> <INDENT> assert TestTerminal().stream == sys.__stdout__ <NEW_LINE> <DEDENT> child() | Make sure Terminal ``stream`` is stdout by default. | 625941d0eab8aa0e5d26dcbd |
def exc_handler(typ: BaseException, exc: BaseException, tb: Any) -> None: <NEW_LINE> <INDENT> log.exception(f"Uncaught exception {exc}") <NEW_LINE> raise exc | Generic exception handling for uncaught exceptions to be logged. | 625941d0656771135c3eb9d4 |
def reset_url(self, url): <NEW_LINE> <INDENT> if self.memcache: <NEW_LINE> <INDENT> self._cache_reset(url) | Resets cache for URL
Args:
url: URL value | 625941d04428ac0f6e5ba958 |
def __init__(self, purchase_id, stock_symbol, purchase_price, current_price, shares, current_date, purchase_date): <NEW_LINE> <INDENT> self._purchase_id = purchase_id <NEW_LINE> self._stock_symbol = stock_symbol <NEW_LINE> try: <NEW_LINE> <INDENT> self._purchase_price = float(purchase_price) <NEW_LINE> <DEDENT> except ... | Assign values to stock attributes | 625941d0e76e3b2f99f3a96f |
def generate_samples(self, n_samples, class_label): <NEW_LINE> <INDENT> input_tensor = np.concatenate([sample_Z(n_samples, self.n_Z_features), sample_y(n_samples, self.n_y_features, class_label)], axis=1) <NEW_LINE> logits = output_logits_tensor(input_tensor, self.generator_layers, self.generator_parameters) <NEW_LINE>... | Generates n_samples number from the generator
conditioned on the class_label. | 625941d03cc13d1c6d3c74df |
def print_report(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> datas = {'ids': context.get('active_ids', [])} <NEW_LINE> res = self.read(cr, uid, ids, ['date_start', 'date_end', 'user_ids'], context=context) <NEW_LINE> res = res and res[0... | To get the date and print the report
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param context: A standard dictionary
@return : retrun report | 625941d0a8370b7717052a04 |
def catch_errors_and_exit(function): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return function() <NEW_LINE> <DEDENT> except RuntimeError as error: <NEW_LINE> <INDENT> print(error) <NEW_LINE> exit(1) | Run the function and return its output, catching errors and exiting if
one occurs. | 625941d030bbd722463cbf2b |
def thread_priority(self): <NEW_LINE> <INDENT> return _blocks_swig4.peak_detector_ib_sptr_thread_priority(self) | thread_priority(peak_detector_ib_sptr self) -> int | 625941d0187af65679ca5284 |
def grad(self, x): <NEW_LINE> <INDENT> g = np.zeros(x.shape) <NEW_LINE> g[0] = np.sign(x[0]) <NEW_LINE> g[1] = np.sign(x[1]) <NEW_LINE> return g | Grad function. | 625941d0e8904600ed9f2093 |
def benchmark_8_gpu_fp16_tweaked_layout_off(self): <NEW_LINE> <INDENT> self._setup() <NEW_LINE> FLAGS.num_gpus = 8 <NEW_LINE> FLAGS.dtype = 'fp16' <NEW_LINE> FLAGS.enable_eager = True <NEW_LINE> FLAGS.distribution_strategy = 'default' <NEW_LINE> FLAGS.model_dir = self._get_model_dir( 'benchmark_8_gpu_fp16_tweaked_layou... | Test Keras model with 8 GPUs, fp16,tuning, and layout off. | 625941d024f1403a92600cca |
def takeClosest(myList, myNumber): <NEW_LINE> <INDENT> pos = bisect_left(myList, myNumber) <NEW_LINE> if pos == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if pos == len(myList): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> before = myList[pos - 1] <NEW_LINE> after = myList[pos] <NEW_LINE> if after - myNum... | Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number. | 625941d030dc7b7665901acb |
def do_new(self,arg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.game.create_character() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print(str(err)) | Create a new character. | 625941d0b57a9660fec339e9 |
def process(self, text_input: str): <NEW_LINE> <INDENT> pass | Process string and return new string | 625941d0b57a9660fec339ea |
def computeQUI(distSXY, eps = 1e-7, DEBUG = False, IPmethod = "GIS", maxiter = 100000, maxiter2 = 100000): <NEW_LINE> <INDENT> QSXYd = distSXY.copy() <NEW_LINE> QSXYd.set_rv_names('SXY') <NEW_LINE> QSXYd.make_dense() <NEW_LINE> suppS = QSXYd.alphabet[0] <NEW_LINE> nS = len(suppS) <NEW_LINE> suppX = QSXYd.alphabet[1] <N... | Compute an optimizer Q
distSXY : A joint distribution of three variables (as a dit.Distribution).
eps : The precision of the outer loop. The precision of the inner loop will be eps / (20 |S|).
DEBUG : Print output for debugging.
The computation is carried out using computeQUI_numpy | 625941d060cbc95b062c66a9 |
def preprocessData(X, y, vocabulary): <NEW_LINE> <INDENT> featureList = mutualInformation(X, y, 10, vocabulary) <NEW_LINE> feature_index = [vocabulary[f] for f in featureList] <NEW_LINE> return X[:, feature_index], y | Runs mutual information and returns new design matrix X' | 625941d038b623060ff0af53 |
@pytest.mark.django_db <NEW_LINE> def test_cannot_approve_draft_state(): <NEW_LINE> <INDENT> article = mommy.make(Article) <NEW_LINE> assert article.state == State.draft <NEW_LINE> _ = article.send_to_editor() <NEW_LINE> assert article.state == State.waiting_for_editor <NEW_LINE> _ = article.send_back_to_author() <NEW_... | must be State.waiting_for_editor to be approved
| 625941d08c3a873295158521 |
def move(self, move_id: int) -> None: <NEW_LINE> <INDENT> if not self.root.is_evaluated(): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> return <NEW_LINE> <DEDENT> assert self.root_id < self.num_nodes, 'root node is unevaluated' <NEW_LINE> node = self.root.child(move_id) <NEW_LINE> if not node.is_evaluated(): <NEW_LINE> ... | Commit move and pick new root node.
Set new tree root to one of current root's child nodes.
Forget about ancestor and sibling nodes.
:param move_id: Action id of move that was made | 625941d0796e427e537b072c |
def _RecordInertiaInfoFromURDF(self): <NEW_LINE> <INDENT> self._link_urdf = [] <NEW_LINE> num_bodies = self._pybullet_client.getNumJoints(self.quadruped) <NEW_LINE> for body_id in range(-1, num_bodies): <NEW_LINE> <INDENT> inertia = self._pybullet_client.getDynamicsInfo(self.quadruped, body_id)[2] <NEW_LINE> self._link... | Record the inertia of each body from URDF file. | 625941d09c8ee82313fbb8db |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return FileResponse( id = 12345, deleted = True ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return FileResponse( ) | Test FileResponse
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941d024f1403a92600ccb |
def device_added(self, device): <NEW_LINE> <INDENT> if self._has_actions('device_added'): <NEW_LINE> <INDENT> GLib.timeout_add(500, self._device_added, device) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._device_added(device) | Show 'Device added' notification.
:param device: device object | 625941d0be7bc26dc91cd764 |
def add_store(self): <NEW_LINE> <INDENT> with open("stores_locations.csv", encoding="utf-8") as stores: <NEW_LINE> <INDENT> reader = csv.reader(stores) <NEW_LINE> next(reader, None) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> Store.objects.create( name_store=row[0], latitude=row[1], longitude=row[2],) | Add store in the Store's table from a csv file | 625941d03d592f4c4ed1d1d2 |
def trigram(): <NEW_LINE> <INDENT> text=readfile() <NEW_LINE> tr = str.maketrans("", "", string.punctuation) <NEW_LINE> cleaned_text=text.translate(tr) <NEW_LINE> words=cleaned_text.split() <NEW_LINE> create_trigram(words) <NEW_LINE> print_trigram() | Creates triagram from text | 625941d0627d3e7fe0d68fb6 |
def test_serialize(self): <NEW_LINE> <INDENT> self.anno.class_label = 'person' <NEW_LINE> self.anno.x_top_left = 35 <NEW_LINE> self.anno.y_top_left = 30 <NEW_LINE> self.anno.width = 30 <NEW_LINE> self.anno.height = 40 <NEW_LINE> string = self.anno.serialize( self.class_label_map, self.image_width, self.image_height ) <... | test if serialization of one annotation works | 625941d0d268445f265b4fd3 |
def set_RadioStation(self, value): <NEW_LINE> <INDENT> super(UpdateListenInputSet, self)._set_input('RadioStation', value) | Set the value of the RadioStation input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing representing a radio station.) | 625941d0bd1bec0571d90795 |
def process_manual_select_product(): <NEW_LINE> <INDENT> return q.process.manual_select_product() | :menu: (enable=True, name=LOAD PRODUCT, section=UUT, num=1.1, args={}) | 625941d063f4b57ef000127e |
def test_reschedule(self): <NEW_LINE> <INDENT> db, conf, web, tmpdir = setup_webservice() <NEW_LINE> runjobdir = add_running_job(db, 'reschedule', completed=True) <NEW_LINE> web._process_completed_jobs() <NEW_LINE> job = web.get_job_by_name('RUNNING', 'reschedule') <NEW_LINE> jobdir = os.path.join(conf.directories['RUN... | Check rescheduling of jobs | 625941d07cff6e4e81117aeb |
def get_expenseClass(self, expenseClassesId: str): <NEW_LINE> <INDENT> return self.call("GET", f"/finance/expense-classes/{expenseClassesId}") | Retrieve expenseClass item with given {expenseClassId}
``GET /finance/expense-classes/{expenseClassesId}``
Args:
expenseClassesId (str)
Returns:
dict: See Schema below
Raises:
OkapiRequestNotFound: Not Found
OkapiFatalError: Server Error
Schema:
.. literalinclude:: ../files/ExpenseClasses_get_... | 625941d0293b9510aa2c33fb |
def get_choke_point_matches(query_graph, target_graph, choke_point, vertex_candidates=None): <NEW_LINE> <INDENT> if vertex_candidates is None: <NEW_LINE> <INDENT> vertex_candidates = nx_graph.get_vertex_candidates(query_graph, target_graph) <NEW_LINE> <DEDENT> if any([len(vc) == 0 for vc in vertex_candidates]): <NEW_LI... | Return the vertices from target that match the choke point vertex
from query.
Arguments:
query_graph:
target_graph:
choke_point:
Returns:
Vertices from target_graph that correspond to the choke point
vertex from query_graph. | 625941d0be8e80087fb20da8 |
def check(self): <NEW_LINE> <INDENT> import check <NEW_LINE> check.check_hamiltonian(self) | Checks if the Hamiltonian is hermitic | 625941d08e05c05ec3eea4db |
def testHorizontalProfile(self): <NEW_LINE> <INDENT> roiManager = self.manager.getRoiManager() <NEW_LINE> self.plot.addScatter( x=(0., 1., 1., 0.), y=(0., 0., 1., 1.), value=(0., 1., 2., 3.)) <NEW_LINE> self.plot.resetZoom(dataMargins=(.1, .1, .1, .1)) <NEW_LINE> self.qapp.processEvents() <NEW_LINE> roi = rois.ProfileS... | Test ScatterProfileToolBar horizontal profile | 625941d0004d5f362079a498 |
def post_put_delete(cursor, pk, table_name, **kwargs): <NEW_LINE> <INDENT> pk_name = "entity_id" if table_name == "company" else "id" <NEW_LINE> method = request.method <NEW_LINE> method_str = METHODS[method].format(table_name) <NEW_LINE> query_parts = [method_str] <NEW_LINE> params = [] <NEW_LINE> if method in ('PUT',... | Create, update or delete a record. | 625941d04527f215b584c5bc |
def decrypt_letter(charachter, keystream): <NEW_LINE> <INDENT> upper_case = charachter.upper() <NEW_LINE> numerical_charachter = (ord(upper_case) - ord('A')) <NEW_LINE> if ((numerical_charachter - keystream) >= 0): <NEW_LINE> <INDENT> Decryptchar = (numerical_charachter - keystream) <NEW_LINE> <DEDENT> else: <NEW_LINE>... | (str, int)->str
Takes in a charachter and string value and will decrypt the result
REQ: letter should be string
REQ: int must be between 0 and 26
REQ: Char first, then number
>>>decrypt_letter('A', 9)
'R'
>>>decrypt_letter('D', 25)
'E'
>>>decrypt_letter('Z', 29)
'W' | 625941d0656771135c3eb9d5 |
def noise_net_model(): <NEW_LINE> <INDENT> inp = Input(shape=(NUM_CHANNELS, IMG_SIZE, IMG_SIZE)) <NEW_LINE> x = Conv2D(32, (3, 3), activation='relu', padding='same', kernel_regularizer=regularizers.l2(LAMBDA_REG))(inp) <NEW_LINE> x = Conv2D(32, (3, 3), activation='relu', kernel_regularizer=regularizers.l2(LAMBDA_REG))(... | NoiseNet model
:return: model | 625941d03eb6a72ae02ec645 |
def configurable(init_func): <NEW_LINE> <INDENT> assert init_func.__name__ == "__init__", "@configurable should only be used for __init__!" <NEW_LINE> @functools.wraps(init_func) <NEW_LINE> def wrapped(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from_config_func = type(self).from_config <NEW_LI... | Decorate a class's __init__ method so that it can be called with a CfgNode
object using the class's from_config classmethod.
Examples:
.. code-block:: python
class A:
@configurable
def __init__(self, a, b=2, c=3):
pass
@classmethod
def from_config(cls, cfg):
... | 625941d00fa83653e4657120 |
def get_contig_coverage(aligns, end_to_end=False): <NEW_LINE> <INDENT> span = intspan('{}-{}'.formt(aligns[0].qstart, aligns[0].qend)) <NEW_LINE> for i in range(1, len(aligns)): <NEW_LINE> <INDENT> span = span.union(intspan('{}-{}'.format(aligns[i].qstart, aligns[i].qend))) <NEW_LINE> <DEDENT> if not end_to_end: <NEW_L... | Coverage of the contig by the union of the primary_aligns alignments
Args:
aligns: (list) All Alignments constituting a chimera
Returns:
Fraction corresponding to coverage | 625941d045492302aab5e429 |
def inverseJoin(self): <NEW_LINE> <INDENT> bd = self.boundary <NEW_LINE> v = self.vertices <NEW_LINE> if (bd, v) not in self.__class__.joinLookup: <NEW_LINE> <INDENT> nonBoundaryVertices = self.vertices - self.boundaryVertices <NEW_LINE> separatorLookup = self.__class__.separatorLookup <NEW_LINE> bv = self.boundaryVert... | Return all pattern pairs whose joins give this pattern | 625941d04a966d76dd551175 |
def search_artist(name): <NEW_LINE> <INDENT> name = re.sub(r"\b([A-Za-z]) ", r"\1. ", name) <NEW_LINE> name = re.sub("((?<=[A-Za-z]\.)) ([A-Za-z]\.)", r"\1\2", name) <NEW_LINE> url = "http://kutcheris.com/directory_art.php?search=%s" % name <NEW_LINE> r = requests.get(url) <NEW_LINE> b = bs4.BeautifulSoup(r.text) <NEW_... | Search for an artist name.
Return a map of matching results -> artist id
remove spaces between initials, e.g., M. S. Subbulakshmi -> M.S. Subbulakshmi | 625941d0d18da76e2353263c |
def choose_photo_URL(photo): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = photo['url_l'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = photo['url_z'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = photo['url_c'] <NEW_LINE> <DEDENT>... | Choose most suitable url of photo or None if photo too small.
photo - Photo instance | 625941d04d74a7450ccd4329 |
def get_visualization_shorthand(self): <NEW_LINE> <INDENT> message = ('visualization.get_visualization_shorthand needs ' 'to be overridden by child class.') <NEW_LINE> raise NotImplementedError(message) | Returns the shorthand for this output type
Abstract method that needs to be overridden in child classes. | 625941d0e64d504609d749a5 |
def reduce_armor(self, amount): <NEW_LINE> <INDENT> bees_copy = self.place.bees[:] <NEW_LINE> super().reduce_armor(amount) <NEW_LINE> if self.armor <= 0: <NEW_LINE> <INDENT> [bee.reduce_armor(self.damage + amount) for bee in bees_copy] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> [bee.reduce_armor(amount) for bee in b... | Reduce armor by AMOUNT, and remove the FireAnt from its place if it
has no armor remaining.
Make sure to damage each bee in the current place, and apply the bonus
if the fire ant dies. | 625941d0c432627299f04dac |
def test_pandas_builtin_datetime_parser(self): <NEW_LINE> <INDENT> timer.start() <NEW_LINE> df = pd.read_csv(r"testdata\bigcsvfile.txt", usecols=[3,4], parse_dates=[0,1]) <NEW_LINE> [i.to_datetime().date() for i in df["CREATE_DATE"]] <NEW_LINE> [i.to_datetime() for i in df["CREATE_DATETIME"]] <NEW_LINE> timer.timeup() ... | 验证pandas built-in的date parser的和自定义的timewrapper的性能
注意: 数据库不接受pandas.tslib.timestamp作为时间格式输入
结论: 用timewrapper比较好
对于标准格式 "2014-01-01" 和 "2014-01-01 18:00:00"来说, pandas比较快。这是因为
pandas也内置了一系列的日期格式模板, 然后pandas按顺序一个个试验。由于标准模板是
第一个, 所以速度较快。而比较冷僻的格式, 则每次pandas都需试错多次后才能成功。
而TimeWrapper能在试验成功后, 将成功的模板作为之后的默认模板。所... | 625941d0e5267d203edcde02 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.