code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_iris_classifier(): <NEW_LINE> <INDENT> iris = datasets.load_iris() <NEW_LINE> model = SparsemaxRegression( input_size=4, output_size=3, regualizer=1e-1, learning_rate=1e-2 ) <NEW_LINE> tester = ModelTest(model, iris, random_state=42, verbose=False) <NEW_LINE> tester.test(loss=0.2, missrate=0.1)
check sparsemax regression on the iris dataset
625941d89f2886367277ab0c
def findfactor(x): <NEW_LINE> <INDENT> factor = 2 <NEW_LINE> while factor <= math.sqrt(x): <NEW_LINE> <INDENT> if x%factor == 0: <NEW_LINE> <INDENT> return [factor, x / factor] <NEW_LINE> <DEDENT> factor += 1 <NEW_LINE> <DEDENT> return [1, x]
finds first factor pair of x Tests: >>> findfactor(15) [3, 5] >>> findfactor(20) [2, 10] >>> findfactor(5) [1, 5]
625941d84e696a04525c96cc
def docker_host_required(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> if args[0].type != HOST_DOCKER: <NEW_LINE> <INDENT> raise Exception("Not docker host") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return wrapp...
装饰器,必须要求 host 类型是 HOST_DOCKER
625941d8a05bb46b383ecaa1
def _getSession(self) -> Optional[Session]: <NEW_LINE> <INDENT> request = self._request <NEW_LINE> sessionID = request.getCookie(self.sessionCookieName) <NEW_LINE> if sessionID is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return request.site.getSession(sessionID) <NEW_LINE> <DED...
Returns the active session on the given Twisted request object, or None if there is no active session.
625941d84f6381625f114cbc
def _update_times(self): <NEW_LINE> <INDENT> t = time.time() <NEW_LINE> if self.last_run_time: <NEW_LINE> <INDENT> self.delta_time = t - self.last_run_time <NEW_LINE> <DEDENT> self.last_run_time = t
Called every time run() completes. We record stuff here to monitor how our providers are performing.
625941d8ac7a0e7691ed4349
def rabin_karp(txt, pat): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> hy = 0 <NEW_LINE> hx = 0 <NEW_LINE> n = len(txt) <NEW_LINE> m = len(pat) <NEW_LINE> if m > n: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> d = 1 << m - 1 <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> hx = (hx << 1) + ord(pat[i]) <NEW_LINE> h...
Returns list of indices in text string which matches given pattern.
625941d830bbd722463cc048
def BuildAndPushDockerImages(module_configs, version_id, cloudbuild_client, http, code_bucket, cli, remote, source_contexts, config_cleanup): <NEW_LINE> <INDENT> project = properties.VALUES.core.project.Get(required=True) <NEW_LINE> use_cloud_build = properties.VALUES.app.use_cloud_build.GetBool() <NEW_LINE> modules = ...
Builds and pushes a set of docker images. Args: module_configs: A map of module name to parsed config. version_id: The version id to deploy these modules under. cloudbuild_client: An instance of the cloudbuild.CloudBuildV1 api client. http: a http provider that can be used to create API clients code_bucket: ...
625941d87d847024c06be53f
def scores( root: Path, accessions: Iterable[str], plot_type: str, ): <NEW_LINE> <INDENT> dfs = [] <NEW_LINE> for acc in accessions: <NEW_LINE> <INDENT> fp = root / acc / "scores.csv" <NEW_LINE> if not fp.exists(): <NEW_LINE> <INDENT> print(f"{fp} not found.") <NEW_LINE> continue <NEW_LINE> <DEDENT> tmp = pd.read_csv(f...
Scores plot.
625941d8627d3e7fe0d690d2
def perform_request(self): <NEW_LINE> <INDENT> fs_url = self._resource.url.split('?')[0] <NEW_LINE> req_tpl = { 'fs_caps': fs_url + '?f=json', 'layer_caps': fs_url + '/%d?f=json', 'get_features': fs_url + '/%d/query?where=1=1' '&outFields=*&resultOffset=0&' 'resultRecordCount=1&f=json', 'get_feature_by_id': fs_url + '/...
Perform the drilldown.
625941d82ae34c7f2600d3b1
def _send_ankiconnect_request(self, http_method, payload, error_message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.request( http_method, "http://localhost:8765", json=payload) <NEW_LINE> if response.status_code != 200: <NEW_LINE> <INDENT> raise requests.exceptions.HTTPError( f"Request returned n...
Handler for sening multiple types of requests to the AnkiConnect API. Args: http_method (str): The HTTP method to be used (typically either 'GET' or 'POST'). payload (dict): The JSON to be sent to the AnkiConnect API. error_message (str): A request-specific message to be included in any exceptions. Raises...
625941d8d7e4931a7ee9e19e
def spawn(self): <NEW_LINE> <INDENT> items = [item for item in self.buf] <NEW_LINE> self.buf = [] <NEW_LINE> super(BulkItemsPool, self).add_handler(items)
Spawn an action for everything in self.buf and clear self.buf
625941d885dfad0860c3b0dc
def n_rolls(count, n): <NEW_LINE> <INDENT> if n == "F": <NEW_LINE> <INDENT> return [random.randint(-1, 1) for _ in range(min(count, 100))] <NEW_LINE> <DEDENT> if n < 2: <NEW_LINE> <INDENT> if count < 100: <NEW_LINE> <INDENT> return [random.randint(0, 1) for _ in range(count)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
roll an n-sided die count times :type count: int :type n: int | str
625941d8a8ecb033257d334d
def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs): <NEW_LINE> <INDENT> emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) <NEW_LINE> model = TabularModel(emb_szs, len(d...
Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params.
625941d815fb5d323cde0d93
def findFilesInDir(directory, extension): <NEW_LINE> <INDENT> foundFiles = [] <NEW_LINE> filenames = os.listdir(directory) <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> if filename[-len(extension):] == extension: <NEW_LINE> <INDENT> foundFiles.append(directory + '/' + filename) <NEW_LINE> <DEDENT> <DEDENT> ...
function that searches the specified 'directory' for files with the supplied extention. The function returns a list of these files.
625941d8d7e4931a7ee9e19f
def test_shape(self): <NEW_LINE> <INDENT> rproc = RandomProcess(self.mean, self.var) <NEW_LINE> self.assertEqual(rproc.shape(), 3)
Test shape
625941d8925a0f43d254a0f9
def post_multipart(self, host, selector, fields, files): <NEW_LINE> <INDENT> content_type, body = self.encode_multipart_formdata(fields, files) <NEW_LINE> h = http.client.HTTP(host) <NEW_LINE> h.putrequest('POST', selector) <NEW_LINE> h.putheader('content-type', content_type) <NEW_LINE> h.putheader('content-length', st...
Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page.
625941d8711fe17d825425e7
def write(self, message): <NEW_LINE> <INDENT> self.terminal.write(message) <NEW_LINE> if self.log: <NEW_LINE> <INDENT> self.log.write(message)
Write messages to terminals and files :param message: :return:
625941d810dbd63aa1bd2e23
@app.route('/api/validate-email', methods=['POST']) <NEW_LINE> def validate_email(): <NEW_LINE> <INDENT> email = request.get_json()["email"].strip() <NEW_LINE> if not EmailValidator.is_syntax_valid(email): <NEW_LINE> <INDENT> response = EmailValidatorResponse(False, "Address syntax invalid") <NEW_LINE> <DEDENT> elif no...
:param email: string the address to be validates :return: response: EmailValidatorResponse success status and message Read more at https://github.com/mariodmtrv/RobustMail/wiki#check-an-email
625941d830bbd722463cc049
def _destroy_auth_token(self, user=None): <NEW_LINE> <INDENT> Token.objects.get(user) <NEW_LINE> return token
Destroys api Token for the current user
625941d83346ee7daa2b2fee
def has(self, key): <NEW_LINE> <INDENT> msg = bluzelle_pb2.bzn_msg() <NEW_LINE> msg.db.has.key = key <NEW_LINE> resp = self._send_request(self._host, self._port, msg) <NEW_LINE> return resp.resp.has
Create a new K/V :param key: Key to test :return: true if key exists
625941d830dc7b7665901be5
def is_empty_column(self, c): <NEW_LINE> <INDENT> return uniq(self.column(c)) == [-1]
Checks if column c of the partial latin square self is empty. EXAMPLES:: sage: from sage.combinat.matrices.latin import * sage: L = back_circulant(4) sage: L.is_empty_column(0) False sage: L[0,0] = L[1,0] = L[2,0] = L[3,0] = -1 sage: L.is_empty_column(0) True
625941d863f4b57ef0001394
def test_pass_exist(self): <NEW_LINE> <INDENT> self.new_password.save_pass() <NEW_LINE> self.assertTrue(Password.password_exist("Facebook"))
This test will check whether the password_exists function works
625941d81d351010ab855d9c
def testStringLen(self): <NEW_LINE> <INDENT> s = ExtendedString("string of size 17") <NEW_LINE> assert len(s) == 17
testear que len(ExtendedString("string of size 17") funciona y devuelve 17
625941d892d797404e30440c
def _check_state_available(self): <NEW_LINE> <INDENT> if not self._first_error_timestamp: <NEW_LINE> <INDENT> self._first_error_timestamp = dt_util.utcnow() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tdelta = dt_util.utcnow() - self._first_error_timestamp <NEW_LINE> if tdelta.total_seconds() >= 60: <NEW_LINE> <INDEN...
Set to unavailable if issue been occurring over 1 minute.
625941d823849d37ff7b330f
def get_greatest(number_list:list) -> int : <NEW_LINE> <INDENT> greatest_number = max(number_list) <NEW_LINE> return greatest_number
주어진 리스트에서 가장 큰 숫자를 반환함 Parameters: number_list (list): integer로 값으로만 구성된 list ex - [10, 33, 22, 99, 33] Returns: greatest_number (int): parameter number_list 중 가장 큰 값 Examples: >>> number_list = [39, 54, 32, 11, 99] >>> import basic_math as bm >>> bm.get_gr...
625941d85fc7496912cc3bff
@hooks.hook('admin-relation-joined') <NEW_LINE> def admin(): <NEW_LINE> <INDENT> hookenv.log('Starting the admin-relation-joined hook.') <NEW_LINE> admin_port = '8500' <NEW_LINE> private_address = hookenv.unit_private_ip() <NEW_LINE> ui_url = 'http://{0}:{1}/ui'.format(private_address, admin_port) <NEW_LINE> hookenv.re...
The admin relation gives other charms the hostname, port and url of the HTTP administrator interface for Consul.
625941d8091ae356686671dc
@with_session <NEW_LINE> def get_user_group(username, session): <NEW_LINE> <INDENT> if username is not None: <NEW_LINE> <INDENT> actor_id = get_user_id_from_name(username, session=session) <NEW_LINE> group = (session .query(GroupMembership.group) .filter(GroupMembership.touch_id == Touch.id) .filter(Touch.actor_id == a...
Get the group associated with a given username.
625941d8bde94217f3683070
def PostProcessMRIGraph(graph, upper_distance=7.0, k=5): <NEW_LINE> <INDENT> pos_all=np.array(graph.GetNodesPos()) <NEW_LINE> nodes_all=graph.GetNodes() <NEW_LINE> graphs=list(nx.connected_component_subgraphs(graph)) <NEW_LINE> nodes=[i.GetNodes() for i in graphs] <NEW_LINE> end_nodes=[i.GetJuntionNodes(bifurcation=[0,...
This function reconnect seperated segments of MRI graph
625941d8d53ae8145f87a4ed
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DatasetCreateRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941d838b623060ff0b06f
def clone(self) -> "simuPOP::BaseOperator *": <NEW_LINE> <INDENT> return _simuPOP_linop.BaseOperator_clone(self)
Usage: x.clone() Details: Return a cloned copy of an operator. This function is available to all operators.
625941d832920d7e50b28453
def process_input(): <NEW_LINE> <INDENT> if len(sys.argv) < 2: <NEW_LINE> <INDENT> vm_directory(None) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_input = sys.argv[1] <NEW_LINE> <DEDENT> base_idx = len(user_input) - 3 <NEW_LINE> if user_input[base_idx:] in ('.vm', '.VM'): <NEW_LINE> <INDENT> fil...
decide the mode based on input
625941d83317a56b86939ed4
def test__api_normalizeurl_widgets_rightasc(self): <NEW_LINE> <INDENT> new_slugs = dict(self.default_url_slugs) <NEW_LINE> url = '/__normalizeurl.json?widgets=rightasc' <NEW_LINE> new_slugs['widgets'] = 'rightasc' <NEW_LINE> self._run_url_slugs_equal(url, new_slugs)
[test_ui_api.py] /__normalizeurl: widgets rightasc
625941d8d164cc6175782fd0
def save_veg_parms(cells, filename): <NEW_LINE> <INDENT> with open(filename, 'w') as f: <NEW_LINE> <INDENT> writer = csv.writer(f, delimiter=' ') <NEW_LINE> for cell_id, cell in cells.items(): <NEW_LINE> <INDENT> writer.writerow( [ cell_id, sum([band.num_hrus for band in cell.bands]) ] ) <NEW_LINE> for band_id, band in...
Writes the vegetation parameters out to a file of the same format as the original vegetation parameters file.
625941d807d97122c4178b11
def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete()
Deletes the ConnectAppInstance :returns: True if delete succeeds, False otherwise :rtype: bool
625941d8a219f33f34628be8
def save_state_to_str(config): <NEW_LINE> <INDENT> if not config: <NEW_LINE> <INDENT> raise ValueError("Invalid config") <NEW_LINE> <DEDENT> value = None <NEW_LINE> try: <NEW_LINE> <INDENT> string_f = StringIO() <NEW_LINE> config.write(string_f) <NEW_LINE> value = string_f.getvalue() <NEW_LINE> <DEDENT> except: <NEW_LI...
Convert from ConfigParser to String
625941d844b2445a33932316
def make_conn(args): <NEW_LINE> <INDENT> client = MongoClient(args.mongo_conn) <NEW_LINE> database = client.event_scrape <NEW_LINE> collection = database['news_stories'] <NEW_LINE> return collection
Function to establish a connection to a local MonoDB instance. Returns ------- collection: pymongo.collection.Collection. Collection within MongoDB that holds the scraped news stories.
625941d860cbc95b062c67c5
def remaining(self, attempts, last_attempt): <NEW_LINE> <INDENT> if attempts == 0 or last_attempt is None: <NEW_LINE> <INDENT> return self.zero <NEW_LINE> <DEDENT> return max(self.delta(attempts) - self.elapsed(last_attempt), self.zero)
Get the time delta remaining for the current backoff period relative to the last_attempt.
625941d8d99f1b3c44c6780d
def fit(self, X, y): <NEW_LINE> <INDENT> self.w_ = np.zeros(1+X.shape[1]) <NEW_LINE> self.errors_ = [] <NEW_LINE> for _ in range(self.n_iter): <NEW_LINE> <INDENT> errors = 0 <NEW_LINE> for xi, target in zip(X,y): <NEW_LINE> <INDENT> update = self.eta * (target - self.predict(xi)) <NEW_LINE> self.w_[1:] += update * xi <...
Fit training data. Parameters ---------- X: {array-like}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y: array-like, shape = [n_samples] Target values. Returns ------- self: object
625941d866656f66f7cbc42e
def get_all_groups(self): <NEW_LINE> <INDENT> return self.groups + ['all']
Return saved groups and special group 'all'
625941d826238365f5f0f0f3
def numTrees(self, n): <NEW_LINE> <INDENT> return (int(Solution.nCr(2*n,n)/(n + 1)))
:type n: int :rtype: int
625941d8a17c0f6771cbe2d1
def __on_item_toggled(self, view, path): <NEW_LINE> <INDENT> iterator = self.__model.get_iter(path) <NEW_LINE> toggle = not self.__model.get_value(iterator, 0) <NEW_LINE> self.__model.set_value(iterator, 0, toggle) <NEW_LINE> album_id = self.__model.get_value(iterator, 2) <NEW_LINE> self.__populate_albums_playlist(albu...
When item is toggled, set model @param widget as cell renderer @param path as str representation of Gtk.TreePath
625941d88a43f66fc4b542e4
def MASE(training_series, testing_series, prediction_series): <NEW_LINE> <INDENT> n = training_series.shape[0] <NEW_LINE> d = np.abs( np.diff( training_series) ).sum()/(n-1) <NEW_LINE> errors = np.abs(testing_series - prediction_series ) <NEW_LINE> return errors.mean()/d
Computes the MEAN-ABSOLUTE SCALED ERROR forcast error for univariate time series prediction. See "Another look at measures of forecast accuracy", Rob J Hyndman parameters: training_series: the series used to train the model, 1d numpy array testing_series: the test series to predict, 1d numpy array or float ...
625941d8097d151d1a2230d9
def get_c2d_topic_for_subscribe(device_id, module_id): <NEW_LINE> <INDENT> return _get_topic_base(device_id, module_id) + "/messages/devicebound/#"
:return: The topic for cloud to device messages.It is of the format "devices/<deviceid>/messages/devicebound/#"
625941d8851cf427c661a78e
def undo(): <NEW_LINE> <INDENT> pass
undo() -> None Perform the most recent undo. @return: None
625941d855399d3f05588936
def test_conjugate_l1norm(): <NEW_LINE> <INDENT> l1 = rr.l1norm(4, lagrange=0.3) <NEW_LINE> v1=rr.smooth_conjugate(l1, rr.identity_quadratic(0.3,None,None,0)) <NEW_LINE> v2 = rr.conjugate(l1, rr.identity_quadratic(0.3,None,None,0), tol=1.e-12) <NEW_LINE> w=np.random.standard_normal(4) <NEW_LINE> u11, u12 = v1.smooth_ob...
this test verifies that numerically computing the conjugate is essentially the same as using the smooth_conjugate of the atom
625941d807f4c71912b11705
def get_kl(self): <NEW_LINE> <INDENT> return - 0.5 * tf.reduce_sum( 1.0 + 2.0 * self.z_log_sigma - tf.square(self.z_mu) - tf.exp(2.0 * self.z_log_sigma), 1)
d_kl(q(z|x)||p(z)) returns the KL-divergence between the prior p and the variational posterior q. :return: KL divergence between q and p
625941d86aa9bd52df037026
def test_broken_pipe_errors(self): <NEW_LINE> <INDENT> request = WSGIRequest(self.request_factory.get('/').environ) <NEW_LINE> client_address = ('192.168.2.0', 8080) <NEW_LINE> msg = f'- Broken pipe from {client_address}\n' <NEW_LINE> tests = [ BrokenPipeError, ConnectionAbortedError, ConnectionResetError, ] <NEW_LINE>...
WSGIServer handles broken pipe errors.
625941d8435de62698dfdecf
def benchmark( self, num_calling_threads=1, num_warmup_iters=10, num_iters=100, profiler_output_path=""): <NEW_LINE> <INDENT> config = torch._C.BenchmarkConfig() <NEW_LINE> config.num_calling_threads = num_calling_threads <NEW_LINE> config.num_warmup_iters = num_warmup_iters <NEW_LINE> config.num_iters = num_iters <NEW...
Args: num_warmup_iters (int): Warmup iters are used to make sure we run a module a few times before actually measuring things. This way we avoid cold caches and any other similar problems. This is the number of warmup iterations for each of the thread in separate num_iters (int): Number...
625941d85fcc89381b1e1943
def test_push_function_defaults(self): <NEW_LINE> <INDENT> def echo(a=10): <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> v = self.client[-1] <NEW_LINE> v.block=True <NEW_LINE> v['f'] = echo <NEW_LINE> v.execute('b=f()') <NEW_LINE> self.assertEqual(v['b'], 10)
test that pushed functions preserve default args
625941d8bd1bec0571d908b1
def findNearestVLBISources(self, radecString, radius=3, catalog='rfc_2014b_cat.txt', returnDictionary=False, verbose=True): <NEW_LINE> <INDENT> if (not os.path.exists(catalog)): <NEW_LINE> <INDENT> print("Downloading catalog %s from astrogeo.org" % catalog) <NEW_LINE> if '/opt/local/bin' not in os.environ['PATH']: <NEW...
Reads the current VLBI catalog and finds all sources within specified radius. Downloads the file first, if necessary, using wget. radius: search radius (in degrees) returnDictionary: if True, then return dictionary keyed by source name with value equal to the separation (in degrees). Otherwise, return simple list of...
625941d8046cf37aa974cfc8
def _with_optional_from( value: typing.Any, ref: str, target: some.graph.WithOptional, errors: some.graph.parse.Errors ) -> None: <NEW_LINE> <INDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> errors.add( ref, "Expected a dictionary, but got: {}".format( type(value))) <NEW_LINE> return <NEW_LINE> <DEDENT> valu...
parses WithOptional from a JSONable value. If ``errors``, the attributes of ``target`` have undefined values. :param value: JSONable value :param ref: reference to the value (e.g., a reference path) :param target: parsed ``value`` as WithOptional :param errors: errors encountered during parsing :return:
625941d8460517430c394402
def redefined_by_decorator(node): <NEW_LINE> <INDENT> if node.decorators: <NEW_LINE> <INDENT> for decorator in node.decorators.nodes: <NEW_LINE> <INDENT> if (isinstance(decorator, astng.Getattr) and getattr(decorator.expr, 'name', None) == node.name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT...
return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value
625941d807f4c71912b11706
def flatten_dict(d, parent_key=''): <NEW_LINE> <INDENT> items = [] <NEW_LINE> for k, v in d.items(): <NEW_LINE> <INDENT> new_key = parent_key + '.' + k if parent_key else k <NEW_LINE> if isinstance(v, collections.MutableMapping): <NEW_LINE> <INDENT> items.extend(list(flatten_dict(v, new_key).items())) <NEW_LINE> <DEDEN...
Flatten a nested dictionary. Converts a dictionary with nested values to a single level flat dictionary, with dotted notation for each key.
625941d8293b9510aa2c3515
def deserialize(self, data): <NEW_LINE> <INDENT> vals = collections.deque(data.split()) <NEW_LINE> def build_tree(): <NEW_LINE> <INDENT> val = vals.popleft() <NEW_LINE> if val != 'null': <NEW_LINE> <INDENT> node = TreeNode(int(val)) <NEW_LINE> node.left = build_tree() <NEW_LINE> node.right = build_tree() <NEW_LINE> ret...
Decodes your encoded data to tree. :type data: str :rtype: TreeNode
625941d8dd821e528d63b42a
def get_url_for_download(self, asset_id, timeout): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tags = self.client.get_object_tagging( Bucket=self.config.bucket, Key=asset_id) <NEW_LINE> uploaded = False <NEW_LINE> if tags: <NEW_LINE> <INDENT> for tag in tags['TagSet']: <NEW_LINE> <INDENT> key = tag.get('Key') <NEW_LIN...
Return URL for download if the asset is ready, None otherwise.
625941d8a934411ee3751916
def select_actions(self, states, explore=False): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> if self.centralized: <NEW_LINE> <INDENT> rand = np.random.uniform() <NEW_LINE> <DEDENT> for i, state in enumerate(states): <NEW_LINE> <INDENT> if not self.centralized: <NEW_LINE> <INDENT> rand = np.random.uniform() <NEW_LINE> <...
:param states: List of the agent states :return: actions for each agent
625941d8a05bb46b383ecaa2
def time_08_3(self): <NEW_LINE> <INDENT> for ii in range(self.no_runs): <NEW_LINE> <INDENT> rle_encode_frame(self.arr8_3)
Time encoding 8 bit 3 sample/pixel.
625941d857b8e32f5248371e
def build_method_map(self, prototype, prefix=''): <NEW_LINE> <INDENT> if not isinstance(prototype, dict): <NEW_LINE> <INDENT> prototype = dict((method, getattr(prototype, method)) for method in dir(prototype) if not method.startswith('_')) <NEW_LINE> <DEDENT> for attr, method in prototype.items(): <NEW_LINE> <INDENT> i...
Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all public methods will be used. prefix: string, optional ...
625941d8c432627299f04ec9
def __getitem__(self, index): <NEW_LINE> <INDENT> captions_path = self.captions_path <NEW_LINE> root = self.root <NEW_LINE> vocab = self.vocab <NEW_LINE> all_captions = [line.rstrip('\n') for line in open(captions_path)] <NEW_LINE> all_openpose_files = sorted(os.listdir(root)) <NEW_LINE> vocab_dictionary = {} <NEW_LINE...
Returns one data pair (image and caption).
625941d83346ee7daa2b2fef
@api.route('/module/find', methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> def find_model(): <NEW_LINE> <INDENT> data = request.json <NEW_LINE> page = data.get('page') if data.get('page') else 1 <NEW_LINE> per_page = data.get('sizePage') if data.get('sizePage') else 10 <NEW_LINE> project_name = data.get('projec...
查找接口模块
625941d801c39578d7e750be
@recorder.use_cassette('top_level_cat') <NEW_LINE> def test_catalog_ref_order(): <NEW_LINE> <INDENT> url = 'http://thredds.ucar.edu/thredds/catalog.xml' <NEW_LINE> cat = TDSCatalog(url) <NEW_LINE> assert list(cat.catalog_refs) == ['Forecast Model Data', 'Forecast Products and Analyses', 'Observation Data', 'Radar Data'...
Test that catalog references are properly ordered.
625941d826068e7796caef64
def getListOfIntParams(self, sName, iMin = None, iMax = None, aiDefaults = None): <NEW_LINE> <INDENT> if sName in self._dParams: <NEW_LINE> <INDENT> if sName not in self._asCheckedParams: <NEW_LINE> <INDENT> self._asCheckedParams.append(sName); <NEW_LINE> <DEDENT> if isinstance(self._dParams[sName], list): <NEW_LINE> <...
Gets parameter list. Raises exception if not found and aiDefaults is None, or if any of the values are not valid integers or outside the range defined by iMin and iMax.
625941d8cb5e8a47e48b7d29
def check_flush(cards): <NEW_LINE> <INDENT> return len(set(map(lambda x: x[1], cards))) == 1
Check is all the cards are of the same suit :param cards: List of Cards dealt to a player :return: True when all the cards are of the same suit False otherwise
625941d88a43f66fc4b542e5
def read_table(filename): <NEW_LINE> <INDENT> table = [] <NEW_LINE> item_list = [] <NEW_LINE> infile = open(filename, "r") <NEW_LINE> lines = infile.readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> values = line.split(",") <NEW_LINE> strip_quotation_marks_list(values) <NEW_LI...
reads file and converts it to a 2D list parameter filename is the file containing a comma separated dataset to be read returns 2D list containing rows from file
625941d8f9cc0f698b14087c
def calculateTwitterUserFeatures(df): <NEW_LINE> <INDENT> mean_and_median = ["mean", "median"] <NEW_LINE> user_stats = df.groupby("root_user").agg( { "breadth_max": mean_and_median, "depth_max": mean_and_median, "first_level_comments": mean_and_median, "lifetime": mean_and_median, "size": mean_and_median + ["sum"], "re...
Apply summary functions to the input dataframe in order to calculate user features. Each row contains info related to one submission: 1. breadth_max 2. depth_max 3. first_level_comments 4. lifetime 5. root_user 6. size 7. root_id ...
625941d81f037a2d8b946480
def get_gifs_from_giphy(search_string): <NEW_LINE> <INDENT> baseurl = "https://api.giphy.com/v1/gifs/search" <NEW_LINE> params = {'q': search_string, 'api_key': api_key, 'limit': 5} <NEW_LINE> data = requests.get(baseurl, params = params) <NEW_LINE> res_d = json.loads(data.text) <NEW_LINE> return res_d['data']
Returns data from Giphy API with up to 5 gifs corresponding to the search input
625941d85f7d997b87174d1c
def drawn(self, core): <NEW_LINE> <INDENT> LOGGER.debug("A card is drawn, %r.", self) <NEW_LINE> self._do_drawn(core)
Called while this card is drawn.
625941d80fa83653e465723c
def test_asdict_root_event_should_return_event_as_a_dict(self): <NEW_LINE> <INDENT> event_data = 'example event data' <NEW_LINE> module = 'example module data' <NEW_LINE> source_event = '' <NEW_LINE> event_type = 'ROOT' <NEW_LINE> evt = SpiderFootEvent(event_type, event_data, module, source_event) <NEW_LINE> evt_dict =...
Test asDict(self)
625941d891f36d47f21ac777
def test_create_part_all_primary(self): <NEW_LINE> <INDENT> succ = BlockDev.part_create_table (self.loop_dev, BlockDev.PartTableType.MSDOS, True) <NEW_LINE> self.assertTrue(succ) <NEW_LINE> ps = BlockDev.part_create_part (self.loop_dev, BlockDev.PartTypeReq.NORMAL, 2048*512, 10 * 1024**2, BlockDev.PartAlign.OPTIMAL) <N...
Verify that partition creation works as expected with all primary parts
625941d8adb09d7d5db6ca10
def __init__( self, symbol, datestamp, quantity, direction, fill_cost, commission=None ): <NEW_LINE> <INDENT> self.symbol = symbol <NEW_LINE> self.datestamp = datestamp <NEW_LINE> self.quantity = quantity <NEW_LINE> self.direction = direction <NEW_LINE> self.fill_cost = fill_cost <NEW_LINE> self.commission = commission
Initializes a FillEvent direction == 'BUY','SELL' commission: is $ per share
625941d8f548e778e58cd801
def _end_bulk_operation(self, structure_key, emit_signals=True): <NEW_LINE> <INDENT> bulk_ops_record = self._get_bulk_ops_record(structure_key) <NEW_LINE> if not bulk_ops_record.active: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if emit_signals and bulk_ops_record.is_root: <NEW_LINE> <INDENT> self.send_pre_publish_...
End the active bulk operation on structure_key (course or library key).
625941d82c8b7c6e89b35a42
def viewNextSelect(self): <NEW_LINE> <INDENT> self.treeView.selectionModel().restoreNextSelect()
Go to the next tree selection in history.
625941d831939e2706e4d0e9
def free_sub_xray_lines_weight(self, xray_lines='all', bound=0.01): <NEW_LINE> <INDENT> def free_twin(component): <NEW_LINE> <INDENT> component.A.twin = None <NEW_LINE> component.A.free = True <NEW_LINE> if component.A.value - bound * component.A.value <= 0: <NEW_LINE> <INDENT> component.A.bmin = 1e-10 <NEW_LINE> <DEDE...
Free the weight of a sub X-ray lines Remove the twin on the height of sub-Xray lines (non alpha) Parameters ---------- xray_lines: list of str or 'all' The Xray lines. If 'all', fit all lines bounds: float Bound the height of the peak to a fraction of its height
625941d8009cb60464c63632
def import_curve(p, a, b, g, r, name="dummyName", oid=(1, 3, 132, 0, 0xff)): <NEW_LINE> <INDENT> if isinstance(p, str): <NEW_LINE> <INDENT> p = pkcs_os2ip(p) <NEW_LINE> <DEDENT> if isinstance(a, str): <NEW_LINE> <INDENT> a = pkcs_os2ip(a) <NEW_LINE> <DEDENT> if isinstance(b, str): <NEW_LINE> <INDENT> b = pkcs_os2ip(b) ...
Create an ecdsa.curves.Curve from the usual parameters. Arguments may be either octet strings or integers, except g which we expect to be an octet string.
625941d8e5267d203edcdf1c
def get_rows(self) -> dict: <NEW_LINE> <INDENT> rows = {} <NEW_LINE> str_list = [] <NEW_LINE> for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': <NEW_LINE> <INDENT> str_list.append(ch) <NEW_LINE> <DEDENT> counter = 0 <NEW_LINE> for num in range(2, self.length + 2): <NEW_LINE> <INDENT> line = str_list[counter:counter + num] <NEW_L...
Return the current result for key_lines in row.
625941d894891a1f4081bd2c
def __init__(self, score): <NEW_LINE> <INDENT> self.score = score <NEW_LINE> self.lst = [self.allergen[i] for i in range(8) if (self.score & (2**i))]
initialize allergy score
625941d83eb6a72ae02ec765
def execute(self, sources, target): <NEW_LINE> <INDENT> fields = self._get_fields_list_from_eps(sources) <NEW_LINE> feature_set = set(self.exclude_names) <NEW_LINE> target._ml_fields = list(self._clear_field_roles(fields[0], feature_set))
:type sources: list[DFAdapter] :type target: DFAdapter
625941d88c0ade5d55d3ec3f
def annotate(return_type=_invalid_placeholder_type, **kwargs): <NEW_LINE> <INDENT> global annotated_function_list <NEW_LINE> def decorator(func): <NEW_LINE> <INDENT> global annotated_function_list <NEW_LINE> func.type_annotations = kwargs <NEW_LINE> if return_type is not _invalid_placeholder_type: <NEW_LINE> <INDENT> f...
A decorator that informs the compyler about the return type of a function and a collection of hint for other variable names. These can include - captured variables - function arguments - other variables within the function Ex: @annotate(compyler.double, a=compyler.double, b=compyler.double) def add(a, b): ...
625941d829b78933be1e592b
def test_retrieve_ingredients_list(self): <NEW_LINE> <INDENT> Ingredient.objects.create(user=self.user, name='Pepper') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Salt') <NEW_LINE> response = self.client.get(INGREDIENTS_URL) <NEW_LINE> ingredients = Ingredient.objects.all().order_by('-name') <NEW_LINE> s...
Test retrieving a list of ingredients
625941d84527f215b584c6d7
def set_current_user(self, value, over_time=3600): <NEW_LINE> <INDENT> self.set_secure_cookie(self.talks_name, value, expires=self.expires_time(over_time))
设置用户会话cookie :param value: 值,可以是token,也可以是session id :param over_time: 过期时间 :return: None
625941d8f8510a7c17cf9980
def test_sign_index_action_user_sign_has(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> response = c.post('/sign_index_action/2/',{"phone":"18611001101"}) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertIn(b"user has sign in.", response.content)
用户已签到
625941d80a50d4780f667116
def subscribe_to_component_updates(self, *, stream_handler: typing.Optional[client.SubscribeToComponentUpdatesStreamHandler] = None, on_stream_event: typing.Optional[typing.Callable[[model.ComponentUpdatePolicyEvents], None]] = None, on_stream_error: typing.Optional[typing.Callable[[Exception], bool]] = None, on_stream...
Perform the SubscribeToComponentUpdates operation synchronously. The initial response or error will be returned synchronously, further events will arrive via the streaming callbacks Args: stream_handler: Methods on this object will be called as stream events happen on this operation. If an executor is prov...
625941d8287bf620b61d3ce5
def eval_all(expressions, env): <NEW_LINE> <INDENT> if expressions is nil: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if expressions.second is nil: <NEW_LINE> <INDENT> return scheme_eval(expressions.first, env, True) <NEW_LINE> <DEDENT> scheme_eval(expressions.first, env) <NEW_LINE> return eval_all(expressions.seco...
Evaluate each expression in the Scheme list EXPRESSIONS in environment ENV and return the value of the last.
625941d86fb2d068a760f323
def calibrate(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if self.recording: <NEW_LINE> <INDENT> raise Exception( "Error in libeyelink.libeyelink.calibrate(): Trying to " "calibrate after recording has started!") <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> self.eyelink_graphics.esc_pressed = Fals...
See pygaze._eyetracker.baseeyetracker.BaseEyeTracker
625941d8d58c6744b4257ee1
def add_user(self, u): <NEW_LINE> <INDENT> pass
Parameters: - u
625941d8099cdd3c635f0edd
def get_record_file_content(): <NEW_LINE> <INDENT> return files_service().get_file_content( id_=pid_value, file_key=file_key, identity=g.identity )
Retrieve record file content.
625941d8a8ecb033257d334f
def get_face_tuples(self, points): <NEW_LINE> <INDENT> face_indeces = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) <NEW_LINE> tuple_list = list(zip(points[:,0], points[:,1], points[:,2])) <NEW_LINE> faces = [[tuple_list[face_indeces[ix][iy]] for iy in range(len(face_ind...
groups the corner tuples as 6 faces
625941d8187af65679ca53a2
def get_width(name, w, l, m_a, m_b_d, mass, m_s): <NEW_LINE> <INDENT> vehicle = VehicleProfile(name, w, l, m_a, m_b_d, mass, m_s) <NEW_LINE> return vehicle.get_width()
Function returns the width of the vehicle :param name: name of profile :param w: width of the vehicle :param l: length of the vehicle :param m_a: max acceleration of the vehicle :param m_b_d: max braking deceleration of the vehicle :param mass: mass of the vehicle :param m_s: max speed of the vehicle :type w: float :ty...
625941d80a50d4780f667117
def test_view_recipe_detail(self): <NEW_LINE> <INDENT> recipe = sample_recipe(user=self.user) <NEW_LINE> recipe.tags.add(sample_tag(user=self.user)) <NEW_LINE> recipe.ingredients.add(sample_ingredient(user=self.user)) <NEW_LINE> url = detail_url(recipe.id) <NEW_LINE> res = self.client.get(url) <NEW_LINE> serializer = R...
Test: viewing a Recipe detail
625941d807d97122c4178b12
def set_sample_template_icon(self, sample_template_id: Union[int, str], file): <NEW_LINE> <INDENT> st_id = Id(sample_template_id) <NEW_LINE> headers = self._get_headers() <NEW_LINE> response = requests.post( f"{self._get_api_url()}/sampleTemplates/{st_id.as_id()}/icon", files={"file": file}, headers=headers, ) <NEW_LIN...
Parameters ---------- sample_template_id : Union[int, str] The ID of the template to add the icon too. file : an open File An icon or image to help identify the template in listings. Returns ------- The updated SampleTemplate, with an iconId set.
625941d8fb3f5b602dac3918
def forward(bot, update): <NEW_LINE> <INDENT> logger.info('@ {0} : {1}'.format(update.channel_post.chat.title, update.channel_post.text.split('\n')[1])) <NEW_LINE> if _has_tag(update.channel_post.text): <NEW_LINE> <INDENT> bot.send_message(chat_id=_get_chat_id(chat='Chihiro'), text=update.channel_post.text)
Forward message when target user sends a message in the specific channel.
625941d815fb5d323cde0d95
def __init__(self, dependencies: Iterable[Address]) -> None: <NEW_LINE> <INDENT> self.dependencies = FrozenOrderedSet(sorted(dependencies))
The result of inferring dependencies.
625941d8009cb60464c63633
def rename_file(self, file_name): <NEW_LINE> <INDENT> while exists(file_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = os.path.dirname(os.path.realpath(file_name)) <NEW_LINE> base = os.path.basename(os.path.realpath(file_name)) <NEW_LINE> os.rename(join(path, file_name), join(path, "DONE " + base)) <NEW_LIN...
Rename file_name
625941d84f88993c3716c2e8
def _show_endpoints(apis, pattern, endpoint, proto): <NEW_LINE> <INDENT> url = '/endpoint/%s' % urllib_parse.quote(pattern) <NEW_LINE> if endpoint: <NEW_LINE> <INDENT> if proto: <NEW_LINE> <INDENT> url += '/' + proto <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url += '/*' <NEW_LINE> <DEDENT> url += '/' + endpoint <NE...
Show cell endpoints.
625941d810dbd63aa1bd2e25
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'size_unit': 'str', 'expansion_size': 'int' } <NEW_LINE> self.attribute_map = { 'size_unit': 'sizeUnit', 'expansion_size': 'expansionSize' } <NEW_LINE> self._size_unit = None <NEW_LINE> self._expansion_size = None
VolumeExpansionRequest - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941d83d592f4c4ed1d2ec
def test_gen_xml_for_serial_console(self): <NEW_LINE> <INDENT> diskp = virt._disk_profile('default', 'kvm', [], 'hello') <NEW_LINE> nicp = virt._nic_profile('default', 'kvm') <NEW_LINE> xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='pty', console=True ) <NEW_LINE> root = ET.fromstring(xml_d...
Test virt._gen_xml() serial console
625941d8d268445f265b50f1
def doRetries(self): <NEW_LINE> <INDENT> jobs = self.getJobs.execute(state = 'createcooloff') <NEW_LINE> logging.info("Found %s jobs in createcooloff" % len(jobs)) <NEW_LINE> self.processRetries(jobs, 'create') <NEW_LINE> jobs = self.getJobs.execute(state = 'submitcooloff') <NEW_LINE> logging.info("Found %s jobs in sub...
Queries DB for all watched filesets, if matching filesets become available, create the subscriptions
625941d830bbd722463cc04b
def dropout(self, input_layer, keep_prob=0.5): <NEW_LINE> <INDENT> if self.is_training: <NEW_LINE> <INDENT> dtype = input_layer.dtype <NEW_LINE> with tf.variable_scope(self._count_layer('dropout')): <NEW_LINE> <INDENT> keep_prob_tensor = tf.constant(keep_prob, dtype=dtype) <NEW_LINE> return tf.nn.dropout(input_layer, k...
Applies a dropout layer if is_training
625941d81f5feb6acb0c4dd0
def solr_add_range(lower_recid, upper_recid): <NEW_LINE> <INDENT> for recid in range(lower_recid, upper_recid + 1): <NEW_LINE> <INDENT> if record_exists(recid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> abstract = unicode(get_fieldvalues(recid, CFG_MARC_ABSTRACT)[0], 'utf-8') <NEW_LINE> <DEDENT> except: <NEW_LINE> <...
Adds the regarding field values of all records from the lower recid to the upper one to Solr. It preserves the fulltext information.
625941d81f5feb6acb0c4dcf
def hasNext(self): <NEW_LINE> <INDENT> return len(self.inorder_list) > 0
:rtype: bool
625941d84c3428357757c5aa