code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def loads_jsonp(_jsonp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return json.loads(re.match(".*?({.*}).*", _jsonp, re.S).group(1)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError('Invalid Input')
解析jsonp数据格式为json
625941e5627d3e7fe0d69284
@numba.jit(nogil=True) <NEW_LINE> def read_unsigned_var_int(file_obj): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> shift = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> byte = file_obj.read_byte() <NEW_LINE> result |= ((byte & 0x7F) << shift) <NEW_LINE> if (byte & 0x80) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> ...
Read a value using the unsigned, variable int encoding. file-obj is a NumpyIO of bytes; avoids struct to allow numba-jit
625941e54e4d5625662d4804
def get_adjacency_matrix(self): <NEW_LINE> <INDENT> adj_matrix = [] <NEW_LINE> max_element = max( self.nodes, key=lambda v: v.value ) <NEW_LINE> total_node_size = max_element.value + 1 <NEW_LINE> for node_index in range(0, max_element.value+1): <NEW_LINE> <INDENT> node_with_index = [ x for x in self.nodes if x.value ==...
Return a matrix, or 2D list. Row numbers represent from nodes, column numbers represent to nodes. Store the edge values in each spot, and a 0 if no edge exists.
625941e5d18da76e2353290e
def parse(filename): <NEW_LINE> <INDENT> file = open(filename) <NEW_LINE> fileLines = file.readlines() <NEW_LINE> file.close() <NEW_LINE> fileStringNoComments = "" <NEW_LINE> for line in fileLines: <NEW_LINE> <INDENT> if line.find("#") != 0 and line.find("%") != 0: <NEW_LINE> <INDENT> fileStringNoComments += line <NEW...
Parse file specified by filename to get inputs, outputs, and function name of the first function defined in the m file.
625941e5435de62698dfe080
def powerset(iterable): <NEW_LINE> <INDENT> s = list(iterable) <NEW_LINE> return it.chain.from_iterable(it.combinations(s, r) for r in range(1, len(s)+1))
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
625941e556b00c62f0f14a8f
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.code = ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(32)) <NEW_LINE> return super(Code, self).save(*args, **kwargs)
create the code field by using random strings and digits :param args: :param kwargs:
625941e545492302aab5e6fa
def constants(s): <NEW_LINE> <INDENT> result = set([]) <NEW_LINE> def walk(s): <NEW_LINE> <INDENT> if is_constant(s): <NEW_LINE> <INDENT> result.add(s) <NEW_LINE> <DEDENT> for arg in s.args: <NEW_LINE> <INDENT> walk(arg) <NEW_LINE> <DEDENT> <DEDENT> walk(s) <NEW_LINE> return result
Devuelve un set de constantes en la expresion s. EJ: >>> ppset(variables(F(x, A, y))) set([A]) >>> ppset(variables(F(G(0), z))) set([]) >>> ppset(variables(expr('F(x, x) & G(x, y) & h(B) & R(A, z, z)'))) set([h(B),A])
625941e54e4d5625662d4805
def removePunctuation(column): <NEW_LINE> <INDENT> return F.lower(F.trim(F.regexp_replace(column,'[^A-Za-z0-9 ]+', ''))).alias('sentence')
Removes punctuation, changes to lower case, and strips leading and trailing spaces.
625941e5009cb60464c637e1
def reproc_processing(self): <NEW_LINE> <INDENT> raise NotImplementedError()
:raises: NotImplementedError :return: None
625941e5fbf16365ca6f65ff
def DbGetExportdDeviceListForClass(self, argin): <NEW_LINE> <INDENT> self.debug_stream("In " + self.get_name() + ".DbGetExportdDeviceListForClass()") <NEW_LINE> argout = [''] <NEW_LINE> return argout
Query the database for device exported for the specified class. :param argin: Class name :type: PyTango.DevString :return: Device exported list :rtype: PyTango.DevVarStringArray
625941e54f6381625f114e6f
def update_sweep(self, start, stop, npts): <NEW_LINE> <INDENT> demod_length = self._instrument._demod_length <NEW_LINE> if demod_length > 1: <NEW_LINE> <INDENT> self.shapes = ((demod_length, npts), (demod_length, npts)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.shapes = ((npts,), (npts,))
Function which updates the shape of the parameter (and it's setpoints when this is fixed) Args: start: start time of samples returned after processing stop: stop time of samples returned after processing npts: number of samples returned after processing
625941e53cc13d1c6d3c77ab
def sequence_distance(seq1, seq2, ignored=None, element_dist=elements_distance_binary): <NEW_LINE> <INDENT> ignored = norm_ignore_elems(ignored) <NEW_LINE> seqs = [b for b in seq1 + seq2 if b is not None] <NEW_LINE> blocks = [b for b in np.unique(seqs) if b not in ignored] <NEW_LINE> seq1_d = [blocks.index(b) if b not ...
affinity between two layouts :param [] seq1: sequence layout :param [] seq2: sequence layout :param [] ignored: list of elements to be ignored :param element_dist: callable function to measure distance :return float: >>> seq1 = ['a', 'b', 'a', 'c'] >>> sequence_distance(seq1, seq1) 0.0 >>> seq2 = ['a', 'a', 'b', 'a',...
625941e5283ffb24f3c55d30
def change_level(self): <NEW_LINE> <INDENT> if self.mode == IntrudyModes.SURVEILLANCE: <NEW_LINE> <INDENT> self.level = 0 <NEW_LINE> <DEDENT> elif self.mode != IntrudyModes.SURVEILLANCE: <NEW_LINE> <INDENT> self.level = 1
Changes the sensibility level depending of the mode.
625941e54f88993c3716c496
@deprecated_alias("get_spdk_version") <NEW_LINE> def spdk_get_version(client): <NEW_LINE> <INDENT> return client.call('spdk_get_version')
Get SPDK version
625941e51d351010ab855f4e
def theaterChase(strip, color, wait_ms=50, iterations=10): <NEW_LINE> <INDENT> for j in range(iterations): <NEW_LINE> <INDENT> for q in range(3): <NEW_LINE> <INDENT> for i in range(0, strip.n, 3): <NEW_LINE> <INDENT> strip[i + q] = color <NEW_LINE> <DEDENT> strip.write() <NEW_LINE> sleep_ms(wait_ms) <NEW_LINE> for i in...
Movie theater light style chaser animation.
625941e58e7ae83300e4b400
def __init__(self, T, n_batch, n_state, n_ctrl): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.T = T <NEW_LINE> self.n_batch = n_batch <NEW_LINE> self.n_state = n_state <NEW_LINE> self.n_ctrl = n_ctrl <NEW_LINE> self.n_sc = n_state + n_ctrl
constructor :param T: :param n_batch: :param n_state: :param n_ctrl:
625941e54e696a04525c9880
def lr_range(self, lr:Union[float,slice])->np.ndarray: <NEW_LINE> <INDENT> if not isinstance(lr,slice): return lr <NEW_LINE> if lr.start: res = even_mults(lr.start, lr.stop, len(self.layer_groups)) <NEW_LINE> else: res = [lr.stop/10]*(len(self.layer_groups)-1) + [lr.stop] <NEW_LINE> return np.array(res)
Build differential learning rates.
625941e5b5575c28eb68e437
def draw_button(self): <NEW_LINE> <INDENT> self.screen.fill(self.button_color, self.rect) <NEW_LINE> self.screen.blit(self.msg_image, self.msg_image_rect)
paint a colorful button and write some text
625941e57b180e01f3dc4c28
def _guess_format_and_filename(self, filename, format): <NEW_LINE> <INDENT> if filename and '.' in filename and not format: <NEW_LINE> <INDENT> format = filename.split('.')[-1] <NEW_LINE> <DEDENT> if not format: <NEW_LINE> <INDENT> format = WEBODT_DEFAULT_FORMAT <NEW_LINE> <DEDENT> if not filename: <NEW_LINE> <INDENT> ...
guess format and filename of the output document Either format and filename or both can be undefined (None) variables. Function determines undefined variables on basis of file extension or default values. If needed, temporary file will be created and returned. @return: tuple of strings (filename, format)
625941e5d10714528d60011b
def execute_cli_cmd(self, cli_cmd): <NEW_LINE> <INDENT> custom_headers = {'shell-command': cli_cmd} <NEW_LINE> response = self._rest_call("GET", "/rest/app/command", custom_headers) <NEW_LINE> self._check_response(response) <NEW_LINE> return response.get_data()
Executes any given CLI command using REST API
625941e5f7d966606f6aa43c
def update_scenario(scenario_json=None, update_json=None): <NEW_LINE> <INDENT> if scenario_json is None: <NEW_LINE> <INDENT> scenario_json = provide_elements_api({'name': update_json['scenario'], 'type':'scenario'}) <NEW_LINE> <DEDENT> if update_json['update_type'] == 'input': <NEW_LINE> <INDENT> elements = {e['name']:...
Update scenario takes a scenario and updates values inside this scenario based on the update_json file Parameters ---------- scenario_json: dict Scenario with expanded children (if not given, scenario_json will try to get this from database) update_json: dict Dictionary containing information for update in...
625941e55fc7496912cc3db1
def create_training_model(config: model.ModelConfig, context: List[mx.Context], output_dir: str, train_iter: data_io.BaseParallelSampleIter, args: argparse.Namespace) -> training.TrainingModel: <NEW_LINE> <INDENT> training_model = training.TrainingModel(config=config, context=context, output_dir=output_dir, provide_dat...
Create a training model and load the parameters from disk if needed. :param config: The configuration for the model. :param context: The context(s) to run on. :param output_dir: Output folder. :param train_iter: The training data iterator. :param args: Arguments as returned by argparse. :return: The training model.
625941e56aa9bd52df0371da
def test_jwt_grant_attribute(self): <NEW_LINE> <INDENT> validator = RequestValidator() <NEW_LINE> server = Server(validator) <NEW_LINE> self.assertIn( 'urn:ietf:params:oauth:grant-type:jwt-bearer', server.grant_types )
Test jwt_grant added to Server endpoint
625941e5a05bb46b383ecc51
def findFront(start): <NEW_LINE> <INDENT> before = start.getBefore() <NEW_LINE> if before == None: <NEW_LINE> <INDENT> return start <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return findFront(start.getBefore())
start: a Frob that is part of a doubly linked list returns: the Frob at the beginning of the linked list
625941e5462c4b4f79d1db02
def assign(self,blocklist): <NEW_LINE> <INDENT> self.blockList=blocklist[:] <NEW_LINE> self.sizeList=numpy.zeros((len(self.blockList),2),numpy.int32) <NEW_LINE> self.sizeCumList=numpy.zeros((self.sizeList.shape[0]+1,2),numpy.int32) <NEW_LINE> self.dtype=self.blockList[0].dtype <NEW_LINE> for i in range(len(self.blockLi...
assign blocklist to be the memory for this...
625941e5f548e778e58cd9b3
def find_words(word_type, min_length=0): <NEW_LINE> <INDENT> assert word_type in ["adj", "noun"] <NEW_LINE> words = defaultdict(lambda: []) <NEW_LINE> for l in open(build_path(word_type)): <NEW_LINE> <INDENT> if l and not l.startswith(" "): <NEW_LINE> <INDENT> w = l.split()[0].strip() <NEW_LINE> if "_" in w: <NEW_LINE>...
Returns a dict of first letter to set of words.
625941e5236d856c2ad44c13
@api.route('/users/<int:id>/', methods=["GET", "PUT"]) <NEW_LINE> @auth.login_required <NEW_LINE> def update_user(id): <NEW_LINE> <INDENT> user = User.query.get_or_404(id) <NEW_LINE> if request.method == 'PUT': <NEW_LINE> <INDENT> data_dict = eval(request.data) <NEW_LINE> user.username = data_dict.get('username', user....
更新一个用户 :return:
625941e59b70327d1c4e120a
def find_seeds(prob_range=(0.5, 0.55), seed_range=(0, 1000)): <NEW_LINE> <INDENT> good_seeds = {} <NEW_LINE> for seed in range(*seed_range): <NEW_LINE> <INDENT> s = np.random.RandomState(seed) <NEW_LINE> x = s.rand() <NEW_LINE> if x >= prob_range[0] and x < prob_range[1]: <NEW_LINE> <INDENT> good_seeds[seed] = x <NEW_L...
Find seeds where :func:`numpy.random.rand` would return probability within the given range. Parameters ---------- prob_range : tuple of float Range of desired probabilities in the form of ``[min, max)``. Limit is ``[0, 1)``. seed_range : tuple of int Range of seeds to search in the form of ``[min, max...
625941e5507cdc57c6307117
def test_add(): <NEW_LINE> <INDENT> tadd(1) <NEW_LINE> tadd(4)
add tests.
625941e5507cdc57c6307118
def __encrypt(self, text): <NEW_LINE> <INDENT> key, iv, size = self.token[:32], self.token[32:], AES.block_size <NEW_LINE> data = text + (size - len(text) % size) * chr(size - len(text) % size) <NEW_LINE> data = data.encode("utf-8") <NEW_LINE> data = AES.new(key, AES.MODE_CBC, iv).encrypt(data) <NEW_LINE> data = base64...
Returns the encrypted data. Parameters ---------- param text : string Decrypted text. Returns ------- Base64 Encrypted data.
625941e5498bea3a759b9ee1
def as_proto(self): <NEW_LINE> <INDENT> if self._dims is None: <NEW_LINE> <INDENT> return tensor_shape_pb2.TensorShapeProto(unknown_rank=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return tensor_shape_pb2.TensorShapeProto(dim=[ tensor_shape_pb2.TensorShapeProto.Dim( size=-1 if d.value is None else d.value) for ...
Returns this shape as a `TensorShapeProto`.
625941e5a17c0f6771cbe483
def fields(self): <NEW_LINE> <INDENT> keys = [] <NEW_LINE> for qry in self.queries: <NEW_LINE> <INDENT> fields = qry.fields() <NEW_LINE> keys.extend(fields) <NEW_LINE> <DEDENT> return keys
Returns a list of keys of all the field names referenced by the queries in the group
625941e5d268445f265b52a2
def test_ensure_state_valid_advisory_state(self): <NEW_LINE> <INDENT> advisory = errata.Advisory(errata_id=123, errata_state='invalid_errata_status') <NEW_LINE> with self.assertRaises(ValueError) as context: <NEW_LINE> <INDENT> advisory.ensure_state('UnknownState') <NEW_LINE> <DEDENT> self.assertTrue('UnknownState' in ...
Verify error is raised if desired state is not a recognized state
625941e5796e427e537b09fd
def perform(self) -> None: <NEW_LINE> <INDENT> if self.item.consumable: <NEW_LINE> <INDENT> self.item.consumable.activate(self)
invoke the items ability, this action will be given to provide context
625941e5d53ae8145f87a69b
def compute_mse(labeled_vals, pred_vals): <NEW_LINE> <INDENT> return ((pred_vals - labeled_vals) ** 2).mean()
compute mse.
625941e57d847024c06be6f3
def is_equal_to_two(n): <NEW_LINE> <INDENT> return n == 2
Simple function to use as a callback for tests :param n: Integer. Compared to 2 :return: True if n equals 2. False otherwise
625941e596565a6dacc8fafd
def create_woven_linked_list(head, midpoint, is_odd_length): <NEW_LINE> <INDENT> new_head = Node(data=head.data) <NEW_LINE> ptr1 = head.next <NEW_LINE> ptr2, current_node = link_node(midpoint, new_head) <NEW_LINE> while ptr2 is not None: <NEW_LINE> <INDENT> ptr1, current_node = link_node(ptr1, current_node) <NEW_LINE> ...
Create a fully new woven linked list. This does not mutate the original linked list.
625941e5379a373c97cfaf7a
def __call__(self, request): <NEW_LINE> <INDENT> if not request._security: <NEW_LINE> <INDENT> return request <NEW_LINE> <DEDENT> if self.is_token_expired(): <NEW_LINE> <INDENT> json_response = self.refresh() <NEW_LINE> AFTER_TOKEN_REFRESH.send(**json_response) <NEW_LINE> <DEDENT> for security in request._security: <NE...
Check if the request need security header and apply them. Required for pyswagger.core.BaseClient.request(). :param request: the pyswagger request object to check :return: the updated request.
625941e5aad79263cf390e7b
def Connect(self, port): <NEW_LINE> <INDENT> pass
Connect to the controller. To be implemented by subclass. Returns - True (for succesful connection) or False
625941e556ac1b37e62645fb
def createCPB(self, item, neighbour): <NEW_LINE> <INDENT> pTree = _Tree() <NEW_LINE> for node in self.nodeLink[item]: <NEW_LINE> <INDENT> node.prefix = [item for item in node.prefix if item in neighbour.get(node.item)] <NEW_LINE> pTree.createTree(node.prefix, node.count) <NEW_LINE> <DEDENT> return pTree
Create conditional pattern base based on item and neighbour :param item: int :param neighbour: dict :return: Tree
625941e5e8904600ed9f2367
def add_permission_by_name(self, code, save=False): <NEW_LINE> <INDENT> if not save: <NEW_LINE> <INDENT> return ["%s | %s" % (p.name, p.code) for p in Permission.objects.filter(code__contains=code)] <NEW_LINE> <DEDENT> for p in Permission.objects.filter(code__contains=code): <NEW_LINE> <INDENT> if p not in self.Permiss...
Adds a permission with given name. Args: code (str): Code name of the permission. save (bool): If False, does nothing.
625941e5dd821e528d63b5d9
def set_proxies(self,proxies): <NEW_LINE> <INDENT> self.__proxies = proxies <NEW_LINE> if self.session_is_open(): self._session.proxies = self.__proxies
set the proxies used by the session
625941e5656771135c3ebca7
def draw_rect(im, rect, color=(255, 255, 255)): <NEW_LINE> <INDENT> vis_pil = Image.fromarray(im) <NEW_LINE> draw = ImageDraw.Draw(vis_pil) <NEW_LINE> draw.rectangle((rect[0], rect[1], rect[0] + rect[2], rect[1] + rect[3]), outline=color, fill=None) <NEW_LINE> del draw <NEW_LINE> return np.array(vis_pil)
Draws a rectangle to the given image. :param im: Image in which the rectangle will be drawn (uint8, from 0 to 255). :param rect: Rectangle specified by [x, y, width, height], where [x, y] is the top-left corner of the rectangle. :param color: Color of the rectangle. :return: Image with the drawn rectangle...
625941e5d164cc6175783183
def prune_dirs(dirs, regex): <NEW_LINE> <INDENT> prunes = [x for x in dirs if not re.match(regex, x)] <NEW_LINE> for prune in prunes: <NEW_LINE> <INDENT> dirs.remove(prune)
Prune directories (in-place) that do not match ``regex``.
625941e566673b3332b924c5
def __init__(self, hidden_units, feature_columns=None, model_dir=None, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=True, config=None): <NEW_LINE> <INDENT> _changing(feature_columns) <NEW_LINE> super(DNNRegressor, self).__init__( model_dir=m...
Initializes a `DNNRegressor` instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should ...
625941e56fb2d068a760f4d7
def openFile(data): <NEW_LINE> <INDENT> with open(FILENAME) as fp: <NEW_LINE> <INDENT> data.extend(fp.readlines())
gets the contents of FILENAME
625941e5cad5886f8bd2740c
def write(self, text): <NEW_LINE> <INDENT> wx.CallAfter(self.text.AppendText, text)
Forward logging events to our TextCtrl.
625941e563d6d428bbe44924
def _plotPoint(self, data, new_line=False): <NEW_LINE> <INDENT> if new_line: <NEW_LINE> <INDENT> style = next(self._style) <NEW_LINE> <DEDENT> for i, (ax, (xAxis, yAxis), labelName) in enumerate(zip( self._axes, self._axesNames, self._labelNames)): <NEW_LINE> <INDENT> if new_line: <NEW_LINE> <INDENT> if labelName is No...
Add one data point to all charts in the smart way Arguments -- data: a dictionary (keys can be lists). Used to smartly assign the data to corresponding plots new_line: create a new line or not
625941e592d797404e3045bf
def getPortID(port): <NEW_LINE> <INDENT> if isinstance(port, int): <NEW_LINE> <INDENT> _id = port <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if port: <NEW_LINE> <INDENT> port = port.strip() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _id = int(port) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <N...
Check and Get port id from port string or port id using socket.getservbyname @param port port string or port id @return Port id if valid, -1 if port can not be found and -2 if port is too big
625941e507d97122c4178cc9
def test_append(self): <NEW_LINE> <INDENT> test_cases = [ Case( description="concat", val="hello", args=["there"], kwargs={}, expect="hellothere", ), Case( description="not a string", val=5, args=["there"], kwargs={}, expect="5there", ), Case( description="argument not a string", val="hello", args=[5], kwargs={}, expec...
Test append filter function.
625941e524f1403a92600f96
def test_not_found(self): <NEW_LINE> <INDENT> resp = self.client.get(r('subscriptions:detail', 0)) <NEW_LINE> self.assertEqual(404, resp.status_code)
Detail cannot be found.
625941e54c3428357757c759
def __init__(self, N, maxevals=[1, 1, 1], aggregate=np.median, reevals=None, epsilon=1e-7, parallel=False): <NEW_LINE> <INDENT> self.lam_reeval = reevals <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.parallel = parallel <NEW_LINE> self.theta = 0.5 <NEW_LINE> self.cum = 0.3 <NEW_LINE> self.alphasigma = 1 + 2 / (N + ...
parameters are `N` dimension, (only) necessary to adjust the internal "alpha"-parameters `maxevals` maximal value for ``self.evaluations``, where ``self.evaluations`` function calls are aggregated for noise treatment. With ``maxevals == 0`` the noise handler is (temporarily) "switched off". If `max...
625941e56e29344779a62a44
def widthdraw_money(account): <NEW_LINE> <INDENT> cash = int(input("Nhap so tien can rut: ")) <NEW_LINE> if cash > int(database[account].get('amount')): <NEW_LINE> <INDENT> print("Tài khoan không đủ để thực hiện giao dịch, vui long nhap lai") <NEW_LINE> widthdraw_money(account) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
Implement widthdrawing money from account
625941e5091ae3566866738b
def __eq__(self, other: 'SyndicationAuthorization') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Return `true` when self and other are equal, false otherwise.
625941e57047854f462a1839
def verify(self, tempfile=None, allowEmptyChecksums=False): <NEW_LINE> <INDENT> from .datafile import Dataset_File <NEW_LINE> df = self.datafile <NEW_LINE> if not (allowEmptyChecksums or df.sha512sum or df.md5sum): <NEW_LINE> <INDENT> logger.error("Datafile for %s has no checksums", self.url) <NEW_LINE> return False <N...
Verifies this replica's data matches the Datafile checksums. It must have at least one checksum hash to verify unless "allowEmptyChecksums" is True. If passed a file handle, it will write the file to it instead of discarding data as it's read.
625941e571ff763f4b549ac6
def Cancel(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Cancel') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Starts asynchronous cancellation on a long-running operation. The server. makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the ca...
625941e510dbd63aa1bd2fd6
def send_buffer(self): <NEW_LINE> <INDENT> self._port.send_buffer(self.get_buffer())
Get a buffer from the pool and send it to the port the pool is associated with.
625941e5d99f1b3c44c679bb
def ordercv(n, sossp, sogsp, nt, disc, classnum, tmp_ss, tmp_gs): <NEW_LINE> <INDENT> factor_n = misc.FactoredInteger(n) <NEW_LINE> while True: <NEW_LINE> <INDENT> c_s1 = ClassGroup(disc, classnum, []) <NEW_LINE> lstp_ls = sossp.retel() <NEW_LINE> sogsptp = sogsp.retel() <NEW_LINE> for p, e in factor_n: <NEW_LINE> <IND...
n: int
625941e52c8b7c6e89b35bf1
def test_dict_exporter_node(): <NEW_LINE> <INDENT> root = Node("root") <NEW_LINE> s0 = Node("sub0", parent=root) <NEW_LINE> s0b = Node("sub0B", parent=s0) <NEW_LINE> s0a = Node("sub0A", parent=s0) <NEW_LINE> s1 = Node("sub1", parent=root, foo="bar") <NEW_LINE> s1a = Node("sub1A", parent=s1) <NEW_LINE> s1b = Node("sub1B...
Dict Exporter.
625941e521a7993f00bc812b
def grad(self, x): <NEW_LINE> <INDENT> return np.where(x >= 0, 1, 0)
Predicts the activation for f`(x) (ReLu : 0 < x 1)
625941e563b5f9789fde751a
def _build(self, data): <NEW_LINE> <INDENT> for key, val in data.items(): <NEW_LINE> <INDENT> setattr(self, key, val)
Build our this :class:`Student` object
625941e50c0af96317bb861c
def as_json(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self, cls=_RecordingsJSONEncoder)
Return a JSON string representing this Channel.
625941e521bff66bcd684d82
@login_required <NEW_LINE> @csrf_exempt <NEW_LINE> def mail_report(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> receiver_email = request.POST.get('receiver_email') <NEW_LINE> filename = request.POST.get('filename') <NEW_LINE> datatable_export = json.loads(request.POST.get('datatable_ex...
1. Recieve the report data to be sent in mail, 2. Prepare CSV attachment 3. Send mail 4. Delete generated attachment file 5. Return response code
625941e594891a1f4081bedf
def save(self, is_exit=False, explicit=False, silent=False, force=False): <NEW_LINE> <INDENT> if (self._config_opt is not None and (not config.instance.get(self._config_opt)) and (not explicit) and (not force)): <NEW_LINE> <INDENT> if not silent: <NEW_LINE> <INDENT> log.save.debug("Not saving {name} because autosaving ...
Save this saveable. Args: is_exit: Whether we're currently exiting qutebrowser. explicit: Whether the user explicitly requested this save. silent: Don't write informations to log. force: Force saving, no matter what.
625941e5097d151d1a22328c
def get_params(self, baseLr): <NEW_LINE> <INDENT> return [{'params' : self.parameters(), 'lr' : baseLr}]
Create the a dictionary of the parameters that are going to be optimized. :param baseLr: learning rate to use for parameters :return:
625941e582261d6c526ab8da
def get_datetime_exact_match(source, target): <NEW_LINE> <INDENT> rules = set() <NEW_LINE> for arg in ("date", "time"): <NEW_LINE> <INDENT> regex = r":%s \( (.+?) \)" % arg <NEW_LINE> matches = re.findall(regex, target) <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> source_rhs = string_utils.format_source(match) ...
Return seed rules based on exact match for dates and times.
625941e5498bea3a759b9ee2
def recv_loop(self): <NEW_LINE> <INDENT> self._completed_response_lines = [] <NEW_LINE> self._is_multiline = None <NEW_LINE> lines_iterator = self.get_lines() <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line = next(lines_iterator) <NEW_LINE> if self._is_multiline is None: <NEW_LINE> <INDENT> sel...
Service socket recv, returning responses to the correct queue
625941e530c21e258bdfa8d6
def _assign_properties0_19_to_0_19(obj, old_dict): <NEW_LINE> <INDENT> _wrn("New property values added.") <NEW_LINE> if hasattr(obj, "Length"): <NEW_LINE> <INDENT> obj.Length = old_dict["Length"] <NEW_LINE> <DEDENT> if hasattr(obj, "Start"): <NEW_LINE> <INDENT> obj.Start = old_dict["Start"] <NEW_LINE> <DEDENT> if hasat...
Assign the new properties from the old properties. If new properties are named differently than the older properties or if the old values need to be transformed because the class now manages differently the data, this can be done here. Otherwise simple assigning the old values is possible.
625941e5de87d2750b8601cb
def test(self, state, inquiry): <NEW_LINE> <INDENT> return getattr(self, state) == inquiry
Is current state/preparation etc. busy or free?
625941e5cad5886f8bd2740d
@nt.raises(NotImplementedError) <NEW_LINE> def test_semiabstractmethod_decorator_with_args(): <NEW_LINE> <INDENT> @pyshell.util.semiabstractmethod("My Message %s()") <NEW_LINE> def my_method(): <NEW_LINE> <INDENT> print("Doing my not-implemented method") <NEW_LINE> <DEDENT> nt.eq_(my_method.__name__,'my_method') <NEW_L...
@semiabstractmethod(message)
625941e5ac7a0e7691ed44f9
def search(term, auth=None): <NEW_LINE> <INDENT> term = str(term) <NEW_LINE> search_url = API_BASE + ENDPOINTS["organisms_search"] <NEW_LINE> results = [] <NEW_LINE> response = requests.get(search_url + term) <NEW_LINE> if utils.valid_response(response.status_code): <NEW_LINE> <INDENT> response_data = json.loads(respon...
Search CoGe Organisms by Term :param term: Search term (str). :return: List of search results, stored as Organisms. Empty list if no results.
625941e51b99ca400220aee7
def _prime_test_with_list(number): <NEW_LINE> <INDENT> cutoff = int(math.sqrt(number)) <NEW_LINE> for prime in prime_list: <NEW_LINE> <INDENT> if prime > cutoff: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if number % prime == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Tests just using the primes in the primes_list
625941e530bbd722463cc1fc
def find_open_port(): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.bind(("",0)) <NEW_LINE> port = s.getsockname()[1] <NEW_LINE> s.close() <NEW_LINE> return port
Ask the OS for an open port
625941e58c3a8732951587f4
def load_response_descriptor_projects_release_release_resource(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.load_response_descriptor_projects_release_release_resource_with_http_info(id, **kwargs) <NEW_LINE> <DEDEN...
Get a ReleaseResource by ID # noqa: E501 Gets a release by ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.load_response_descriptor_projects_release_release_resource(id, async_req=True) >>> result = thread.get...
625941e55fdd1c0f98dc0669
def search(subreddit, keyword, limit): <NEW_LINE> <INDENT> search_result = r.subreddit(subreddit).search('{0}'.format( keyword), time_filter='month') <NEW_LINE> log.debug('Search result: {}'.format(search_result.__dict__)) <NEW_LINE> if search_result is None: <NEW_LINE> <INDENT> log.info('No matching result.') <NEW_LIN...
Search for the queries in the sub using reddit search, time filtered
625941e5d18da76e2353290f
def set_golden_hammers(self, num): <NEW_LINE> <INDENT> if not 255 >= num >= 0: <NEW_LINE> <INDENT> raise ValueError("Minimum is 0, maximum is 255.") <NEW_LINE> <DEDENT> for autosave in self.autosave: <NEW_LINE> <INDENT> autosave.goldenHammers = num <NEW_LINE> <DEDENT> self.update_autosave_checksum()
Sets golden hammers from 0 to 255. NOTE: More than 5 will glitch the milestone wall.
625941e5046cf37aa974d178
def addGdbLayer(self, layerDef, gdbFile, start = 0, maxFeatures = 0): <NEW_LINE> <INDENT> if (Globals.isThreadUnsafe()): <NEW_LINE> <INDENT> func = Func[LayerDef, str, int, int, Task[IGraphicsLayer]](self.view.addGdbLayer) <NEW_LINE> layer = dispatcher.Invoke(func, layerDef, gdbFile, start, maxFeatures) <NEW_LINE> <DED...
A thread safe call to -> IS3View.addGdbLayer
625941e5a8ecb033257d3500
def nv_lock(self): <NEW_LINE> <INDENT> return self.nv_define_space(TPM_NV_INDEX_LOCK, 0, 0)
Lock the NVRAM
625941e5283ffb24f3c55d31
def getTypeById(self, type:str, id:str) -> object: <NEW_LINE> <INDENT> return self.settings.find("file[@type='" + type + "'][@id='"+id+"']")
Filters settings nodes by both type and id. :param type: type string from settings. :param id: id string from settings. :return: ElementTree.Element or list of them.
625941e573bcbd0ca4b2c4aa
def border( self, color, width, height ): <NEW_LINE> <INDENT> self._check_wand_error( api.MagickBorderImage( self._wand, color._wand, width, height ) )
Surraunds an image with a color defined by color.Color(color_str).
625941e51d351010ab855f4f
def getPlayerOrientation(self, player="Player"): <NEW_LINE> <INDENT> yp = [x.value for x in self.getPlayerTag(player)["Rotation"]] <NEW_LINE> y, p = yp <NEW_LINE> if p == 0: <NEW_LINE> <INDENT> p = 0.000000001 <NEW_LINE> <DEDENT> if p == 180.0: <NEW_LINE> <INDENT> p -= 0.000000001 <NEW_LINE> <DEDENT> yp = y, p <NEW_LIN...
returns (yaw, pitch)
625941e544b2445a339324c7
def launch(*args, **kwargs): <NEW_LINE> <INDENT> pass
Launch the appropriate application to open the document, web page or directory specified. Flags: - directory : dir (unicode) [create] A directory.Flag can appear in Create mode of commandFlag can have multiple arguments, passed either as a tuple or a list. - movie : mov ...
625941e57d847024c06be6f4
def run_graph(self, wav_data, labels, input_layer_name, output_layer_name, num_top_predictions): <NEW_LINE> <INDENT> with tf.Session() as sess: <NEW_LINE> <INDENT> softmax_tensor = sess.graph.get_tensor_by_name(output_layer_name) <NEW_LINE> predictions, = sess.run(softmax_tensor, {input_layer_name: wav_data}) <NEW_LINE...
Runs the audio data through the graph and prints predictions.
625941e567a9b606de4a82eb
def _fit(self, v_pos, rng): <NEW_LINE> <INDENT> h_pos = self._mean_hiddens(v_pos) <NEW_LINE> v_neg = self._sample_visibles(self.h_samples_, rng) <NEW_LINE> h_neg = self._mean_hiddens(v_neg) <NEW_LINE> lr = float(self.learning_rate) / v_pos.shape[0] <NEW_LINE> update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True)....
Inner fit for one mini-batch. Adjust the parameters to maximize the likelihood of v using Stochastic Maximum Likelihood (SML). Parameters ---------- v_pos : array-like, shape (n_samples, n_features) The data to use for training. rng : RandomState Random number generator to use for sampling.
625941e566656f66f7cbc5e1
def assert_success(self, func, **options): <NEW_LINE> <INDENT> if options: <NEW_LINE> <INDENT> func(**options) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func() <NEW_LINE> <DEDENT> expected = 'N files: ' + str(len(self.input_files())) <NEW_LINE> actual = 'N files: ' + str(len(self.output_files())) <NEW_LINE> self.as...
Runs function and asserts success. Args: func (function): function to run. options (kwargs): function options; unpacked keyword args
625941e5cdde0d52a9e5346a
def __init__(self, number_of_individuals, individual_generator, fitness, filter_func): <NEW_LINE> <INDENT> self.n = number_of_individuals <NEW_LINE> self.individuals = [] <NEW_LINE> for _ in range(number_of_individuals): <NEW_LINE> <INDENT> self.individuals.append(individual_generator()) <NEW_LINE> <DEDENT> self.fitnes...
Crea una nueba población con el número de individuos dados, generados por la función individual_generator. ---------- Parámetros number_of_individuals: el número de individuos de esta población individual_generator: función que genera un individuo en la población fitness: función qu...
625941e58e05c05ec3eea7ad
def GetLogEntries(self): <NEW_LINE> <INDENT> return self.log_entries
Return the list of recorded log entries. @rtype: list of (string, string) tuples @return: the list of recorded log entries
625941e515fb5d323cde0f4a
def test_sale_with_pricelist_discount_excluded(self): <NEW_LINE> <INDENT> self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]}) <NEW_LINE> self.company_data['product_order_no'].write({'categ_id': self.product_category_1.id}) <NEW_LINE> self.company_data['product_delivery_no']....
Test SO with the pricelist 'discount displayed' and check discount and unit price appeared on its lines
625941e5dc8b845886cb596b
def getCOEmission(self, edgeID): <NEW_LINE> <INDENT> return self._getUniversal(tc.VAR_COEMISSION, edgeID)
getCOEmission(string) -> double Returns the CO emission in mg for the last time step on the given edge.
625941e5851cf427c661a940
def returnObjs(subReddit, maxNumberImgs): <NEW_LINE> <INDENT> return fetchSubImages.core.returnObjs(subReddit, maxNumberImgs)
Returns the last 'maxNumberImgs' images in the 'subReddit' sub as objects containing [title] and [url] :param subReddit: Subreddit for fetching :param maxNumberImgs: Maximum number of posts fetched :return: List of objects containing "title" and "url" :type subReddit: str :type maxNumberImgs: int :rtype: list
625941e556b00c62f0f14a91
def construct_message(sender, message, whisper=False, time="00:00"): <NEW_LINE> <INDENT> constructed_message = "{:s} {:s}&gt; {:s}".format( time, "{:s}{:s}".format("from " if whisper else "", sender), message ) <NEW_LINE> return constructed_message
External API-like method for simulating sending a message
625941e5eab8aa0e5d26df8e
def setup_show(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import pylab <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> import base64 <NEW_LINE> import hashlib <NEW_LINE> import inspect <NEW_LINE> try: <NEW_LINE> <INDENT> from cStringIO import StringIO <NEW_LINE> <DED...
Override pylab's show() function with our own.
625941e594891a1f4081bee0
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.asset_name = validated_data.get('asset_name', instance.asset_name) <NEW_LINE> instance.asset_type = validated_data.get('asset_type', instance.asset_type) <NEW_LINE> instance.asset_class = validated_data.get('asset_class', instance.asset_class) <NE...
Update and return an existing `Asset` instance, given the validated data.
625941e5009cb60464c637e3
def sign_extend(value, bits): <NEW_LINE> <INDENT> sign_bit = 1 << (bits - 1) <NEW_LINE> return (value & (sign_bit - 1)) - (value & sign_bit)
Performs 2's compliment sign extension :param value: value to sign extend :param bits: number of bits making up the value :return: sign extended value
625941e53d592f4c4ed1d497
def __init__ ( self, main_resolver ): <NEW_LINE> <INDENT> with DependencyResolverChannel.id_gen_lock: <NEW_LINE> <INDENT> self.ident = next ( DependencyResolverChannel.id_generator ) <NEW_LINE> <DEDENT> self._depres_master = main_resolver
Initializes a DependencyResolverChannel which can be used to communicate with the dep resolver. arguments: * main_resolver -- dep resolver to connect to; setting this to None results in automatic assignment when registering with the first dep resolver.
625941e5e76e3b2f99f3ac3a
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('-n', help='The value N of the board nxm', required=True) <NEW_LINE> parser.add_argument('-m', help='The value M of the board nxm', required=True) <NEW_LINE> pieces_help = 'List of pieces to be used. Valid optiosn ar...
function that parses the command line arguments
625941e5cdde0d52a9e5346b
def canReorderDoubled(self, A): <NEW_LINE> <INDENT> def valid(nums): <NEW_LINE> <INDENT> if len(nums) % 2 == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> counts = collections.Counter(nums) <NEW_LINE> for num in sorted(nums): <NEW_LINE> <INDENT> if counts[num]: <NEW_LINE> <INDENT> if counts[2 * num] == 0: <NE...
:type A: List[int] :rtype: bool
625941e53317a56b8693a083
def __init__(self, input_shape, num_filters, kernel_size, stride, padding, use_bias, args, device, normalization=True, meta_layer=True): <NEW_LINE> <INDENT> super(MetaConvReLUNormLayer, self).__init__() <NEW_LINE> self.meta_layer = meta_layer <NEW_LINE> self.normalization = normalization <NEW_LINE> self.conv = MetaConv...
Initializes a Conv->BatchNorm->ReLU layer which applies those operation in that order. :param args: A named tuple containing the system's hyperparameters. :param device: The device to run the layer on. :param normalization: The type of normalization to use 'batch_norm' or 'layer_norm' :param meta_layer: Whether this la...
625941e5ec188e330fd5abcc
def get_type(symbol): <NEW_LINE> <INDENT> url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol <NEW_LINE> soup = BeautifulSoup(urllib.urlopen(url).read()) <NEW_LINE> if soup.find('span', text='Business Summary'): <NEW_LINE> <INDENT> return 'Stock' <NEW_LINE> <DEDENT> elif soup.find('span', text='Fund Summary'): ...
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
625941e585dfad0860c3b291
def scan(theLocals, *namelist, **kw): <NEW_LINE> <INDENT> redirKW, closeFHList = redirProcess(kw) <NEW_LINE> if '_save' in kw: <NEW_LINE> <INDENT> del kw['_save'] <NEW_LINE> <DEDENT> resetList = redirApply(redirKW) <NEW_LINE> try: <NEW_LINE> <INDENT> line = _irafutils.tkreadline() <NEW_LINE> if line == "": <NEW_LINE> <...
Scan function sets parameters from line read from stdin This can be used either as a function or as a task (it accepts redirection and the _save keyword.)
625941e5b5575c28eb68e439