code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_alter_layout_depthwise_conv2d(): <NEW_LINE> <INDENT> def before(): <NEW_LINE> <INDENT> x = relay.var("x", shape=(1, 32, 56, 56)) <NEW_LINE> w = relay.var("w", shape=(32, 1, 3, 3)) <NEW_LINE> y = relay.nn.conv2d(x, w, padding=(1, 1), channels=32, kernel_size=(3, 3), groups=32) <NEW_LINE> y = relay.Function(anal...
Test depthwise_conv2d operator
625941f3be383301e01b5a70
def test_login_redirects_with_a_wrong_name(self): <NEW_LINE> <INDENT> url = reverse('hc-check-token', args=['wrong-name', 'secret-token']) <NEW_LINE> response = self.client.post(url) <NEW_LINE> self.assertRedirects(response, "/accounts/login/")
Ensure that when a bad username is provided for logging in, then it should redirect to the login page
625941f33eb6a72ae02ecae5
def __init__(self, title='Setting values:', values={'int': 1, 'String': 'This is String', 'float': 3.5}): <NEW_LINE> <INDENT> style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER <NEW_LINE> wxsc.SizedDialog.__init__(self, parent=None, id=-1, title=title, style=style) <NEW_LINE> self.originvalues = values.copy() <NEW_LINE...
#~ using it as follow: #~ dialog = InputDialog(title='Setting values:',values={'int':1,'String':'This is String','float':3.5}) #~ just for test: #~ dialog = InputDialog()
625941f310dbd63aa1bd3199
def test_should_raise_if_notebook_is_not_a_file(conf, work_dir): <NEW_LINE> <INDENT> script_path = join(work_dir, 'script.py') <NEW_LINE> write_python_script('import os', script_path) <NEW_LINE> with pytest.raises(MlVToolException) as e: <NEW_LINE> <INDENT> compare(join(work_dir, 'does_not_exist.ipynb'), script_path, c...
Test raises if provided notebook is not a file
625941f3236d856c2ad44dda
def run(self): <NEW_LINE> <INDENT> args = (self.model.fcn, self.beta0, self.data.y, self.data.x) <NEW_LINE> kwds = {'full_output': 1} <NEW_LINE> kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile', 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb', 'stpd', 'sclb', 'scld', 'work', 'iwork'] <NEW_LINE> i...
Run the fitting routine with all of the information given. Returns ------- output : Output instance This object is also assigned to the attribute .output .
625941f3a934411ee3751c8c
def extend_by(self, extend_type): <NEW_LINE> <INDENT> extend_type = self.parent()(extend_type) <NEW_LINE> return self + extend_type
Return a new analytic type which contains all analytic properties specified either in ``self`` or in ``extend_type``. INPUT: - ``extend_type`` - An analytic type or something which is convertable to an analytic type. OUTPUT: The new extended analytic type. EXAMPLES:: sage: AT = Analyti...
625941f3e1aae11d1e74a2b5
def get_acknowledgements(self, host_name=None, author=None, comment=None, service_name=None): <NEW_LINE> <INDENT> filters = [] <NEW_LINE> filter_vars = {} <NEW_LINE> if host_name: <NEW_LINE> <INDENT> filters.append('host.name==hostname') <NEW_LINE> filter_vars['hostname'] = host_name <NEW_LINE> <DEDENT> if author: <NEW...
Get acknowledgements (=comments) :param host_name: :param author: :param comment: :param service_name: :return:
625941f3ff9c53063f47c7e7
def pdf(self, x): <NEW_LINE> <INDENT> if self._pdf is None: <NEW_LINE> <INDENT> self._pdf = interpolate.interp1d(self.xs, self.agg_density, kind='linear', bounds_error=False, fill_value='extrapolate') <NEW_LINE> <DEDENT> return self._pdf(x) / self.bs
probability density function, assuming a continuous approximation of the bucketed density :param x: :return:
625941f33346ee7daa2b3369
def main(request): <NEW_LINE> <INDENT> project = request.args.get('project') <NEW_LINE> zone = request.args.get('zone') <NEW_LINE> instance_name = request.args.get('instance') <NEW_LINE> instance = compute.instances().get(project=project, zone=zone, instance=instance_name).execute() <NEW_LINE> if instance['status'] == ...
Toggles compute engine instance start-stop
625941f3fbf16365ca6f67c8
def case8(glyph): <NEW_LINE> <INDENT> point_list = list() <NEW_LINE> first = list() <NEW_LINE> middle = list() <NEW_LINE> final = list() <NEW_LINE> output = list() <NEW_LINE> miny = glyph.bounds[1] <NEW_LINE> maxy = glyph.bounds[3] <NEW_LINE> dist_y = maxy - miny <NEW_LINE> temp_y = dist_y * 0.4 <NEW_LINE> for i in ran...
middle four, exist final
625941f33617ad0b5ed684ed
def livre(self): <NEW_LINE> <INDENT> return self._livre_var
Checks whether the explorer is free
625941f345492302aab5e8c1
def normalize_amplitude(chunk, amplitude): <NEW_LINE> <INDENT> chunk_amplitude = find_amplitude(chunk) <NEW_LINE> return chunk * (amplitude / chunk_amplitude)
Normalize a chunk of audio samples to a given amplitude Args: chunk (numpy.ndarray): An array of int16 audio samples amplitude (float): The amplitude to normalize to. Should be between 0 and 1. Returns: (numpy.ndarray): An array of int16 audio samples whose amplitude is normalized to `amplitud...
625941f33617ad0b5ed684ee
def AsJsonString(self): <NEW_LINE> <INDENT> return simplejson.dumps(dict(self.AsDict().items()+super(ServerOp, self).AsDict().items()), sort_keys=True)
A JSON string representation of this kubernetes.ServerOp instance. Returns: A JSON string representation of this kubernetes.ServerOp instance.
625941f38e71fb1e9831dd9e
def test_quintuple_layout(): <NEW_LINE> <INDENT> window_layout = ( "e078,200x60,0,0{80x60,0,0[80x40,0,0,264,80x20,0,41,268]," "120x60,81,0[120x20,81,0,265,120x30,81,21,266,120x10,81,51,267]}" ) <NEW_LINE> window_data = [ { "identity": "window", "number": 0, "title": "window", "postfix": "~-", "layout": window_layout, "...
Tests a layout where the left half is split in two and the right in thirds | 2 0 | --- --- | 3 1 | --- | 4
625941f34c3428357757c91b
def _filter_author(self, value): <NEW_LINE> <INDENT> self.filters.append( Q(author__username__icontains=value) | Q(author__email__icontains=value) )
Filters articles by an author
625941f3187af65679ca5717
def shutdown(self): <NEW_LINE> <INDENT> pass
Called when calibre is shutting down, either for good or in preparation to restart. Do any cleanup required. This method is called on the device thread, not the GUI thread.
625941f350812a4eaa59c912
def get_datacenter(content, obj): <NEW_LINE> <INDENT> datacenters = content.rootFolder.childEntity <NEW_LINE> for d in datacenters: <NEW_LINE> <INDENT> dch = get_all(content, d, type(obj)) <NEW_LINE> if dch is not None and obj in dch: <NEW_LINE> <INDENT> return d
Get the datacenter to whom an object belongs
625941f31b99ca400220b0ab
def depth_first_search(self): <NEW_LINE> <INDENT> if(self.isSolvable()==False): <NEW_LINE> <INDENT> return (None,None) <NEW_LINE> <DEDENT> closed = list() <NEW_LINE> q = list() <NEW_LINE> q.append(Node(state = self.state,depth = 0)) <NEW_LINE> while q: <NEW_LINE> <INDENT> node = q.pop() <NEW_LINE> if node.isGoalState()...
Parameters: State Returns: List of Moves to solve the state, otherwise None if unsolvable
625941f330dc7b7665901f56
def _has_surrogates(s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s.encode() <NEW_LINE> return False <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> return True
Return True if s contains surrogate-escaped binary data.
625941f324f1403a92601158
@requires_h5py <NEW_LINE> def test_io(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> fname = op.join(tempdir, 'test-tfr.h5') <NEW_LINE> data = np.zeros((3, 2, 3)) <NEW_LINE> times = np.array([.1, .2, .3]) <NEW_LINE> freqs = np.array([.10, .20]) <NEW_LINE> info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003']...
Test TFR IO capacities.
625941f397e22403b379d593
def process_binary(self, trail, target=None): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> vec = target <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vec = NP.zeros((len(self.namespace), self.veclen), dtype=NP.float32) <NEW_LINE> <DEDENT> for c in trail: <NEW_LINE> <INDENT> poi_id = self.namespace.ind...
This will only set the time slot to be one at the check-in location
625941f3d8ef3951e3243b35
def Update(self, value, time=0): <NEW_LINE> <INDENT> if type(value) != type([]): <NEW_LINE> <INDENT> value = [value] <NEW_LINE> <DEDENT> if len(value) != len(self._value): <NEW_LINE> <INDENT> raise Exception("ERROR:\n len(value) != len(self.GetValue())") <NEW_LINE> <DEDENT> self._update_value = [] <NEW_LINE> self._upda...
Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter **must** be a multiple of 50 milliseconds. :param `value`: The value to be added to the gauge; :param `time`: The length of time in milliseconds that it will take to move the gauge.
625941f32ae34c7f2600d728
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> data = super(LoginView, self).get_context_data(**kwargs) <NEW_LINE> data.update({'query_string': self.request.META['QUERY_STRING']}) <NEW_LINE> return data
Add extra data to the context
625941f3cdde0d52a9e53630
def p_list_sort(t): <NEW_LINE> <INDENT> t[0] = Operation('list_sort', [t[2]])
statement : SORT var
625941f360cbc95b062c6b3b
def string2bin(data, size=None): <NEW_LINE> <INDENT> if isinstance(data, tuple): <NEW_LINE> <INDENT> data = data[1] <NEW_LINE> <DEDENT> datalen = len(data) <NEW_LINE> if datalen > size: <NEW_LINE> <INDENT> raise ValueError("Data %s bigger then size" % repr(data)) <NEW_LINE> <DEDENT> data += "\x00" * (size - datalen) <N...
Convert a string to a byte-string.
625941f3a17c0f6771cbe646
def characteristic_immutability_sentry(self, attr, value): <NEW_LINE> <INDENT> prev = sys._getframe().f_back <NEW_LINE> if ( attr not in attrs or prev is not None and prev.f_code.co_name in _VALID_INITS ): <NEW_LINE> <INDENT> self.__original_setattr__(attr, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Att...
Immutability sentry automatically created by characteristic. If an attribute is attempted to be set from any other place than an initializer, a TypeError is raised. Else the original __setattr__ is called.
625941f326068e7796caf2e0
def delete_many(self, collection: str, filters: dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> deletes = self._connection[self._database][collection].delete_many(filters) <NEW_LINE> return deletes.deleted_count <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> raise self._process_errors(error)
Update one document of a collection by given filters :param collection: Mongo collection name :param filters: Mongo query to match document
625941f307d97122c4178e92
def isPolyA(self): <NEW_LINE> <INDENT> return self.percentNuc("A") >= 0.9
Determine whether this sequence is polyA. To be a polyA sequence, it must have > 90% Adenine. :return: True if the sequence is PolyA by the above definition.
625941f3ad47b63b2c50a577
def TruncateString(val1, val2): <NEW_LINE> <INDENT> if (len(val1) == 0) or (len(val2) == 0): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif (val1 == val2): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> str1 = str(val1) <NEW_LINE> str2 = str(val2) <NEW_LINE> num_char_compared = 10 <NEW_LINE> if (str1[:num_char...
Compare two field values using exact string comparator with truncated strings.
625941f3be8e80087fb2122f
def Rnm(N, M): <NEW_LINE> <INDENT> nharm = R2nharm(N, M) <NEW_LINE> yn = zeros((nharm,), dtype=int_) <NEW_LINE> ym = zeros((nharm,), dtype=int_) <NEW_LINE> i = 0 <NEW_LINE> for n in range(N+1): <NEW_LINE> <INDENT> mf = -n + M - 1 <NEW_LINE> if mf > 0: mf = 0 <NEW_LINE> for m in range(-n,mf+1): <NEW_LINE> <INDENT> yn[i]...
Gets arrays representing the degrees and orders of a rhomboidal truncation of maximum degree N and order width M :param int N: highest degree in truncation :param int M: highest number of orders in each degree :return: tuple containing - the degrees of the functions in the expansion - the orders of the funct...
625941f3046cf37aa974d339
def softmax_loss_vectorized(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> N = X.shape[0] <NEW_LINE> D = X.shape[1] <NEW_LINE> C = W.shape[1] <NEW_LINE> unnormalized_log_probability = np.dot(X, W) <NEW_LINE> unnormalized_probability = np.exp(unnormalized_log_probability) <NEW_...
Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive.
625941f3bde94217f36833e3
def check_repeat(db, record): <NEW_LINE> <INDENT> models = [TechRepublicData, SecurityNewsData, PyjobData, RedditData] <NEW_LINE> temp = db.query(*models) <NEW_LINE> for model in models: <NEW_LINE> <INDENT> if temp.filter(model.title == record.title).count(): <NEW_LINE> <INDENT> return True
Check for repeats by comparing them in the database.
625941f34f88993c3716c658
def write_file(self, f=None, check=False): <NEW_LINE> <INDENT> if f is not None: <NEW_LINE> <INDENT> if isinstance(f, str): <NEW_LINE> <INDENT> f_gnc = open(f, "w") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f_gnc = f <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> f_gnc = open(self.fn_path, "w") <NEW_LINE> <...
Write the package file. Parameters ---------- f : filename or file handle File to write to. Returns ------- None
625941f3b545ff76a891440d
def zipstream(files): <NEW_LINE> <INDENT> stream = StringIO() <NEW_LINE> z = zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED) <NEW_LINE> for filename, contents in files.items(): <NEW_LINE> <INDENT> z.writestr(filename, contents) <NEW_LINE> <DEDENT> z.close() <NEW_LINE> stream.seek(0) <NEW_LINE> return stream
Given a dictionary mapping file names to content buffers, return a StringIO instance containing a zipfile made up of those contents.
625941f37cff6e4e81117f7d
def _download_data_from_s3(self, s3_data_url): <NEW_LINE> <INDENT> local_data_hash = data_utils.get_md5(s3_data_url.encode('utf-8')) <NEW_LINE> local_data_location = os.path.join(mlconfig.data_dir, local_data_hash) <NEW_LINE> if os.path.exists(local_data_location): <NEW_LINE> <INDENT> self.logger.info("\t\t- S3 data %s...
download s3 data from s3_data_url, to data_dir/[md5(s3_url)]
625941f38e05c05ec3eea971
def createAnalysisQueries(self, cid: Text, title: Text, query_txt: Text): <NEW_LINE> <INDENT> analysisQueriesBody = { "title": title, "queryText": query_txt } <NEW_LINE> aq_object = self.adh_service.customers().analysisQueries().create(parent=cid, body=analysisQueriesBody).execute() <NEW_LINE> return aq_object
Create analysis queries. Create analysis queries, the detail link as below: https://developers.google.com/ads-data-hub/reference/rest/v1/customers.analysisQueries/create Args: cid: customer's id, ex customers/1234567. title: analysis's queries. query_txt: adh sql query Returns: analysis query creation object...
625941f3eab8aa0e5d26e152
def get_emitter(self): <NEW_LINE> <INDENT> supervisor_emitter = self.supervisorControl.get_emitter(self.EMITTER_NAME) <NEW_LINE> return supervisor_emitter
Returns the supervisor emitter
625941f38e05c05ec3eea972
def confirm_ok(new_rules='/etc/pf.conf.new', good_rules='/etc/pf.conf'): <NEW_LINE> <INDENT> if len(__salt__['at.atq'](tag='pf')['jobs']) == 0: <NEW_LINE> <INDENT> return 'No pf at job found, not copying anything!' <NEW_LINE> <DEDENT> __salt__['at.atrm']('all', 'pf') <NEW_LINE> if __salt__['file.directory_exists'](good...
Confirm the given rules are working, removing the safeguard job and moving the temporary ruleset to it's destination. Both new_rules and good_rules can be single files as well as directories. CLI Example:: salt '*' pf.confirm_ok [new_rules=<file/directory>] [good_rules=<file/directory>] salt '*' pf.confirm_o...
625941f34f6381625f115033
def hop_between_brackets(self): <NEW_LINE> <INDENT> textCursor = self.editor.textCursor() <NEW_LINE> pos = textCursor.position() <NEW_LINE> whole_text = self.editor.toPlainText() <NEW_LINE> first_half = whole_text[:pos] <NEW_LINE> second_half = whole_text[pos:] <NEW_LINE> first_pos = first_half.rfind('(') <NEW_LINE> se...
Jump to closest bracket, starting with closing bracket.
625941f3f9cc0f698b140bee
def delete(self): <NEW_LINE> <INDENT> with open(self.db_conn, 'r') as f, open('edit.csv', 'w') as out: <NEW_LINE> <INDENT> cnt=sum(1 for line in open(self.db_conn)) <NEW_LINE> index=0 <NEW_LINE> delete=randint(1,cnt) <NEW_LINE> for line in f: <NEW_LINE> <INDENT> if(index!=delete): <NEW_LINE> <INDENT> out.write(line) <N...
This method made a random delete to provide a way to make some test
625941f35fdd1c0f98dc082d
def GetRecords(self,sensor,startTime,endTime): <NEW_LINE> <INDENT> if not sensor: <NEW_LINE> <INDENT> print('Sensor required to obtain record form') <NEW_LINE> raise DatabaseException('Sensor Required') <NEW_LINE> <DEDENT> rows = self.Select(self.recTable,['recData','recError','recDTG','recID'], 'recDTG ASC',senID=EQ(s...
Obtain records from a date range for a sensor Parameters: sensor - Sensor, sensor to obtain records from startTime - DateTime, starting time endTime - DateTime, ending time
625941f329b78933be1e5c9d
def create_field_option(self, list_id, field_id, field_option, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.create_field_option_with_http_info(list_id, field_id, field_option, **kwargs)
Create new field option # noqa: E501 Creates a field option # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_field_option(list_id, field_id, field_option, async_req=True) >>> result = thread.get() :param as...
625941f3498bea3a759ba0a5
def __init__( self, path_parameters: dict, query_parameters: MultiDict, body_parameters: dict, form_parameters: MultiDict, header_parameters: dict, files_parameters: dict, ): <NEW_LINE> <INDENT> self.path_parameters = path_parameters <NEW_LINE> self.query_parameters = query_parameters <NEW_LINE> self.body_parameters = ...
:param path_parameters: Parameters found in path, example: (for '/users/<user_id>') '/users/42' =>{'user_id': '42'} :param query_parameters: Parameters found in query, example: '/foo?group_id=1&group_id=2&deleted=false' => MultiDict( ( ('group_id', '1'), ('group_id', '2'), ...
625941f3e64d504609d74e37
def test_retrieve(self): <NEW_LINE> <INDENT> serializer = self.serializer_class(instance=self.instance) <NEW_LINE> expected = self.data <NEW_LINE> self.assertEqual(serializer.data, expected)
Serialize an instance of a model with a ManyToMany relationship.
625941f34527f215b584ca49
def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> Parameter.__init__(self, *args, **kargs) <NEW_LINE> if self.opts['type'] == 'color': <NEW_LINE> <INDENT> self.value = self.colorValue <NEW_LINE> self.saveState = self.saveColorState
Initialize the parameter. This is normally called implicitly through :meth:`Parameter.create`. The keyword arguments avaialble to :meth:`Parameter.__init__` are applicable.
625941f355399d3f05588cb0
def interface(confirm): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> get_name = input("Enter your name. ") <NEW_LINE> conn = sqlite3.connect("Bid.db") <NEW_LINE> cursor = conn.cursor() <NEW_LINE> sql = "SELECT * FROM Bid WHERE Name=?" <NEW_LINE> results = cursor.execute(sql, [get_name]) <NEW_LINE> bid_list = res...
Create interface allowing team members to bid on work.
625941f34d74a7450ccd47bd
def set_start_state(self, start_state: State): <NEW_LINE> <INDENT> start_state = self._pda_obj_creator.to_state(start_state) <NEW_LINE> self._states.add(start_state) <NEW_LINE> self._start_state = start_state
Sets the start state to the automaton Parameters ---------- start_state : :class:`~pyformlang.pda.State` The start state
625941f3baa26c4b54cb1711
@bacpypes_debugging <NEW_LINE> def object_type_encode(obj): <NEW_LINE> <INDENT> if _debug: object_type_encode._debug("object_type_encode %r", obj) <NEW_LINE> tag = Tag() <NEW_LINE> obj.encode(tag) <NEW_LINE> if _debug: object_type_endec._debug(" - tag: %r", tag) <NEW_LINE> return tag
Encode an ObjectType object into a tag.
625941f3d486a94d0b98e73f
def on_update(self, delta_time): <NEW_LINE> <INDENT> self.physics_engine.update() <NEW_LINE> coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) <NEW_LINE> for coin in coin_hit_list: <NEW_LINE> <INDENT> coin.remove_from_sprite_lists() <NEW_LINE> arcade.play_sound(self.collect_coin_s...
Movement and game logic
625941f3ec188e330fd5ad8a
def coerce( self, value ): <NEW_LINE> <INDENT> if isinstance( value, (str,unicode)): <NEW_LINE> <INDENT> value = [ float(x) for x in value.replace( ',', ' ').split()] <NEW_LINE> <DEDENT> if isinstance(value, field.NUMERIC_TYPES): <NEW_LINE> <INDENT> return arrays.array([float(value)],self.targetType) <NEW_LINE> <DEDENT...
Base coercion mechanism for floating point field types
625941f3925a0f43d254a475
def __call__( self, parameter_values: Sequence[float], quantum_kernel: QuantumKernel, data: np.ndarray, labels: np.ndarray, ) -> float: <NEW_LINE> <INDENT> return self.evaluate(parameter_values, quantum_kernel, data, labels)
This method calls the ``evaluate`` method. This is a convenient method to compute loss.
625941f36e29344779a62c09
def expr(self): <NEW_LINE> <INDENT> exprval = self.term() <NEW_LINE> while self._accept('PLUS') or self._accept('MINUS'): <NEW_LINE> <INDENT> op = self.tok.type <NEW_LINE> right = self.term() <NEW_LINE> if op == 'PLUS': <NEW_LINE> <INDENT> exprval += right <NEW_LINE> <DEDENT> elif op == 'MINUS': <NEW_LINE> <INDENT> exp...
expression ::= term { ('+'|'-') term }*
625941f3fff4ab517eb2fa38
def regex_overlap(text, regex): <NEW_LINE> <INDENT> overlap = [False for t in text] <NEW_LINE> for m in re.finditer(regex, ' '.join(text)): <NEW_LINE> <INDENT> begin, end = m.span() <NEW_LINE> i = 0 <NEW_LINE> for j, t in enumerate(text): <NEW_LINE> <INDENT> if begin <= i < end or begin <= i+len(t) < end: <NEW_LINE> <I...
for a list of tokens in text and a regex, match it in the tokens and return a list of booleans denoting which tokens are a part of the match
625941f35e10d32532c5f51d
def internalAddFile(filename, content, userkey, extra_tags=None, genFromFile=None, genFromVer=None): <NEW_LINE> <INDENT> fn = filename <NEW_LINE> new_hash = getGitBlobHash(content) <NEW_LINE> theDataKey = datamodel.DB_FileContent.all(keys_only=True).filter('__key__ =', db.Key.from_path(u'DB_FileContent', new_hash)).get...
extra_tags is a set like {'a','m'} - but usually either None or {'a'} - 'z' always gets added.
625941f399fddb7c1c9de985
def create_zone(self, domain, **kwargs): <NEW_LINE> <INDENT> data = {'name':domain} <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> data.update(kwargs) <NEW_LINE> <DEDENT> return self.post('zones', data)
AKA add a domain to cloudflare
625941f3fb3f5b602dac3c92
def get_from_database(self, full_name): <NEW_LINE> <INDENT> return self.task_database.get_value(self.task_path, full_name)
Access to a database value using full name. Parameters ---------- full_name : str Full name of the database entry, ie task_name + '_' + entry, where task_name is the name of the task that wrote the value in the database.
625941f3dd821e528d63b79c
def reboot(self): <NEW_LINE> <INDENT> command = adb_location + 'adb shell reboot' <NEW_LINE> try: <NEW_LINE> <INDENT> proc_reboot = subprocess.Popen(command, shell=True) <NEW_LINE> time.sleep(10) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(' adb shell reboot error') <NEW_LINE> raise e <...
단말기 재부팅시키기. adb shell reboot가 안정적인 재부팅 명령어인지는 확인해야한다. adb shell reboot 명령어 실행 후, 10초간격으로 adb연결된 device가 있는지 확인(재부팅 완료되었는지 확인) 연결을 확인한 후 10초 후 함수 종료 output- 재연결 확인이 완료되면 True반환
625941f392d797404e304785
def update_scene(scene, client=default): <NEW_LINE> <INDENT> return raw.put("data/entities/%s" % scene["id"], scene, client=client)
Save given scene data into the API.
625941f399cbb53fe67931dd
def printHashMap(self): <NEW_LINE> <INDENT> return self.hashMap
:return: hash map with all key/value pairs
625941f3cc0a2c11143dd48a
def get_apex_around(self, mz, tolerance): <NEW_LINE> <INDENT> ap_mz, ap_int, _ = self._get_apex_around(mz, tolerance) <NEW_LINE> return ap_mz, ap_int
Returns tuple of apex_mz, apex_int
625941f376d4e153a657f12b
def ArgOverride(self, args, overrides, pretty_print=True): <NEW_LINE> <INDENT> args.update(overrides) <NEW_LINE> if pretty_print: <NEW_LINE> <INDENT> self._PrettyPrintArgs(args, overrides)
Override arguments based on given overrides and provide nice output Args: args: dict of arguments to be passed to binary_search_state.Run (runs dict.update, causing args to be mutated). overrides: dict of arguments to update args with pretty_print: if True print out args/overrides to user in pretty forma...
625941f360cbc95b062c6b3c
def get_field(self, **kwargs): <NEW_LINE> <INDENT> return forms.CharField(**kwargs)
Get a Django form field for this type. The kwargs are passed directly to the field constructor. :param kwargs: Kwargs for field constructor. :type kwargs: dict :return: Form field. :rtype: django.forms.Field
625941f3091ae3566866754c
def _get_connection(self, *args): <NEW_LINE> <INDENT> return MyTelnetConnection(*args)
Can be overridden to use a custom connection.
625941f321bff66bcd684f45
def clone_matrix(mat): <NEW_LINE> <INDENT> return [[x for x in row] for row in mat]
Clones a 2D array :param mat: :return:
625941f34a966d76dd55160e
def p_apply_groups_spec(p): <NEW_LINE> <INDENT> p[0] = [] <NEW_LINE> for group in p[4]: <NEW_LINE> <INDENT> p[0].append(VarType(VarType.APPLY_GROUPS, group))
apply_groups_spec : APPLY_GROUPS ':' ':' one_or_more_strings
625941f345492302aab5e8c2
def dict_to_sql(csvfile, se, dest_table, dest_name, primary_key): <NEW_LINE> <INDENT> full_data = csv.DictReader(csvfile) <NEW_LINE> first_row = next(full_data) <NEW_LINE> assert primary_key in first_row.keys(), 'Not a valid key.' <NEW_LINE> order_keys = [item for item in first_row.keys() if item != ''] <NEW_LINE> prim...
Merges data from csvfile into dest_table at dest_name.
625941f3cdde0d52a9e53631
def RnnEncoder(name, _image_cnn, _rnn_encoder_dim): <NEW_LINE> <INDENT> batch_size = tf.shape(_image_cnn)[0] <NEW_LINE> height = tf.shape(_image_cnn)[1] <NEW_LINE> with tf.variable_scope(name): <NEW_LINE> <INDENT> def fn(x, i): <NEW_LINE> <INDENT> return BiRnn( name='encoder_bilstm', inputs=_image_cnn[:, i], units=_rnn...
Args: _image_cnn:the feature come fron cnn, shape is (B,H,W,C) _batchsize: must be a specific int number _rnn_encoder_dim: num unit of the rnn layer encode the feature in the height dimension, H * (B,W,C), it means rnn H times, and each time the input tensor is (B,W,C) return: encoder ou...
625941f3287bf620b61d4058
def read_val_names(val_names_path): <NEW_LINE> <INDENT> val_names = [] <NEW_LINE> f = open(val_names_path, 'r') <NEW_LINE> line = None <NEW_LINE> while 1: <NEW_LINE> <INDENT> line = f.readline().replace('\n', '') <NEW_LINE> if line is None or len(line) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> val_names.appen...
Read the filenames of validation images and labels into self.val_list
625941f338b623060ff0b3e5
def test_register_wrongpasswordformat(self): <NEW_LINE> <INDENT> check = user.create_user([], 'jj') <NEW_LINE> self.assertEqual(check, 'wrong data format')
check if wrong password format is entered
625941f350485f2cf553d395
def split(self, pagenum): <NEW_LINE> <INDENT> righthalf = Page(self.bottom, pagenum) <NEW_LINE> righthalf.keylist[:BTORDER // 2] = copy.deepcopy(self.keylist[BTORDER // 2:]) <NEW_LINE> righthalf.m = BTORDER // 2 <NEW_LINE> lefthalf = self <NEW_LINE> lefthalf.m = BTORDER // 2 <NEW_LINE> lefthalf.close() <NEW_...
splits a full page into 2 halves: lefthalf: M/2 items (original page) righthalf: M/2 items (a newly created page; brought into internal memory) returns (to its parent page) a reference to righthalf
625941f34f88993c3716c659
def test(self): <NEW_LINE> <INDENT> self.restore_model(self.test_iters) <NEW_LINE> if self.dataset == 'CelebA': <NEW_LINE> <INDENT> data_loader = self.celeba_loader <NEW_LINE> <DEDENT> elif self.dataset == 'RaFD': <NEW_LINE> <INDENT> data_loader = self.rafd_loader <NEW_LINE> <DEDENT> with torch.no_grad(): <NEW_LINE> <I...
Translate images using StarGAN trained on a single dataset.
625941f37d43ff24873a329e
def setUp(self): <NEW_LINE> <INDENT> self.test_net.reset()
In our *setUp()* method we call *reset()* to reset the network.
625941f36fece00bbac2dd3f
def generate_js_metadata(pkg_data, project_shortname): <NEW_LINE> <INDENT> importlib.import_module(project_shortname) <NEW_LINE> mod = sys.modules[project_shortname] <NEW_LINE> jsdist = getattr(mod, '_js_dist', []) <NEW_LINE> project_ver = pkg_data.get('version') <NEW_LINE> rpkgname = snake_case_to_camel_case(project_s...
Dynamically generate R function to supply JavaScript and CSS dependency information required by dashR package. Parameters ---------- project_shortname = component library name, in snake case Returns ------- function_string = complete R function code to provide component features
625941f3d6c5a10208144648
def is_empty(self): <NEW_LINE> <INDENT> return not self._gadgets
Check if the sizegroup is empty @return: true if the sizegroup doesn't have any gadgets @rtype: bool
625941f3711fe17d82542956
@pytest.fixture <NEW_LINE> def swift_cli(ctrl_remote): <NEW_LINE> <INDENT> return os_cli.Swift(ctrl_remote)
Swift cli client
625941f38da39b475bd65575
def is_bv_concat(self): <NEW_LINE> <INDENT> return self.node_type() == BV_CONCAT
Test whether the node is the BVConcat operator.
625941f3b830903b967e9efd
def _call(self, signal): <NEW_LINE> <INDENT> feat, energy = super(MFCC, self)._call(signal) <NEW_LINE> feat = np.log(feat) <NEW_LINE> feat = dct(feat, type=2, axis=1, norm='ortho')[:, :self.num_cep] <NEW_LINE> feat = self._lifter(feat, self.cep_lifter) <NEW_LINE> if self.append_energy: <NEW_LINE> <INDENT> feat[:, 0] = ...
Compute MFCC features from an audio signal. Args: signal: the audio signal from which to compute features. Should be an N*1 array Returns: A numpy array of size (NUMFRAMES by numcep) containing features. Each row holds 1 feature vector.
625941f321a7993f00bc82f5
def __init__(self, *, model_id=None, model_version=None, documents=None, aligned_elements=None, unaligned_elements=None): <NEW_LINE> <INDENT> self.model_id = model_id <NEW_LINE> self.model_version = model_version <NEW_LINE> self.documents = documents <NEW_LINE> self.aligned_elements = aligned_elements <NEW_LINE> self.u...
Initialize a CompareReturn object. :param str model_id: (optional) The analysis model used to compare the input documents. For the **Compare two documents** method, the only valid value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value o...
625941f396565a6dacc8fcc2
def __init__(self, name, temp, vmag, espectral_type, d): <NEW_LINE> <INDENT> self.nombre = name <NEW_LINE> self.temperatura = temp <NEW_LINE> self.magnitud_visual = vmag <NEW_LINE> self.tipo_espectral = espectral_type <NEW_LINE> self.diametro = d
Constructor de la clase estrella Inicializa los diferentes atributos
625941f3009cb60464c639a6
def update( self ): <NEW_LINE> <INDENT> pass
Updates the available command list.
625941f3d6c5a10208144649
def authenticate(username, password, service='login', tty="console", **kwargs): <NEW_LINE> <INDENT> encoding = 'utf-8' <NEW_LINE> if not isinstance(password, bytes): <NEW_LINE> <INDENT> password = password.encode(encoding) <NEW_LINE> <DEDENT> if not isinstance(username, bytes): <NEW_LINE> <INDENT> username = username.e...
Returns True if the given username and password authenticate for the given service. Returns False otherwise. :param string username: The username to authenticate. :param string password: The password in plain text. :param string service: The PAM service to authenticate against. Defaults to 'login'. :param string tty...
625941f3d268445f265b5468
def phone(self, message, china_mobile=None, china_union=None, china_telcom=None, other_telphone=None): <NEW_LINE> <INDENT> isChinaMobile = isChinaUnion = isChinaTelcom = isOtherTelphone = False <NEW_LINE> if re.match(china_mobile or self.ChinaMobile, message): <NEW_LINE> <INDENT> isChinaMobile = True <NEW_LINE> <DEDENT...
Validates a phone number. :param message: :param china_mobile: :param china_union: :param china_telcom: :param other_telphone: :return:
625941f363f4b57ef0001700
def PopupError(*args, title=None, button_color=(None, None), background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=False, icon=None, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)): <NEW_LINE> <INDENT> tbutton_color...
Popup with colored button and 'Error' as button text :param *args: Variable number of items to display :type *args: (Any) :param title: Title to display in the window. :type title: (str) :param button_color: button color (foreground, background) :type button_color: Tuple[str, str] :param background_color: color of bac...
625941f3293b9510aa2c3889
def upload_photo(filename, full_location, thumb_location): <NEW_LINE> <INDENT> bucket = get_bucket() <NEW_LINE> full_key = bucket.new_key("full/" + filename) <NEW_LINE> full_key.set_contents_from_filename(full_location) <NEW_LINE> full_key.set_acl('public-read') <NEW_LINE> full_url = full_key.generate_url(expires_in=0,...
Upload a photo and thumbnail to S3. Args: filename: (str) filename to store the file as on the server. full_location: (str) path to the full size image on disk. thumbnail_location: (str) path to the thumbnail image on disk. Returns: (str, str) the public URL for the full size and thumbnail images ...
625941f3283ffb24f3c55ef3
def __add__(self, param): <NEW_LINE> <INDENT> if isinstance(self, Image) and isinstance(param, Image): <NEW_LINE> <INDENT> a = self.data <NEW_LINE> b = param.data <NEW_LINE> im = Image(self) <NEW_LINE> im.filename = self.filename+'+'+param.filename <NEW_LINE> <DEDENT> elif isinstance(self, Image) and isinstance(param, ...
Syntax: a = b+c creates a new image 'a' which is the addition pixel by pixel of images b and c Redifine the '+' operation for 2 images or one image and one number
625941f371ff763f4b549c90
def getValue(self, state): <NEW_LINE> <INDENT> actions = self.getLegalActions(state) <NEW_LINE> if (len(actions) == 0): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> actionValues = [self.getQValue(state, action) for action in actions] <NEW_LINE> return max(actionValues)
Returns max_action Q(state,action) where the max is over legal actions. Note that if there are no legal actions, which is the case at the terminal state, you should return a value of 0.0.
625941f3236d856c2ad44ddd
def publish_split_topic_dsmr_reading(reading): <NEW_LINE> <INDENT> split_topic_settings = SplitTopicTelegramMQTTSettings.get_solo() <NEW_LINE> if not split_topic_settings.enabled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> config_parser = configparser.ConfigParser() <NEW_LINE> config_parser.read_string(split_topic_...
Publishes a DSMR reading to a broker, formatted in multiple topic per field name, if set and enabled.
625941f3be383301e01b5a73
def __init__(self, context, id, msg): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> print("--------------------Entered requesthandler--------------------") <NEW_LINE> self.context = context <NEW_LINE> self.msg = msg <NEW_LINE> self._id = id
RequestHandler :param context: ZeroMQ context :param id: Requires the identity frame to include in the reply so that it will be properly routed :param msg: Message payload for the worker to process
625941f38e71fb1e9831dd9f
def getMap(self): <NEW_LINE> <INDENT> return str(self.map)
Currently just returns the html of the initial picture I.E. is not interactive
625941f3f7d966606f6aa605
def _update_wrapper(self, o): <NEW_LINE> <INDENT> wrapped_func = self._wrapped.fget if self._wrapping_property else self._wrapped <NEW_LINE> functools.update_wrapper(o, wrapped_func)
Updates the given object with __name__, __doc__, etc. from the wrapped thing. Just like functools.update_wrapper, but handles the case where we are wrapping a property
625941f345492302aab5e8c3
def quiz_mega(request, question): <NEW_LINE> <INDENT> quiz = get_object_or_404(QuestionQuiz, id=question) <NEW_LINE> ans = quiz.throw_answers() <NEW_LINE> content = { 'question':quiz, 'ans':ans, } <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> if 'submit' in request.POST: <NEW_LINE> <INDENT> request.sessio...
This page load quiz questions and other informations which are needed to start quiz of every mixed lecture. All data is store in request.session. I program this in that way, that quest can use quizzes and see thier result without registration and login. Arguments: none Returns: Page with all quiz of lecture, wh...
625941f3de87d2750b860393
def _add_commands(self): <NEW_LINE> <INDENT> self.remove_command('help') <NEW_LINE> for attr in dir(self): <NEW_LINE> <INDENT> cmd = getattr(self, attr) <NEW_LINE> if isinstance(cmd, commands.Command): <NEW_LINE> <INDENT> self.add_command(cmd)
Adds commands automatically
625941f350812a4eaa59c914
def intSquareRoot(x): <NEW_LINE> <INDENT> return squareRoot(x, 0.5) + 1
Returns an integer number always bigger or equal than the square root of x
625941f32ae34c7f2600d729
def findall(text): <NEW_LINE> <INDENT> sentences = nltk.sent_tokenize(text) <NEW_LINE> sentences = [word2num(sentence) for sentence in sentences] <NEW_LINE> cand_sentences = ' '.join(find_candidates(sentences)) <NEW_LINE> nes = return_nes(cand_sentences) <NEW_LINE> return nes
Find sample sizes within a piece of text. Parameters ---------- text : str Text to clean. Returns ---------- nes : list of tuples or None Pairs of sample sizes and groups.
625941f324f1403a9260115a
def before(): <NEW_LINE> <INDENT> shutil.copyfile('/hosts', '/hosts.d/base')
task that moves the hosts file to the /hosts.d/base location :return:
625941f397e22403b379d595
def broadcast_gather(input, dim, index, sparse_grad=False, index_ndim=1): <NEW_LINE> <INDENT> index_shape = index.shape[-index_ndim:] <NEW_LINE> index = index.flatten(-index_ndim) <NEW_LINE> batch_shape = broadcast_shapes(input.shape[:dim], index.shape[:-1]) <NEW_LINE> input = input.expand(*batch_shape, *input.shape[di...
input: Size(batch_shape..., N, event_shape...) index: Size(batch_shape..., M) -> Size(batch_shape..., M, event_shape...)
625941f391af0d3eaac9c017
def cache_files(paths, env='base'): <NEW_LINE> <INDENT> _mk_client() <NEW_LINE> return __context__['cp.fileclient'].cache_files(paths, env)
Used to gather many files from the master, the gathered files will be saved in the minion cachedir reflective to the paths retrieved from the master. CLI Example:: salt '*' cp.cache_files salt://pathto/file1,salt://pathto/file1
625941f33c8af77a43ae3da1
def load_classifier_from_pickle(self, file_name=None): <NEW_LINE> <INDENT> if not file_name: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_name = max(glob.glob(os.path.join(__pickled_data_directory__, '*.classifier.gz')), key=os.path.getctime) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> self._lo...
Loads data from a GZipped binary dump of the data set Takes thw newest if no file name is provided :param file_name:
625941f3ad47b63b2c50a579
def test_model_evaluation(y_true: list, predictions, label_encoder: LabelEncoder, classification_type: str, runtime) -> None: <NEW_LINE> <INDENT> if label_encoder.classes_.size == 2: <NEW_LINE> <INDENT> y_true_inv = y_true <NEW_LINE> y_pred_inv = np.round_(predictions, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y...
Function to evaluate a loaded model not instantiated with the CnnModel class. :param y_true: Ground truth of the data in one-hot-encoding type. :param predictions: Labels predicted. :param label_encoder: The label encoder for y value (label). :param classification_type: The classification type. Ex: N-B-M: normal, benig...
625941f373bcbd0ca4b2c66f
def sedol_checksum(base): <NEW_LINE> <INDENT> weights = (1, 3, 1, 7, 3, 9) <NEW_LINE> assert len(base) == 6 <NEW_LINE> for badLetter in 'AEIO': <NEW_LINE> <INDENT> assert badLetter not in base <NEW_LINE> <DEDENT> check = sum([int(char, 36) * weights[n] for n, char in enumerate(base)]) <NEW_LINE> return str((10 - (check...
Stock Exchange Daily Official List (SEDOL) http://goo.gl/HxFWL
625941f36aa9bd52df0373a2