code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AuthOidc): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e3a4f1c619b28b0410
def test_boss_single(api): <NEW_LINE> <INDENT> bossId = 24723 <NEW_LINE> bossName = 'Selin Fireheart' <NEW_LINE> boss = api.boss(bossId) <NEW_LINE> assert boss['id'] == bossId <NEW_LINE> assert boss['name'] == bossName
Retreive a specific boss (Selin Fireheart)
625941e356b00c62f0f14a3c
def service_restart(self, name): <NEW_LINE> <INDENT> r = requests.get(self.url+'service/restart/'+name) <NEW_LINE> return r.json()
Restart a "service" on the REST server
625941e3460517430c39455c
def test_dns_question_hashablity(): <NEW_LINE> <INDENT> record1 = r.DNSQuestion('irrelevant', const._TYPE_A, const._CLASS_IN) <NEW_LINE> record2 = r.DNSQuestion('irrelevant', const._TYPE_A, const._CLASS_IN) <NEW_LINE> record_set = {record1, record2} <NEW_LINE> assert len(record_set) == 1 <NEW_LINE> record_set.add(recor...
Test DNSQuestions are hashable.
625941e3bd1bec0571d90a0f
def getImageDescriptor(self): <NEW_LINE> <INDENT> return self.sd
**SUMMARY** Returns the image descriptor. **RETURNS** Image descriptor - numpy.ndarray **EXAMPLE** >>> track = SURFTracker(image, pts, detector, descriptor, temp, skp, sd, tkp, td) >>> sd = track.getImageDescriptor()
625941e307d97122c4178c74
def process_data(file_name): <NEW_LINE> <INDENT> with open(file_name, 'rb') as f: <NEW_LINE> <INDENT> reader = csv.reader(f) <NEW_LINE> data = [tup[0].split() for tup in list(reader) if tup] <NEW_LINE> f.close() <NEW_LINE> <DEDENT> labels = [tup[0] for tup in data] <NEW_LINE> tups = [tup[1:] for tup in data] <NEW_LINE>...
Process data into tuple_dicts assuming LIBSVM format
625941e307f4c71912b11865
def impute(self, columns, method='median', all_null='raise'): <NEW_LINE> <INDENT> allowed = {'drop', 'raise', 'ignore'} <NEW_LINE> if all_null not in allowed: <NEW_LINE> <INDENT> raise ValueError( 'all_null must be one of: %s' % ', '.join(allowed)) <NEW_LINE> <DEDENT> self.verify_columns_in_dataset(columns) <NEW_LINE> ...
Perform missing value imputation for the given columns using the specified `pandas.DataFrame` method for the fill value. All NaN values in the columns will be replaced with this value. Args: columns (iterable of str): Column names to perform missing value imputation on. method (str): Name of the `panda...
625941e3b57a9660fec33c6a
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> if not head or not head.next: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> pre = cur = head <NEW_LINE> lookup = {} <NEW_LINE> while cur: <NEW_LINE> <INDENT> if cur.val in lookup: <NEW_LINE> <INDENT> pre.next = cur.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
:type head: ListNode :rtype: ListNode
625941e391f36d47f21ac8d7
def test_process(self): <NEW_LINE> <INDENT> name = "mymonitor" <NEW_LINE> ret = {"name": name, "changes": {}, "result": True, "data": {}, "comment": ""} <NEW_LINE> mock = MagicMock(side_effect=[{}, {name: 1}]) <NEW_LINE> with patch.dict(status.__salt__, {"status.pid": mock}): <NEW_LINE> <INDENT> comt = 'Process signatu...
Test to return whether the specified signature is found in the process tree.
625941e39b70327d1c4e11b7
def tz_strip(self, data_frame): <NEW_LINE> <INDENT> datetime_index = data_frame.index <NEW_LINE> data_frame.index = pandas.DatetimeIndex(datetime_index.values) <NEW_LINE> return None
tz_strip - Converts a tz-aware DatetimeIndex into a tz-naive DatetimeIndex, effectively baking the timezone into the internal representation. Parameters ---------- datetime_index : pandas.DatetimeIndex, tz-aware Returns ------- pandas.DatetimeIndex, tz-naive
625941e391af0d3eaac9bdfc
def evaluate_parser(filepath): <NEW_LINE> <INDENT> ovo = OvO('data/polyglot.pkl', 'data/train.txt') <NEW_LINE> train_trees = ListTrees('data/train.txt') <NEW_LINE> par = PCFGParser() <NEW_LINE> par.count_rules(train_trees.rules) <NEW_LINE> lex = PLexicon() <NEW_LINE> lex.learn(train_trees.rules_unchomsky) <NEW_LINE> y_...
Method to evaluate the parser :param filepath: path to save the results
625941e332920d7e50b285b4
def forward(self, state, action): <NEW_LINE> <INDENT> xs = torch.relu(self.fcs1(state)) <NEW_LINE> x = torch.cat((xs, action), dim=1) <NEW_LINE> x = torch.relu(self.fc2(x)) <NEW_LINE> return self.fc3(x)
Build a critic (value) network that maps (state, action) pairs -> Q-values.
625941e399cbb53fe6792fc6
def PointCloudObject(self,name,**kw): <NEW_LINE> <INDENT> pass
This function create a special polygon which have only point. @type name: string @param name: name of the pointCloud @type kw: dictionary @param kw: dictionary of arg options, ie : 'vertices' array of coordinates ; 'faces' int array of faces ; 'parent' hostAp parent object @rtype: hostApp obj @re...
625941e3507cdc57c63070c4
@zope.component.adapter(zope.interface.Interface) <NEW_LINE> @zope.interface.implementer(icemac.addressbook.principals.interfaces.IRoot) <NEW_LINE> def principal_root(principal): <NEW_LINE> <INDENT> return zope.component.hooks.getSite()
Return the site root.
625941e34a966d76dd5513f3
def flatten(inputList): <NEW_LINE> <INDENT> for el in inputList: <NEW_LINE> <INDENT> if isinstance(el, collections.Iterable) and not isinstance(el, basestring): <NEW_LINE> <INDENT> for sub in flatten(el): <NEW_LINE> <INDENT> yield sub <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield el
Return a flattened genertor from an input list. Usage: inputList = [['a'], ['b', 'c', 'd'], [['e']], ['f']] list(flatten(inputList)) >> ['a', 'b', 'c', 'd', 'e', 'f']
625941e3c4546d3d9de72e17
def add_vertex(self, after_vertex_id, vertex_type='linear', edge_type='identity'): <NEW_LINE> <INDENT> changed_edge = None <NEW_LINE> for i in self.vertices[after_vertex_id - 1].edges_out: <NEW_LINE> <INDENT> if i.to_vertex == self.vertices[after_vertex_id]: <NEW_LINE> <INDENT> self.vertices[after_vertex_id - 1].edges_...
3.0: 所有 vertex 和 edg 中记录的都是引用
625941e391af0d3eaac9bdfd
def divide(self, value1, value2): <NEW_LINE> <INDENT> if int(value2) == 0: <NEW_LINE> <INDENT> return [1, 'Não pode haver divisão por zero'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [0, int(value1) / int(value2)]
Divide dois valores inteiros
625941e35fdd1c0f98dc0615
def sendResult(to, status): <NEW_LINE> <INDENT> return None
发送结果,感谢或者举报警告
625941e31b99ca400220ae93
def distancePoints(a, b): <NEW_LINE> <INDENT> return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
Returns the distance between two points
625941e30c0af96317bb85c8
def run(self): <NEW_LINE> <INDENT> self.continue_working = self.comm.bcast(root = mpihelper.MASTER) <NEW_LINE> while self.continue_working: <NEW_LINE> <INDENT> position, current_set = self._receive_next_set() <NEW_LINE> while not position < 0: <NEW_LINE> <INDENT> result = self._get_solution(position, current_set) <NEW_...
Primary method that is called on the worker processors. Each worker continues to listen for incoming parameter set data as long as the value of position is non-negative. The continue_working attribute is used to establish an outer loop that continues until a False value is broadcast by the master processor, when its st...
625941e3cdde0d52a9e53416
def _stat_permissions(self, fp): <NEW_LINE> <INDENT> return fp.getPermissions()
Get the filepath's permissions object @param fp: L{twisted.python.filepath.FilePath} @return: L{twisted.python.filepath.Permissions} of C{fp}
625941e32c8b7c6e89b35b9e
def getSlendernessZ(self,Leq): <NEW_LINE> <INDENT> return Leq/self.getGyrationRadiusZ()
return buckling slendernes relative to z-axis (strong axis) :param Leq: buckling length in XY buckling plane.
625941e363d6d428bbe448d1
def create_subject(self, name, description=None, external_id=None, public_read=False, public_write=False): <NEW_LINE> <INDENT> return CogniacSubject.create(self, name=name, description=description, external_id=external_id, public_read=public_read, public_write=public_write)
Create a CogniacSubject name (String): Name of new subject description (String): Optional description of the subject public_read(Bool): Subject media is accessible to other tenants and can be input into other tenant's apps. public_write(Bool): Oth...
625941e30fa83653e4657399
def resultUniq(): <NEW_LINE> <INDENT> revmapped_fls = [file for file in os.listdir('./output') if re.search(r'revmapped.csv', file)] <NEW_LINE> print ('Revamapped files:',revmapped_fls) <NEW_LINE> print ('\nCombining all the revamapped files for uniq and table update\n') <NEW_LINE> revamappedComb = './output/ALL_revama...
Read revmapped files, remove header, combine files parse on pval,Uniq on miRname, tarname and cleavesite
625941e30383005118ecf9c2
def get(self, ph_type, default=None): <NEW_LINE> <INDENT> for placeholder in self: <NEW_LINE> <INDENT> if placeholder.ph_type == ph_type: <NEW_LINE> <INDENT> return placeholder <NEW_LINE> <DEDENT> <DEDENT> return default
Return the first placeholder shape with type *ph_type* (e.g. 'body'), or *default* if no such placeholder shape is present in the collection.
625941e397e22403b379d37c
def test_equal_on_equal(self): <NEW_LINE> <INDENT> a = payloads.CreateKeyPairResponsePayload() <NEW_LINE> b = payloads.CreateKeyPairResponsePayload() <NEW_LINE> self.assertTrue(a == b) <NEW_LINE> self.assertTrue(b == a) <NEW_LINE> a = payloads.CreateKeyPairResponsePayload( private_key_unique_identifier=( "7f7ee394-40f9...
Test that the equality operator returns True when comparing two CreateKeyPair response payloads with the same data.
625941e324f1403a92600f43
def load(Loader, representation, namespace=None, name=None, options=None, **kwargs): <NEW_LINE> <INDENT> Loader = _make_backwards_compatible_loader(Loader) <NEW_LINE> context = get_representation_context(representation) <NEW_LINE> if not is_compatible_loader(Loader, context): <NEW_LINE> <INDENT> raise IncompatibleLoade...
Use Loader to load a representation. Args: Loader (Loader): The loader class to trigger. representation (str or io.ObjectId or dict): The representation id or full representation as returned by the database. namespace (str, Optional): The namespace to assign. Defaults to None. name (str, Option...
625941e33cc13d1c6d3c7759
def pve_redirect(request): <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('pvestats:pvestats', kwargs = {'stat': 'number_nightfalls'}))
Redirects to pve main landing page. Used information from this helpful site: https://overiq.com/django/1.10/redirecting-urls-in-django/
625941e34527f215b584c834
def k_right(self): <NEW_LINE> <INDENT> if self.cursor_position < len(self.text): <NEW_LINE> <INDENT> self.cursor_position += 1
Handles the right arrow key
625941e363f4b57ef00014ef
def get_network_sm_cellular_usage_history(self, options=dict()): <NEW_LINE> <INDENT> self.validate_parameters(network_id=options.get("network_id"), device_id=options.get("device_id")) <NEW_LINE> _url_path = '/networks/{networkId}/sm/{deviceId}/cellularUsageHistory' <NEW_LINE> _url_path = APIHelper.append_url_with_templ...
Does a GET request to /networks/{networkId}/sm/{deviceId}/cellularUsageHistory. Return the client's daily cellular data usage history. Usage data is in kilobytes. Args: options (dict, optional): Key-value pairs for any of the parameters to this API Endpoint. All parameters to the endpoint are supp...
625941e323849d37ff7b346d
def t130000_x3(actionbutton1=_, flag1=6001, flag2=6000): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> assert (not GetOneLineHelpStatus() and not IsTalkingToSomeoneElse() and not IsClientPlayer() and not IsPlayerDead() and not IsCharacterDisabled()) <NEW_LINE> assert CompareBonfireState(1) <NEW_LINE> if GetEventS...
State 0
625941e31d351010ab855efc
def multi_model(self, local_tm=False): <NEW_LINE> <INDENT> if local_tm: <NEW_LINE> <INDENT> models = self.local_tm_models <NEW_LINE> self.pipes = self.local_tm_models <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> models = self.mf_models <NEW_LINE> <DEDENT> self.pipes = [] <NEW_LINE> for i in range(len(models)): <NEW_LI...
Function for optimisation of all model-free models.
625941e3004d5f362079a712
def ensure_no_workspans_conflicts(self, workspan): <NEW_LINE> <INDENT> print("-> workspans conflicts") <NEW_LINE> today = workspan["from"].replace(hour=0, minute=0, second=0, microsecond=0) <NEW_LINE> tomorow = today + relativedelta(days=1) <NEW_LINE> todays_workspans = adb.get_user_workspans(self.mdb, self.user_id, to...
K fungování předpokládá, že v jedné instanci této třídy je přidán jen jeden workspan za den. Předpoklad je splněn při přidávání po jednom (v ApiAddWorkspanHandler) a přidávání celého měsíce (v ApiEditMonthWorkspansHandler).
625941e3fb3f5b602dac3a78
def test_capture_snapshot(sdc_builder, sdc_executor): <NEW_LINE> <INDENT> pipeline_builder = sdc_builder.get_pipeline_builder() <NEW_LINE> data = [ {'NAME': 'Alex Sanchez', 'ROLE': 'Tech Lead', 'AGE': 27, 'TEAM': 'Data Plane'}, {'NAME': 'Martin Balzamo', 'ROLE': 'Manager', 'AGE': 50, 'TEAM': 'BCN'}, {'NAME': 'Tucu', 'R...
Verify the most basic use case for capture_snapshot where we capture the data and assert with the original.
625941e3d8ef3951e324391f
def partition_numbers_linear_1pass(A, pivot_idx): <NEW_LINE> <INDENT> i, j, k = 0, len(A)-1, 0 <NEW_LINE> pivot = A[pivot_idx] <NEW_LINE> while k <= j: <NEW_LINE> <INDENT> if A[k] < pivot: <NEW_LINE> <INDENT> A[i], A[k] = A[k], A[i] <NEW_LINE> i, k = i + 1, k + 1 <NEW_LINE> <DEDENT> elif A[k] > pivot: <NEW_LINE> <INDEN...
i -> tracks indices for nos < pivot j -> tracks indices for nos > pivot k -> tracks the index of the current number
625941e35510c4643540f7bb
def gui_loop(gui_queue: Queue, chain_queue: Queue, command_queue, keystore: Keystore): <NEW_LINE> <INDENT> app = QApplication(sys.argv) <NEW_LINE> ex = ChainGUI(keystore, chain_queue, gui_queue, command_queue) <NEW_LINE> sys.exit(app.exec_())
Main function of the GUI thread, creates the GUI, passes the queues to it, and starts the execution. Args: gui_queue: Queue for messages addressed to the GUI chain_queue: Queue for messages addressed to the blockchain command_queue: Queue for commands to the core thread. keystore: Keystore object, obtai...
625941e3a17c0f6771cbe430
def reorder_time_slots(self, new_patients): <NEW_LINE> <INDENT> self.patients = new_patients <NEW_LINE> for slot in self.time_slots: <NEW_LINE> <INDENT> slot['patient'] = None <NEW_LINE> <DEDENT> last_slot = 0 <NEW_LINE> for patient in self.patients: <NEW_LINE> <INDENT> required_slots = self._get_required_slots(patient...
Updates the existing time slots and patients with the ones given. :param new_patients: The patients (sorted by appointment time in ascending order) to update with.
625941e3f7d966606f6aa3ea
def __init__(self, name): <NEW_LINE> <INDENT> self._logger = logging.getLogger( name ) <NEW_LINE> Process.__init__( self, name=name ) <NEW_LINE> return
This is the base constructor method that receives :param name: The plugin name :param tag: The plugin category :param logstash: The logstash process handle :return:
625941e3b545ff76a89141f6
def check_class(self, run, correct_database_code, msg=None): <NEW_LINE> <INDENT> self.open(msg) <NEW_LINE> db_class = (run.theory[run.DATABASE] | run.theory[run.CLASSIFY_THEORY].database) <NEW_LINE> self.showdb(run) <NEW_LINE> correct = runtime.string_to_database(correct_database_code) <NEW_LINE> self.check_db_diffs(db...
Check that runtime RUN's classify + database theories have exactly the contents CORRECT_DATABASE_CODE.
625941e329b78933be1e5a88
def convert_to_gif( fps: int = 30, resolution: int = 640, filename: str = None, dirname: str = None, ): <NEW_LINE> <INDENT> mp4_pathname = os.path.join(dirname, filename) <NEW_LINE> gif_filename = filename[:-4] + ".gif" <NEW_LINE> gif_pathname = os.path.join(dirname, gif_filename) <NEW_LINE> create_palette_command = [ ...
Convert an mp4 video to a gif.
625941e3009cb60464c63790
def _preprocess_data(X, y, fit_intercept, normalize=False, copy=True, sample_weight=None, return_mean=False): <NEW_LINE> <INDENT> if isinstance(sample_weight, numbers.Number): <NEW_LINE> <INDENT> sample_weight = None <NEW_LINE> <DEDENT> X = check_array(X, copy=copy, accept_sparse=['csr', 'csc'], dtype=FLOAT_DTYPES) <NE...
Centers data to have mean zero along axis 0. If fit_intercept=False or if the X is a sparse matrix, no centering is done, but normalization can still be applied. The function returns the statistics necessary to reconstruct the input data, which are X_offset, y_offset, X_scale, such that the output X = (X - X_offse...
625941e38e71fb1e9831db89
def backward(self, top, propagate_down, bottom): <NEW_LINE> <INDENT> if any(propagate_down): <NEW_LINE> <INDENT> raise Exception("There is no proper gradient for the WHDR." "Consider using the whdr hinge loss layer" "that gives an approximation to the WHDR.")
Backward pass of the layer.
625941e35fc7496912cc3d5f
def select(self, *cols): <NEW_LINE> <INDENT> if not cols: <NEW_LINE> <INDENT> cols = ["*"] <NEW_LINE> <DEDENT> if isinstance(cols[0], basestring): <NEW_LINE> <INDENT> cols = [_create_column_from_name(n) for n in cols] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cols = [c._jc for c in cols] <NEW_LINE> <DEDENT> jcols =...
Selecting a set of expressions.:: df.select() df.select('colA', 'colB') df.select(df.colA, df.colB + 1)
625941e331939e2706e4d246
def __init__(self, repo, path, object_id, size=0): <NEW_LINE> <INDENT> self.client = repo.client <NEW_LINE> self.repo = repo <NEW_LINE> self.path = path <NEW_LINE> self.id = object_id <NEW_LINE> self.size = size
:param:`path` the full path of this entry within its repo, like "/documents/example.md" :param:`size` The size of a file. It should be zero for a dir.
625941e3a219f33f34628d45
def get_arduino_info(p): <NEW_LINE> <INDENT> return BOARDS.get((p.vid, p.pid), None)
Get the manufacturer and type information for an Arduino.
625941e33539df3088e2e72c
def add_balance(self, twitch_username, amount): <NEW_LINE> <INDENT> entry = self.db.execute("SELECT * FROM users WHERE twitchUsername=?",(twitch_username,)).fetchone() <NEW_LINE> if entry: <NEW_LINE> <INDENT> balance = entry[2] <NEW_LINE> balance = balance + amount <NEW_LINE> self.set_balance(twitch_username, balance) ...
Adds to a user's account balance Parameters: twitch_username: The twitch username of the user amount: The amount to add to the user's account
625941e3656771135c3ebc54
def atcab_info_base(mode, param2, out_data): <NEW_LINE> <INDENT> c_out_data = create_string_buffer(4) <NEW_LINE> if not isinstance(out_data, bytearray): <NEW_LINE> <INDENT> status = Status.ATCA_BAD_PARAM <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status = _CRYPTO_LIB.atcab_info_base(mode, param2, byref(c_out_data)) ...
Issues an Info command, which return internal device information and can control GPIO and the persistent latch. Args: mode Selects which mode to be used for info command.(int) param2 Selects the particular fields for the mode.(int) out_data Response from info command ...
625941e3a8370b7717052c7f
def get_latest(self): <NEW_LINE> <INDENT> self.cprint("##\tGetting max page number...\n", log=True) <NEW_LINE> return 1
Will always be 1 because we are viewing all content on a single page :return: id of the newest item
625941e32ae34c7f2600d512
def where_does_a_meets_b(a_step, b_offset, b_step, cutoff): <NEW_LINE> <INDENT> step = max([a_step, b_step]) <NEW_LINE> start = 0 if a_step >= b_step else b_offset <NEW_LINE> while start <= cutoff: <NEW_LINE> <INDENT> if start == 0: <NEW_LINE> <INDENT> start += step <NEW_LINE> continue <NEW_LINE> <DEDENT> if start % a_...
Where does bus A meets with bus B, given that B starter at b_offset time. step A|(------)(------)(------)(------)(------)(------)(------)(------) <- here B| b offset ](-----------)(-----------)(-----------)(-----------) the step is the cycle time of the bus. find the bigger step (so we get fast to the poit where...
625941e3de87d2750b860178
def chdir(debugger, args, result, dict): <NEW_LINE> <INDENT> new_dir = args.strip() <NEW_LINE> if not new_dir: <NEW_LINE> <INDENT> new_dir = os.path.expanduser('~') <NEW_LINE> <DEDENT> elif new_dir == '-': <NEW_LINE> <INDENT> if not Holder.prev_dir(): <NEW_LINE> <INDENT> print("bad directory, not changing") <NEW_LINE> ...
Change the working directory, or cd to ${HOME}. You can also issue 'cd -' to change to the previous working directory.
625941e3dd821e528d63b587
def m2_excess(topic_m2_srs, ref_srs): <NEW_LINE> <INDENT> return excess(topic_m2_srs, ref_srs)
Calcs the m2 excess return v. the reference. Args: topic_m2_srs (Panads DataFrame of float): An m2 return or series of returns. ret_srs (Pandas DataFrame of float): The benchmark return or series of returns. Returns: Pandas DataFrame of float: An excess return series.
625941e357b8e32f5248387f
def getNotificationRecipients(min_level): <NEW_LINE> <INDENT> pass
Return the people who should be notified. Recipients will be returned as a dictionary where the key is the person, and the values are (subscription, rationale) tuples. :param min_level: The minimum notification level needed to be notified.
625941e3bde94217f36831cf
def get_buckets_for_sent_metafield(fieldName, langID=-1, docIDs=None, maxBuckets=300): <NEW_LINE> <INDENT> if fieldName not in settings['search_meta']['stat_options'] or langID >= len(settings['languages']) > 1: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if langID >= 0: <NEW_LINE> <INDENT> innerQuery = {'match':...
Group all sentences into buckets, each corresponding to one of the unique values for the fieldName metafield. Consider only top maxBuckets field values (in terms of document count). If langID is provided, count only data for a particular language. Return a dictionary with the values and corresponding sentence/word coun...
625941e34f88993c3716c445
def dataReceived(self, data): <NEW_LINE> <INDENT> self.resetTimeout() <NEW_LINE> try: <NEW_LINE> <INDENT> events = self.conn.receive_data(data) <NEW_LINE> <DEDENT> except h2.exceptions.ProtocolError: <NEW_LINE> <INDENT> dataToSend = self.conn.data_to_send() <NEW_LINE> self.transport.write(dataToSend) <NEW_LINE> self.tr...
Called whenever a chunk of data is received from the transport. @param data: The data received from the transport. @type data: L{bytes}
625941e34e696a04525c982f
def commit_append_to_file(self, message, relative_path, to_append): <NEW_LINE> <INDENT> self.add_append_to_file(relative_path, to_append) <NEW_LINE> self._repo.call('commit', '-m', message, '--', relative_path)
Create and commit a new file. :message: the string content of the commit message :relative_path: the path of the file, relative to the repo :to_append: the string contents to append to the file :returns: None
625941e330dc7b7665901d44
def test_text_rendering_with_encoded_html_entities(self): <NEW_LINE> <INDENT> root_tree_node = RootTreeNode() <NEW_LINE> tree_node = root_tree_node.new_child('noparse', NoParseTreeNode, content='[u]... &lt;some text&gt;[/u]') <NEW_LINE> rendered_output = tree_node.render_text('') <NEW_LINE> expected_output = '[u]... <s...
Test text rendering with encoded HTML entities.
625941e3cc40096d61595d31
def latest(self, **kwargs: Any) -> "models.query.QuerySet[Submission]": <NEW_LINE> <INDENT> return self.filter(**kwargs).order_by("user", "-created_at").distinct("user")
Returns a set of all the latest submissions for all users
625941e385dfad0860c3b23d
def set_resource(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._connection_fsm.on_event(DriverEvent.SET, DriverEvent.SET, *args, **kwargs)
Set device parameters. @param args[0] parameter : value dict of parameters to set. @param timeout=timeout Optional command timeout. @raises InstrumentParameterException if missing or invalid set parameters. @raises InstrumentTimeoutException if could not wake device or no response. @raises InstrumentProtocolException i...
625941e3bf627c535bc135b1
def list_files_by_size(path_dir: str) -> Dict[str: int]: <NEW_LINE> <INDENT> files = dict() <NEW_LINE> for file in os.listdir(path_dir): <NEW_LINE> <INDENT> if os.path.isfile(file): <NEW_LINE> <INDENT> path_file = os.path.join(path_dir, file) <NEW_LINE> size = os.path.getsize(path_file) <NEW_LINE> files[path_file] = si...
Compute the size in bytes of all files in a directory. Ignore all directories. Follows symbolic links.
625941e3099cdd3c635f103b
@pytest.mark.parametrize( "cls, should_handle", [(int, True), (float, True), (datetime, True), (ModelType(Card), True)], ) <NEW_LINE> def test_can_handle(object_serializer_set, cls, should_handle): <NEW_LINE> <INDENT> object_serializer_set[cls]
the object serializer set should not raise an exception if it can handle these types.
625941e37c178a314d6ef847
def _get_result_wrapper(self, query): <NEW_LINE> <INDENT> db = query.database <NEW_LINE> if query._tuples: <NEW_LINE> <INDENT> QRW = db.get_result_wrapper(RESULTS_TUPLES) <NEW_LINE> <DEDENT> elif query._dicts: <NEW_LINE> <INDENT> QRW = db.get_result_wrapper(RESULTS_DICTS) <NEW_LINE> <DEDENT> elif query._naive or not qu...
Get result wrapper class.
625941e330bbd722463cc1aa
def test_fstab_present_test_change(self): <NEW_LINE> <INDENT> ret = { 'name': '/dev/sda1', 'result': None, 'changes': {}, 'comment': ['/home entry will be updated in /etc/fstab.'], } <NEW_LINE> grains_mock = {'os': 'Linux'} <NEW_LINE> opts_mock = {'test': True} <NEW_LINE> salt_mock = { 'mount.set_fstab': MagicMock(retu...
Test fstab_present
625941e33cc13d1c6d3c775a
def get_from_end(self, idx): <NEW_LINE> <INDENT> if idx >= self.num: <NEW_LINE> <INDENT> raise Exception("Out of Index Boundary Exception") <NEW_LINE> <DEDENT> idx = self.num - idx <NEW_LINE> return self.get(idx)
Get the Nth element from end. :param idx: :return:
625941e382261d6c526ab887
def _graph_connected_component(graph, node_id): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> from scipy import sparse <NEW_LINE> n_node = graph.shape[0] <NEW_LINE> if sparse.issparse(graph): <NEW_LINE> <INDENT> graph = graph.tocsr() <NEW_LINE> <DEDENT> connected_nodes = np.zeros(n_node, dtype=np.bool) <NEW_LINE> n...
Find the largest graph connected components that contains one given node Parameters ---------- graph : array-like, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes node_id : int The index of the query node of the graph Returns ------- connected_com...
625941e356b00c62f0f14a3d
def body(self): <NEW_LINE> <INDENT> return ' {}'.format(self._requirement_name())
Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with populate_link() having already been called
625941e3090684286d50f0cc
@pytest.mark.skipif( 'CI' in os.environ, reason="These tests fail in Github CI for unknown reasons" ) <NEW_LINE> @pytest.mark.parametrize( "command,signal_timeout,signal,expected", [ ( "sipplauncher --testsuite tmp-testsuite --dut 1.1.1.1 --group 3 --dry-run", 1, signal.SIGINT, False ), ( "sipplauncher --testsuite tmp-...
Testing reaction to signal
625941e326068e7796caf0c6
def complete_data(data): <NEW_LINE> <INDENT> for key, value in data.items(): <NEW_LINE> <INDENT> if value or (key == PRIORITY and value is 0): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key == ATTRIBUTE or data.get(ATTRIBUTE, False): <NEW_LINE> <INDENT> i_value = match_value_parameter(data) <NEW_LINE> <DEDENT>...
Prompt user to enter previously unentered or invalid data. :param data: A dict of required data names and their current values. :return: None.
625941e3e1aae11d1e74a09d
def _keep_encoder_param(self, sess): <NEW_LINE> <INDENT> for i in range(len(self.vae_layer_type_list)): <NEW_LINE> <INDENT> W_enc = sess.run(self.encoder_layers[i].W) <NEW_LINE> b_enc = sess.run(self.encoder_layers[i].b) <NEW_LINE> self.W_enc_const[i] = tf.constant(W_enc, dtype='float32') <NEW_LINE> self.b_enc_const[i]...
keep encoder parameters when you use transfer learning :param sess: tf.Session() :return
625941e357b8e32f52483880
def test_generate_report(self): <NEW_LINE> <INDENT> u1 = User.objects.create_user('Yoshi') <NEW_LINE> v1 = Volunteer( first_name="Yoshi", last_name="Turtle", address="Mario Land", city="Nintendo Land", state="Nintendo State", country="Nintendo Nation", phone_number="2374983247", email="yoshi@nintendo.com", user=u1 ) <N...
Tests test_generate_report(volunteer_shift_list)
625941e3f9cc0f698b1409da
@channel_session <NEW_LINE> def ws_connect(message): <NEW_LINE> <INDENT> if message['path'] == '/chat': <NEW_LINE> <INDENT> clientName = _getClientName(message['client']) <NEW_LINE> logger.info('New client connected: {}'.format(clientName)) <NEW_LINE> Group(clientName).add(message.reply_channel) <NEW_LINE> message.chan...
Called when a client try to open a WebSocket Args: message (Obj): object containing the client query
625941e3a05bb46b383ecc00
def get_temperature_load(ts, coors, region=None): <NEW_LINE> <INDENT> x = coors[:, 0] <NEW_LINE> return (x - x.min())**2 - T0
Temperature load depends on the `x` coordinate.
625941e38e7ae83300e4b3b0
def grid_bbox(self, column=None, row=None, col2=None, row2=None): <NEW_LINE> <INDENT> args = ('grid', 'bbox', self._w) <NEW_LINE> if column is not None and row is not None: <NEW_LINE> <INDENT> args = args + (column, row) <NEW_LINE> <DEDENT> if col2 is not None and row2 is not None: <NEW_LINE> <INDENT> args = args + (co...
Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid. If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell. The returned integers specify ...
625941e3b57a9660fec33c6b
def setPixelFormat(bpp, depth, bigEndian, trueColor, redMax, greenMax, blueMax, redShift, greenShift, blueShift): <NEW_LINE> <INDENT> return struct.pack('!BBBBHHHBBBBBB', bpp, depth, int(bigEndian), int(trueColor), redMax, greenMax, blueMax, redShift, greenShift, blueShift, 0, 0, 0)
TODO: Figure out what's wrong here... according to the standard then the message below needs padding before and after. But according to reverse engineering of x11vnc then that's not the case! RFB 6.4.1
625941e3498bea3a759b9e90
def remove_mentions(s): <NEW_LINE> <INDENT> return re.sub(r"\@\w+", "", s)
Remove mentions from a string str. Remove the entire mention, as the username is mostly irrelevant. Example: "Hello @bobbros okay" -> "Hello okay" :param s: string to clean :return: string: cleaned string
625941e38da39b475bd6535a
def get_correct_answers(question_id, correct_answer=True): <NEW_LINE> <INDENT> correct_answers = list() <NEW_LINE> question = Question.query.filter_by(id=question_id).first() <NEW_LINE> question_type = question.question_type <NEW_LINE> if question_type == 'MCQ': <NEW_LINE> <INDENT> mcq = MCQ.query.filter_by(question_id...
Returns all the correct or incorrect answers (depending on correct_answer argument input)
625941e356ac1b37e62645aa
def testFormatEventValues(self): <NEW_LINE> <INDENT> formatter_helper = firefox.FirefoxHistoryURLHiddenFormatterHelper() <NEW_LINE> event_values = {'hidden': '1'} <NEW_LINE> formatter_helper.FormatEventValues(event_values) <NEW_LINE> self.assertEqual(event_values['url_hidden_string'], '(URL hidden)') <NEW_LINE> event_v...
Tests the FormatEventValues function.
625941e356b00c62f0f14a3e
def get_updated_field(self): <NEW_LINE> <INDENT> pass
created
625941e3627d3e7fe0d69233
@pytest.mark.parametrize( "source", [StreamSource.CLOUDFRONT, StreamSource.YOUTUBE, None] ) <NEW_LINE> @pytest.mark.parametrize("max_uploads", [2, 4]) <NEW_LINE> def test_upload_youtube_videos(mocker, source, max_uploads): <NEW_LINE> <INDENT> settings.YT_UPLOAD_LIMIT = max_uploads <NEW_LINE> private_videos = VideoFacto...
Test that the upload_youtube_videos task calls YouTubeApi.upload_video & creates a YoutubeVideo object for each public video, up to the max daily limit
625941e33539df3088e2e72d
def section_end_distances(neurites, neurite_type=NeuriteType.all): <NEW_LINE> <INDENT> return map_sections(sectionfunc.section_end_distance, neurites, neurite_type=neurite_type)
section end to end distances in a collection of neurites
625941e3090684286d50f0cd
def TransformProperty(source, transform_func=None, *args, **kwargs): <NEW_LINE> <INDENT> if transform_func: <NEW_LINE> <INDENT> return _TransformProperty(source, transform_func, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def decorate(decorated_func): <NEW_LINE> <INDENT> return _TransformProperty(sou...
Implements a 'transform' datastore property. TransformProperties are similar to DerivedProperties, but with two main differences: - Instead of acting on the whole model, the transform function is passed the current value of a single property which was specified in the constructor. - Property values are calculated wh...
625941e3bd1bec0571d90a11
def mpdist_vector(ts, ts_b, w): <NEW_LINE> <INDENT> matrix = mass_distance_matrix(ts, ts_b, w) <NEW_LINE> rows, cols = matrix.shape <NEW_LINE> all_right_hist = matrix.min(axis=0) <NEW_LINE> mass_minimums = np.apply_along_axis(core.moving_min, 1, matrix, window=rows) <NEW_LINE> mpdist_length = len(ts) - len(ts_b) + 1 <N...
Computes a vector of MPDist measures. Parameters ---------- ts : array_like The time series to compute the matrix for. ts_b : array_like The time series to compare against. w : int The window size. Returns ------- array_like : mpdist_vector The MPDist vector.
625941e3460517430c39455e
def inverseStarPrint(size): <NEW_LINE> <INDENT> linenum = size <NEW_LINE> while(linenum): <NEW_LINE> <INDENT> temp = linenum <NEW_LINE> while(temp): <NEW_LINE> <INDENT> print("*", end="") <NEW_LINE> temp -= 1 <NEW_LINE> <DEDENT> print("\n", end="") <NEW_LINE> linenum -= 1
This function will print the star pattern in inverted form
625941e36e29344779a629f2
@tf.function <NEW_LINE> def decode_predictions(predictions, num_classes, num_boxes=2): <NEW_LINE> <INDENT> if not tf.is_tensor(predictions): <NEW_LINE> <INDENT> predictions = tf.cast(predictions, dtype=tf.float32) <NEW_LINE> <DEDENT> class_indexes = tf.math.argmax(predictions[..., :num_classes], axis=-1) <NEW_LINE> cla...
decodes predictions of the YOLO v1 model Converts bounding boxes output from Yolo with an image split size of GRID into entire image ratios rather than relative to cell ratios. Arguments: predictions (Tensor): predictions of the YOLO v1 model with shape '(1, 7, 7, (num_boxes*5 + num_classes))' num_classes: N...
625941e332920d7e50b285b6
def __contains__(self, dat): <NEW_LINE> <INDENT> return (dat == self.data or (self.left and dat in self.left) or (self.right and dat in self.right))
Search ourselves recursively for dat.
625941e399cbb53fe6792fc8
def bundle_context(context, dest_dir, force=False, skip_non_relocatable=False, quiet=False, patch_libs=False, verbose=False): <NEW_LINE> <INDENT> bundler = _ContextBundler( context=context, dest_dir=dest_dir, force=force, skip_non_relocatable=skip_non_relocatable, patch_libs=patch_libs, quiet=quiet, verbose=verbose ) <...
Bundle a context and its variants into a relocatable dir. This creates a copy of a context with its variants retargeted to a local package repository containing only the variants the context uses. The generated file structure looks like so: /dest_dir/ /context.rxt /packages/ /foo/1.1.1...
625941e373bcbd0ca4b2c458
def __init__(self, checker, tiebreak, lookahead): <NEW_LINE> <INDENT> assert(checker == 'X' or checker == 'O') <NEW_LINE> assert(tiebreak == 'LEFT' or tiebreak == 'RIGHT' or tiebreak == 'RANDOM') <NEW_LINE> assert(lookahead >= 0) <NEW_LINE> super().__init__(checker) <NEW_LINE> self.tiebreak = tiebreak <NEW_LINE> self.l...
Starts AI player with checker, tiebreaker and lookahead
625941e3ff9c53063f47c5d4
def _term_handler(self, signum, frame): <NEW_LINE> <INDENT> logger.warning('Signal received. %s %s', signum, frame) <NEW_LINE> logger.warning('Press CTRL+C to KILL') <NEW_LINE> if len(self.inputlist) > 0: <NEW_LINE> <INDENT> logger.warning('Following Simpacks have been removed unfinished from the Queue: %s, Items: %s',...
Signal Handler for Signal Term
625941e3a934411ee3751a77
def id_generator(): <NEW_LINE> <INDENT> num = 2 <NEW_LINE> while True: <NEW_LINE> <INDENT> yield num <NEW_LINE> num += 1
the id 0 and 1 are reserved for empty (0) and blocking (1) SQM's
625941e3d8ef3951e3243920
def get_info(self): <NEW_LINE> <INDENT> res = self.client.api.get_transmitter(self.id) <NEW_LINE> for k, v in res.items(): <NEW_LINE> <INDENT> setattr(self, k, v) <NEW_LINE> <DEDENT> return self
Retrieves transmitter info.
625941e3956e5f7376d7124e
def forwardSSHServer (self, strServer = 'localhost'): <NEW_LINE> <INDENT> cfg = self.cfg_root["ssh_destinations"][strServer] <NEW_LINE> self.logger.info("started for %s", strServer) <NEW_LINE> self.logger.info("Using file '%s' ...", self.cfg["local_path"]) <NEW_LINE> f = open(self.cfg["local_path"],'w') <NEW_LINE> f.wr...
Forward (copy) the picture that has been taken to the specified server using SSH.
625941e38a349b6b435e8555
def get_trade(self, symbol): <NEW_LINE> <INDENT> symbol = self._check_transform(symbol) <NEW_LINE> data = {"exchange": self.name} <NEW_LINE> trades = [] <NEW_LINE> info = self.client.get_trade(symbol) <NEW_LINE> data['raw'] = info <NEW_LINE> tick = info['tick'] <NEW_LINE> trade = {"id": tick['id'], "time": tick['ts'], ...
查询symbol的最近成交记录(仅返回一条) :param symbol: 交易对,如:btc_usdt :return: { "exchange": 交易所名称, "raw": 交易所返回的信息, "trades": [ {"id": 交易所返回的唯一id, "time": 时间Unix timestamp 毫秒, "price": 价格, "amount": 数量, "type": 订单类型:ORDER_TYPE_BUY, ORDER_T...
625941e326238365f5f0f256
def put(self, employee_id): <NEW_LINE> <INDENT> employee = get_employee_by_id(employee_id) <NEW_LINE> employee.name = request.json["name"] <NEW_LINE> employee.date_birth = request.json["date_birth"] <NEW_LINE> employee.salary = request.json["salary"] <NEW_LINE> employee.department_id = request.json["depart_name"] <NEW_...
Update employee parameter(s) by id.
625941e35fdd1c0f98dc0617
def test_get_missing_repo(self): <NEW_LINE> <INDENT> qs = querysets.RepoQuerySet(mock.MagicMock(), mock.MagicMock()) <NEW_LINE> mock_get = mock.MagicMock() <NEW_LINE> mock_get.side_effect = DoesNotExist <NEW_LINE> qs.get = mock_get <NEW_LINE> self.assertRaises(pulp_exceptions.MissingResource, qs.get_repo_or_missing_res...
Raise a MissingResource if the repo does not exist.
625941e3e8904600ed9f2315
def delete_object_data(self, bucket, key): <NEW_LINE> <INDENT> path = self._get_path('%s/%s' % (bucket, key)) <NEW_LINE> return self.delete(path)
删除桶内对象 注意: 删除成功不是返回200 参数: bucket: 桶名 key: 对象名
625941e316aa5153ce36285a
def forward(self, query, context, context_mask): <NEW_LINE> <INDENT> batch_size, output_len, dimensions = query.size() <NEW_LINE> query_len = context.size(1) <NEW_LINE> if self.attention_type == "general": <NEW_LINE> <INDENT> query = query.reshape(batch_size * output_len, dimensions) <NEW_LINE> query = self.linear_in(q...
Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data overwhich to apply the attention mechanism. Returns: :class:`tuple` with `output` and...
625941e30c0af96317bb85ca
def GetFullyConnected(self): <NEW_LINE> <INDENT> return _itkAreaClosingImageFilterPython.itkAreaClosingImageFilterIF2IF2_Superclass_GetFullyConnected(self)
GetFullyConnected(self) -> bool
625941e31d351010ab855efd
def test_submit_bad_q(self): <NEW_LINE> <INDENT> for val in ('not-an-int', '0', '-20'): <NEW_LINE> <INDENT> data = get_default_submit_parameters() <NEW_LINE> data['gen_npoints_val'] = val <NEW_LINE> rv = self._check_submit(data) <NEW_LINE> self.assertEqual(rv.status_code, 400) <NEW_LINE> self.assertIn(b'q values not a ...
Test submit page with bad q values
625941e3283ffb24f3c55ce0
def change_type(instance, region_name, available_instances): <NEW_LINE> <INDENT> assert(instance["State"] == "stopped") <NEW_LINE> ec2 = boto3.client("ec2", region_name=region_name) <NEW_LINE> choices = [k+" :: "+v for k, v in available_instances.items()] <NEW_LINE> type_prompt = { 'type': 'list', 'name': 'type', 'mess...
This creates a prompt to change the type of a given instance. The available types can be changed in 'instance_types.cfg'. If one is picked, the type of the instance is changed.
625941e3596a897236089e9e
def run_step(context): <NEW_LINE> <INDENT> logger.debug("started") <NEW_LINE> client_in, service_name, waiter_name = get_waiter_args(context) <NEW_LINE> waiter_args = client_in.get('waiterArgs', None) <NEW_LINE> wait_args = client_in.get('waitArgs', None) <NEW_LINE> logger.info(f"Waiting for {waiter_name} on aws {servi...
Run any low-level boto3 client wait from get_waiter. All of the awsWaitIn descendant values support {key} string interpolation. Args: context: Dictionary. Mandatory. Requires the following context keys in context: - awsWaitIn. dict. mandatory. Contains keys: The awsWaitI...
625941e33c8af77a43ae3b87
def getAllowed(self): <NEW_LINE> <INDENT> return self.allowedFields
:return:
625941e3e5267d203edce07b