code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, attrs=None, format=None): <NEW_LINE> <INDENT> format = format or "%H:%M" <NEW_LINE> super(TimeInput, self).__init__(attrs, format) <NEW_LINE> self.attrs["class"] = "form-control" <NEW_LINE> self.attrs["data-date-pickDate"] = "false" | NOTE: The format for the value (used for strptime) and the format for the datetimepicker
must align for this to work correctly | 625941c9046cf37aa974cddf |
def zone_update(self, ctrl: Controller, zone: Zone) -> None: <NEW_LINE> <INDENT> pass | Called when a zone update message is recieved from the controller
Zone data will be set to new value. | 625941c9ab23a570cc250218 |
def intersect(self, nums1, nums2): <NEW_LINE> <INDENT> L1 = len(nums1) <NEW_LINE> L2 = len(nums2) <NEW_LINE> d={} <NEW_LINE> for i in nums1: <NEW_LINE> <INDENT> if i in d: <NEW_LINE> <INDENT> d[i] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> res = [] <NEW_LINE> for j in nums2... | :type nums1: List[int]
:type nums2: List[int]
:rtype: List[int] | 625941c93346ee7daa2b2e01 |
def createCharacterDefinition(characterName=''): <NEW_LINE> <INDENT> if characterName and isCharacterDefinition(characterName, False): <NEW_LINE> <INDENT> raise Exception('Character definition "' + characterName + '" already exists!') <NEW_LINE> <DEDENT> if not characterName: characterName = 'Character1' <NEW_LINE> cha... | Create a new HIK character definition
@param characterName: Name for the new character definition
@type characterName: str | 625941c9fb3f5b602dac3729 |
def _lcod(x, w_e, w_s, thresh, T): <NEW_LINE> <INDENT> with tf.name_scope('itr_00'): <NEW_LINE> <INDENT> b = tf.matmul(x, w_e, name='b') <NEW_LINE> z = tf.zeros_like(b, dtype=tf.float32, name='z') <NEW_LINE> <DEDENT> for t in range(1, T): <NEW_LINE> <INDENT> with tf.name_scope('itr_%02d' % t): <NEW_LINE> <INDENT> z_bar... | Learned Coordinate Descent (LCoD). LCoD is an approximately sparse encoder. It
approximates (in an L2 sense) a sparse code of `x` according to dictionary `w_e`.
Note that during backpropagation, `w_e` isn't strictly a dictionary (i.e.
dictionary atoms are not strictly normalized).
LCoD is a differentiable version of g... | 625941c9a05bb46b383ec8b8 |
def color_top(): <NEW_LINE> <INDENT> local_output = local('top -b -n 1 | head', capture=True) <NEW_LINE> color_rotate(local_output) <NEW_LINE> print | color the output of top -b -n 1 | head
| 625941c9fbf16365ca6f625a |
def testConstructor_021(self): <NEW_LINE> <INDENT> writer = CdWriter(device="/dev/null", scsiId=None, mediaType=MEDIA_CDRW_80, noEject=True, unittest=True) <NEW_LINE> self.assertEqual("/dev/null", writer.device) <NEW_LINE> self.assertEqual(None, writer.scsiId) <NEW_LINE> self.assertEqual("/dev/null", writer.hardwareId)... | Test the constructor with device ``/dev/null``, which is writable and
exists. Use None for SCSI id and a media type of MEDIA_CDRW_80. Make
sure that ``unittest=True``. Use ``noEject=True``. | 625941c94f88993c3716c0fe |
def sort(self, key=None, reverse=False): <NEW_LINE> <INDENT> for rule in self: <NEW_LINE> <INDENT> rule.rules.sort(key, reverse) <NEW_LINE> <DEDENT> super().sort(key=key, reverse=reverse) | Extend `list.sort` to recursively sort `self`.
Example::
>>> rules = Rules('''
... ol li, ul li { a { color: blue }; b { color: black } }
... dl dt, dl dd { b { color: black }; a { color: blue } }
... ''')
>>> rules.sort()
>>> print(rules.render("compact"))
dl dt, dl dd { a { col... | 625941c9ab23a570cc250219 |
def get_nic_count(self, profile_list): <NEW_LINE> <INDENT> return self.hardware.get_item_count_per_profile('ethernet', profile_list) | Get the number of NICs under the given profile(s).
Args:
profile_list (list): Profile(s) of interest.
Returns:
dict: ``{ profile_name : nic_count }`` | 625941c94f6381625f114ad2 |
def add_checker(self, checker): <NEW_LINE> <INDENT> vcids = set() <NEW_LINE> lcids = set() <NEW_LINE> visits = self.visit_events <NEW_LINE> leaves = self.leave_events <NEW_LINE> for member in dir(checker): <NEW_LINE> <INDENT> cid = member[6:] <NEW_LINE> if cid == "default": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDE... | Walk to the checker's dir and collect visit and leave methods. | 625941c93cc13d1c6d3c7411 |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument( '--restore_path', type=str, help='Folder path to checkpoints', default='') <NEW_LINE> parser.add_argument( '--config_path', type=str, help='path to config file for training', ) <NEW_LINE> parser.add_argument( '--data_path... | Call train.py as a new process and pass command arguments | 625941c92c8b7c6e89b35858 |
def _delete(self, path, params): <NEW_LINE> <INDENT> url = "{}/{}".format(self._api_base_url, path) <NEW_LINE> headers = {"X-Atlassian-Token": "nocheck"} <NEW_LINE> response = self.client.delete( url, params=params, headers=headers, auth=self._basic_auth ) <NEW_LINE> self._handle_response_errors(path, params, response) | HTTP DELETE method for Confluence Client api
:param path: path to REST API to delete content
:param params: dictionary with the parameters
to add to DELETE message.
:return: None | 625941c976d4e153a657ebc7 |
def list_authorization_rules( self, resource_group_name, namespace_name, queue_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = self.list_authorization_rules.metadata['url'] <NEW... | Gets all authorization rules for a queue.
:param resource_group_name: Name of the Resource group within the
Azure subscription.
:type resource_group_name: str
:param namespace_name: The namespace name
:type namespace_name: str
:param queue_name: The queue name.
:type queue_name: str
:param dict custom_headers: header... | 625941c9f548e778e58cd614 |
def exclude_freq(self, f_ex, names=None): <NEW_LINE> <INDENT> if names and not isinstance(names, list): <NEW_LINE> <INDENT> names = [names] <NEW_LINE> <DEDENT> for name in names if names else self.names: <NEW_LINE> <INDENT> self.psds[name].exclude_freq(f_ex) | Exclude data points at frequencies f_ex.
Arguments
---------
f_ex : float or list(floats) or None
Frequencies to be excluded. If None, the data point at the
excitation frequency of the excited axis is excluded.
name : str
Name of the psd where the data point shall be excluded. If None,
all psds get f_e... | 625941c930bbd722463cbe5c |
def som_get_awards(som_pointer): <NEW_LINE> <INDENT> ccore = cdll.LoadLibrary(PATH_DLL_CCORE_64); <NEW_LINE> package = ccore.som_get_awards(som_pointer); <NEW_LINE> result = extract_pyclustering_package(package); <NEW_LINE> return result; | !
@brief Returns list of amount of captured objects by each neuron.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map. | 625941c997e22403b379d030 |
def needs_password(self): <NEW_LINE> <INDENT> return self._file_parser.needs_password() | Returns True if any archive entries require password for extraction. | 625941c93eb6a72ae02ec572 |
def __init__(self, data): <NEW_LINE> <INDENT> self.header_len, self.flags, self.channel = unpack('<BBB', data[:3]) <NEW_LINE> self.rssi, self.event_counter, self.delta = unpack('<BHI', data[3:10]) <NEW_LINE> self.data = data <NEW_LINE> self.payload = data[10:] <NEW_LINE> return super().__init__(Packet.N_PACKET_NORDIC, ... | Parse nordic header | 625941c9d6c5a102081440e1 |
def get_notification_dialog(self, wait=True): <NEW_LINE> <INDENT> if wait is True: <NEW_LINE> <INDENT> return self._get_notification_obj_and_props('Notification', 'notification1') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dialog = self.main_window.select_single( 'Notification', objectName='notification1') <NEW_LINE... | Get the notification dialog and properties being displayed on screen
If wait is True then wait for default timeout period
If wait is False then do not wait at all
:param wait: wait status
:return: dialog introspection object | 625941c99f2886367277a924 |
def get_odk_forms_list(self): <NEW_LINE> <INDENT> self.refresh_forms() <NEW_LINE> all_forms = ODKForm.objects.select_related('form_group').all().values('id', 'form_id', 'form_group__group_name', 'form_name', 'full_form_id', 'auto_update', 'is_source_deleted').order_by('id') <NEW_LINE> to_return = [] <NEW_LINE> for frm ... | Get all the defined ODK forms | 625941c93346ee7daa2b2e02 |
def get_menus(): <NEW_LINE> <INDENT> return [] | Return all the available menus in current DCC. This function returns specific DCC objects that represents DCC
UI menus.
:return: List of all menus names in current DCC
:rtype: list(str) | 625941c966656f66f7cbc242 |
def test_api_list_with_protected_obj(self): <NEW_LINE> <INDENT> self._test_list('adam', 2, obj=self.protected_article) <NEW_LINE> self._test_list('seele', 2, obj=self.protected_article) <NEW_LINE> self._test_list('nerv', 2, obj=self.protected_article) <NEW_LINE> self._test_list('children', 2, obj=self.protected_article... | 内部公開オブジェクト関連スターリスト取得テスト | 625941c950485f2cf553ce30 |
def do_exit(self): <NEW_LINE> <INDENT> pass | do_exit() -> To be implemented by inheritor.
| 625941c9be383301e01b551e |
def delete(self, value): <NEW_LINE> <INDENT> pass | Delete a RBTNode that contains value value from this
RedBlackTree. If there is no such RBTNode, raise a
NoSuchValueException.
| 625941c95f7d997b87174b2e |
def _break_on_local_flushed(self, local_info, remote_info): <NEW_LINE> <INDENT> self.unlink(local_info, remote_info) | Break the remote/local relationship on flush. | 625941c9be8e80087fb20cdb |
def getRandTad(cl, side, line): <NEW_LINE> <INDENT> tad_length = int(line[4]) - int(line[2]) <NEW_LINE> chrom = line[0] <NEW_LINE> if side == 0: <NEW_LINE> <INDENT> end_up = int(line[1]) <NEW_LINE> end_down = int(line[2]) <NEW_LINE> start_down = end_up - tad_length <NEW_LINE> start_up = start_down - 10000 <NEW_LINE> if... | Generates locations for artificial tad boundaries
:param cl: The cell line in which the fake tad will exist
:param side: 1: downstream boundary of the tad is fixed
0: upstream boundary of the tad is fixed
:param line: the line from .looplist file containing the coordinates of the real tad
:return: the artificial tad [... | 625941c99c8ee82313fbb80c |
def __init__(self,radius,x,y,color=None): <NEW_LINE> <INDENT> self.radius=radius <NEW_LINE> self.x=x <NEW_LINE> self.y=y <NEW_LINE> self.color=color <NEW_LINE> self.drawDot() | the constructor for the class that creates the lines | 625941c97d847024c06be352 |
def embed_tree(logits_and_state, is_root): <NEW_LINE> <INDENT> return td.InputTransform(tokenize) >> td.OneOf( key_fn=lambda pair: pair[0] == '2', case_blocks=(add_metrics(is_root, is_neutral=False), add_metrics(is_root, is_neutral=True)), pre_block=(td.Scalar('int32'), logits_and_state)) | Creates a block that embeds trees; output is tree LSTM state. | 625941c96aa9bd52df036e3b |
def write_connectivity(self, con_file='grid.con.wb'): <NEW_LINE> <INDENT> def write_face(indx, type, blk, side, dit): <NEW_LINE> <INDENT> fh.write(FRMT.format(indx, type, blk, side, dit[0,0], dit[0,1], dit[0,2], dit[1,0], dit[1,1], dit[1,2], '')) <NEW_LINE> <DEDENT> FRMT = '{:5}{:7}{:7}{:7}{:6}{:11}{:11}{:6}{:11}{:11}{... | Pre: Grid, Connectivity | 625941c98e71fb1e9831d840 |
def select_rows(self): <NEW_LINE> <INDENT> self.open_connection() <NEW_LINE> with self.conn.cursor() as cur: <NEW_LINE> <INDENT> cur.execute(query) <NEW_LINE> records = [row for row in cur.fetchall()] <NEW_LINE> cur.close() <NEW_LINE> return records | Run a SQL query to select rows from table. | 625941c9de87d2750b85fe29 |
def my_represent_scalar(self, tag, value, style=None): <NEW_LINE> <INDENT> if style is None: <NEW_LINE> <INDENT> if should_use_block(value): <NEW_LINE> <INDENT> style = '|' <NEW_LINE> value = value.rstrip() <NEW_LINE> value = ''.join(x for x in value if x in string.printable or ord(x) >= 0xA0) <NEW_LINE> value = value.... | Uses block style for multi-line strings | 625941c9283ffb24f3c55999 |
def createImagesTable(self,matrix,color): <NEW_LINE> <INDENT> if color == "green": <NEW_LINE> <INDENT> self.vContent.append(" <TABLE id=\"green\">\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vContent.append(" <TABLE id=\"hor-zebra\">\n") <NEW_LINE> <DEDENT> isOdd = True <NEW_LINE> for fields in matrix: <NE... | Creates a table of two columns where odd rows are titles and pair rows are images | 625941c9d58c6744b4257cf7 |
def delegate_inventory(args, inventory_path_src): <NEW_LINE> <INDENT> if isinstance(args, PosixIntegrationConfig): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def inventory_callback(files): <NEW_LINE> <INDENT> if data_context().content.collection: <NEW_LINE> <INDENT> working_path = data_context().content.collection.... | Make the given inventory available during delegation. | 625941c9d4950a0f3b08c3e7 |
def makelsnodepath(linesegs,thickness=1, rgbacolor=[1,1,1,1]): <NEW_LINE> <INDENT> ls = LineSegs() <NEW_LINE> ls.setThickness(thickness) <NEW_LINE> for p0p1tuple in linesegs: <NEW_LINE> <INDENT> pnt00, pnt01, pnt02 = p0p1tuple[0] <NEW_LINE> pnt10, pnt11, pnt12 = p0p1tuple[1] <NEW_LINE> ls.setColor(rgbacolor[0], rgbacol... | create linesegs pathnode
:param linesegs: [[pnt0, pn1], [pn0, pnt1], ...]
:param thickness:
:return: a panda3d pathnode
author: weiwei
date: 20161216 | 625941c9baa26c4b54cb11b7 |
def print_eigenvalues(self): <NEW_LINE> <INDENT> print >> self.txt, eigenvalue_string(self) | Print eigenvalues and occupation numbers. | 625941c9e5267d203edcdd35 |
def uniqueValues(aDict): <NEW_LINE> <INDENT> values = [] <NEW_LINE> keys = [] <NEW_LINE> for key,value in aDict.items(): <NEW_LINE> <INDENT> keys.append(key) <NEW_LINE> values.append(value) <NEW_LINE> <DEDENT> a = [] <NEW_LINE> for i in values: <NEW_LINE> <INDENT> if values.count(i) > 1: <NEW_LINE> <INDENT> continue <N... | aDict: a dictionary
returns keys for only unique values in dict | 625941c9627d3e7fe0d68ee6 |
def test_get_current_season(self, api_key): <NEW_LINE> <INDENT> assert isinstance(FantasyDataNBA(api_key).get_current_season(), int), "Invalid value type" | API call get_current_season | 625941c94f88993c3716c0ff |
def daemonize(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> ... | do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 | 625941c9b830903b967e99a3 |
def train_test_split_fn(*arrays, **options): <NEW_LINE> <INDENT> split_dfs = cross_validation.train_test_split(*arrays, **options) <NEW_LINE> test_size = options.pop('test_size', None) <NEW_LINE> train_size = options.pop('train_size', None) <NEW_LINE> random_state = options.pop('random_state', None) <NEW_LINE> if test_... | Stores the split dataframes. | 625941c97b25080760e394f1 |
def page(message): <NEW_LINE> <INDENT> verbose = False <NEW_LINE> try: <NEW_LINE> <INDENT> from asap.parameters import rcParams <NEW_LINE> verbose = rcParams['verbose'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if verbose: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from IPython.genutils... | Run the input message through a pager. This is only done if
``rcParams["verbose"]`` is set. | 625941c907f4c71912b11519 |
def binary_search(A, target): <NEW_LINE> <INDENT> L, R = 0, len(A) - 1 <NEW_LINE> while L <= R: <NEW_LINE> <INDENT> M = L + (R - L) // 2 <NEW_LINE> if A[M] < target: <NEW_LINE> <INDENT> L = M + 1 <NEW_LINE> <DEDENT> elif A[M] == target: <NEW_LINE> <INDENT> return M <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> R = M - ... | Traditional iterative binary search (accounting for integer overflow) | 625941c9097d151d1a222ef1 |
def handleHRowHeader(self, cell, row_dims, rowProperties) : <NEW_LINE> <INDENT> i = cell['i'] <NEW_LINE> j = cell['j'] <NEW_LINE> prop = rowProperties[j] <NEW_LINE> logger.debug("({},{}) Handle HRow header".format(cell['i'], cell['j'])) <NEW_LINE> if (cell['isEmpty'] or cell['value'].lower() == 'id.' or cell['value'].l... | Build up lists for hierarchical row headers.
Cells marked as hierarchical row header are often empty meaning
that their intended value is stored somewhere else in the Excel sheet. | 625941c973bcbd0ca4b2c10e |
def click_ray(self,x,y): <NEW_LINE> <INDENT> R,t = se3.inv(self.camera.matrix()) <NEW_LINE> u = float(x-self.width/2) <NEW_LINE> v = float(self.height-y-self.height/2) <NEW_LINE> aspect = float(self.width)/float(self.height) <NEW_LINE> rfov = self.fov*math.pi/180.0 <NEW_LINE> scale = 2.0*math.tan(rfov*0.5/aspect)*aspec... | Returns a pair of 3-tuples indicating the ray source and direction
in world coordinates for a screen-coordinate point (x,y) | 625941c9d486a94d0b98e1dd |
def query_execution(self,conn,sql): <NEW_LINE> <INDENT> curser = conn.cursor() <NEW_LINE> curser.execute(sql) <NEW_LINE> rows = curser.fetchall() <NEW_LINE> conn.commit() <NEW_LINE> return rows | description:
------------
execute sql query on input db connection
args:
------------
:param conn: current connection to database
:param sql: input sql query
return:
------------
:return ID: inserted ID | 625941c93eb6a72ae02ec573 |
def __iter__(self): <NEW_LINE> <INDENT> filepath = self.associations_path <NEW_LINE> if not os.path.exists(filepath): <NEW_LINE> <INDENT> raise GeneOntologyError(f"{os.path.basename(filepath)} does not exist at {os.path.dirname(filepath)}") <NEW_LINE> <DEDENT> if not hasattr(self, "go_dag"): <NEW_LINE> <INDENT> self.lo... | Iterate over annotations.
| 625941c932920d7e50b28267 |
def each(self, *funcs): <NEW_LINE> <INDENT> funcs = list(map(_make_callable, funcs)) <NEW_LINE> if len(funcs) == 1: <NEW_LINE> <INDENT> return Collection(map(funcs[0], self._items)) <NEW_LINE> <DEDENT> tupler = lambda item: Scalar( tuple(_unwrap(func(item)) for func in funcs)) <NEW_LINE> return Collection(map(tupler, s... | Call `func` on each element in the collection.
If multiple functions are provided, each item
in the output will be a tuple of each
func(item) in self.
Returns a new Collection.
Example:
>>> col = Collection([Scalar(1), Scalar(2)])
>>> col.each(Q * 10)
Collection([Scalar(10), Scalar(20)])
>>> col.eac... | 625941c95fc7496912cc3a15 |
def valid_move(x, y): <NEW_LINE> <INDENT> if [x, y] in empty_cells(board): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | სვლა არის ვალიდური თუ მოცემული უჯრა ცარიელია
:param x: X კოორდინატი
:param y: Y კოორდინატი
:return: აბრუნებს True თუ board[x][y] ცარიელია | 625941c9cb5e8a47e48b7b43 |
def __init__(self, shape=(4, 2)): <NEW_LINE> <INDENT> nn.__init__(self, shape=shape) | Deep Neural Network | 625941c9cc40096d615959e8 |
def test_create_port_vnic_type_direct(self): <NEW_LINE> <INDENT> resource = 'port' <NEW_LINE> cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None) <NEW_LINE> name = 'myname' <NEW_LINE> myid = 'myid' <NEW_LINE> netid = 'netid' <NEW_LINE> args = ['--vnic_type', 'direct', netid] <NEW_LINE> position_names = ['binding:... | Create port: --vnic_type direct netid. | 625941c9a79ad161976cc1dd |
def negative_log_likelihood(self, y): <NEW_LINE> <INDENT> return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y]) | Return the mean of the negative log-likelihood of the prediction of this model under a given
target distribution.
.. math::
rac{1}{|\mathcal{D}|} \mathcal{L} ( heta=\{W,b\}, \mathcal{D}) =
rac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|}
\log(P(Y=y^{(i)}|x^{(i)}, W,b)) \
\ell ( heta=\... | 625941c9d6c5a102081440e2 |
def cnn_model(input_shape, show_table=False): <NEW_LINE> <INDENT> X_input = Input(input_shape) <NEW_LINE> X = ZeroPadding2D((3, 3))(X_input) <NEW_LINE> X = Conv2D(32, (7, 7), strides=(1, 1), name='conv0')(X) <NEW_LINE> X = BatchNormalization(axis=3, name='bn0')(X) <NEW_LINE> X = Activation('relu')(X) <NEW_LINE> X = Max... | Implementation of the HappyModel.
Arguments:
input_shape -- shape of the images of the dataset
Returns:
model -- a Model() instance in Keras | 625941c9004d5f362079a3cb |
def numericAtipicalEval(self): <NEW_LINE> <INDENT> for col in self.numericDictionary.keys(): <NEW_LINE> <INDENT> std = self.numericDictionary[col]["std"] <NEW_LINE> mean = self.numericDictionary[col]["mean"] <NEW_LINE> max_2std = (2*std)+ mean <NEW_LINE> max_2_5std = (2.5*std)+ mean <NEW_LINE> max_3std = (3*std)+ ... | Para encontrar las variables atipicas en un conjunto de datos numéricos
aplicamos una revisión para encontrar el número de observaciones que se
encuentran a mas de 1, 2, 2.5 y 3 desviaciones estandar de la media | 625941c9925a0f43d2549f0e |
@transformer_cfg_reg.register() <NEW_LINE> def transformer_wmt_en_de_big(): <NEW_LINE> <INDENT> cfg = TransformerModel.get_cfg() <NEW_LINE> cfg.defrost() <NEW_LINE> cfg.MODEL.attention_dropout = 0.1 <NEW_LINE> cfg.MODEL.dropout = 0.3 <NEW_LINE> cfg.MODEL.ENCODER.units = 1024 <NEW_LINE> cfg.MODEL.ENCODER.hidden_size = 4... | Same wmt_en_de_big architecture as in FairSeq | 625941c9377c676e91272240 |
def has_edge(self, direction): <NEW_LINE> <INDENT> if direction in valid_directions: <NEW_LINE> <INDENT> return self.__dict__[direction] is not None <NEW_LINE> <DEDENT> raise ValueError('Invalid edge direction') | Return True if cell has an edge on ordinal 'direction' | 625941c996565a6dacc8f763 |
def create_elem_dict(row): <NEW_LINE> <INDENT> elem = { 'id': row.id, 'version': row.version, 'userId': row.user_id, 'userName': row.user_name, 'timestamp': row.timestamp, 'tags': row.tags, } <NEW_LINE> if row.add: <NEW_LINE> <INDENT> elem['added'] = True <NEW_LINE> <DEDENT> if row.delete: <NEW_LINE> <INDENT> elem['del... | Create new element dictionary from row with metadata common to all
nodes/ways/relations. | 625941c91d351010ab855bb3 |
def write_model(self): <NEW_LINE> <INDENT> log.info("Writing the model ...") <NEW_LINE> path = self.output_path_file(self.config.name + ".mod") <NEW_LINE> self.model.saveto(path) | This function ...
:return: | 625941c9a219f33f34628a02 |
def from_wave_data(wave): <NEW_LINE> <INDENT> fmt_chunk = wave.chunk("fmt ") <NEW_LINE> if fmt_chunk is not None: <NEW_LINE> <INDENT> is_little_endian = wave.is_little_endian <NEW_LINE> fmt_data = fmt_chunk.data <NEW_LINE> return WaveDataFormat( utilities.to_short(fmt_data, 0, True, is_little_endian), utilities.to_shor... | :param wave: the WaveData object to extract a WaveDataFormat object from
:return: the WaveDataFormat object for the given WaveData object | 625941c994891a1f4081bb41 |
def isolated_circuit(N, Sign, FnameBNET=None): <NEW_LINE> <INDENT> Sign = Sign.lower() <NEW_LINE> assert( Sign in ["positive","negative"]) <NEW_LINE> lines = ["v%i, \t v%i"%(i,i+1) for i in range(1,N)] <NEW_LINE> if Sign=="positive": <NEW_LINE> <INDENT> lines+= ["v%i, \t v1"%N] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Creates a *bnet* file of an isolated circuit of length *N* and given *Sign*.
**arguments**:
* *N* (int): number of components
* *Sign* (str): either *"positive"* or *"negative"*
* *FnameBNET* (str): name of *bnet* file or *None* for the string of the file contents
**returns**:
* *BNET* (str) if *FnameBNE... | 625941c971ff763f4b549722 |
def get_commit_message_characteristics(self): <NEW_LINE> <INDENT> logging.info('Extracting message characteristics...') <NEW_LINE> commit_messages = self.get_query_result(self.commit_message_query.format()) <NEW_LINE> keywords = sorted(['fix', 'bug', 'feature', 'improve', 'document', 'refactor', 'update', 'add', 'remov... | This method returns the message characteristics features
:return: The message characteristics features as a Pandas DataFrame | 625941c957b8e32f52483532 |
def get_portal(authentication_proxy, codehosting_proxy): <NEW_LINE> <INDENT> portal = Portal(Realm(authentication_proxy, codehosting_proxy)) <NEW_LINE> portal.registerChecker( PublicKeyFromLaunchpadChecker(authentication_proxy)) <NEW_LINE> return portal | Get a portal for connecting to Launchpad codehosting. | 625941c9379a373c97cfabdc |
def definition(cfg=ccdc.ARD): <NEW_LINE> <INDENT> return get('grid_fn', cfg)() | Returns the grid definition associated with configuration | 625941c985dfad0860c3aef2 |
def update_density_plot(self): <NEW_LINE> <INDENT> y = np.append(self.data.density[1:], self.data.density[-1]) <NEW_LINE> self.fig.data[1].y = y | Update the density line in the plot. | 625941c926238365f5f0ef05 |
def validate(self, object, name, value): <NEW_LINE> <INDENT> if isinstance(value, AffineScalarFunc): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if isinstance(value, float): <NEW_LINE> <INDENT> return ufloat((value, 0)) <NEW_LINE> <DEDENT> if isinstance(value, int): <NEW_LINE> <INDENT> return ufloat((value, 0)... | Validates that a specified value is valid for this trait.
| 625941c9baa26c4b54cb11b8 |
def _unpack_data(self, data: List) -> None: <NEW_LINE> <INDENT> while data: <NEW_LINE> <INDENT> err = create_message(PROTO_ERROR) <NEW_LINE> err.ParseFromString(msg_bytes(data.pop(0))) <NEW_LINE> self.errors.append(err) | Called when all fields of the message are set. Usefull for data deserialization.
| 625941c9a8ecb033257d3165 |
def parse_netloc(netloc): <NEW_LINE> <INDENT> url = build_url_from_netloc(netloc) <NEW_LINE> parsed = urllib.parse.urlparse(url) <NEW_LINE> return parsed.hostname, parsed.port | Return the host-port pair from a netloc. | 625941c9f548e778e58cd615 |
def remove(self, token): <NEW_LINE> <INDENT> self._db.pop(token) | Remove the token from the dictionary | 625941c93c8af77a43ae3838 |
def build_submit_description(executable, output, error, user_log, query_params): <NEW_LINE> <INDENT> all_query_params = DEFAULT_QUERY_CLASSAD.copy() <NEW_LINE> all_query_params.update(query_params) <NEW_LINE> submit_description = [] <NEW_LINE> for key, value in all_query_params.items(): <NEW_LINE> <INDENT> submit_descr... | Build up the contents of a condor submit description file.
>>> submit_args = dict(executable='/path/to/script', output='o', error='e', user_log='ul')
>>> submit_args['query_params'] = dict()
>>> default_description = build_submit_description(**submit_args)
>>> assert 'executable = /path/to/script' in default_descripti... | 625941c930dc7b76659019ff |
def policy_backward(eph, epdlogp): <NEW_LINE> <INDENT> dW2 = np.array((np.dot(eph.T, epdlogp[0]).ravel(),np.dot(eph.T, epdlogp[1]).ravel())) <NEW_LINE> dh = np.array((np.outer(epdlogp[0], model['W2'][0]),np.outer(epdlogp[1], model['W2'][1])), ndmin=2) <NEW_LINE> dh[0][eph <= 0] = 0 <NEW_LINE> dh[1][eph <= 0] = 0 <NEW_L... | backward pass. (eph is array of intermediate hidden states) | 625941c9a934411ee375172c |
def test_landing_url(self): <NEW_LINE> <INDENT> self.import_page.upload_tarball(self.tarball_name) <NEW_LINE> self.assertEqual(self.import_page.finished_target_url(), self.landing_page.url) | Scenario: When uploading a library or course, a link appears for me to view the changes.
Given that I upload a library or course
A button will appear that contains the URL to the library or course's main page | 625941c9cad5886f8bd27071 |
def _send_response(self): <NEW_LINE> <INDENT> for identifier in self._identifiers: <NEW_LINE> <INDENT> if identifier in self._responses and self._was_updated(identifier): <NEW_LINE> <INDENT> response = requests.post(self._submit_url, { "identifier": identifier, "api_key": self._api_key, "notebook": str(self._notebook),... | Sends responses to the nbforms server | 625941c9fb3f5b602dac372a |
def relative_paths(root: Path, paths: list) -> List[str]: <NEW_LINE> <INDENT> result = [] <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> exclusion = path.startswith("!") <NEW_LINE> if exclusion: <NEW_LINE> <INDENT> path = path[1:] <NEW_LINE> <DEDENT> if isinstance(path, Path): <NEW_LINE> <INDENT> inp = str(path.rela... | Normalises paths from incoming configuration and ensures
they are all strings relative to root | 625941c9596a897236089b59 |
def get_quandl_data(market, company): <NEW_LINE> <INDENT> filename = "data/" + company + ".csv" <NEW_LINE> try: <NEW_LINE> <INDENT> return pandas.read_csv(filename, parse_dates=True, index_col=0) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> original_columns = ["open", "close", "high", "low", "volume"] <NEW... | Gets lots of data from quandl.
:param market: stock market id
:param company: company id
:return: data | 625941c93617ad0b5ed67f8f |
def evaluateVarianceDerivWRTnewpt(self, newpt): <NEW_LINE> <INDENT> assert self.pts is not None, "must specify training points before running this" <NEW_LINE> assert newpt.shape[1] == self.kernel.dimension, "evaluation points for GP is incorrect shape" <NEW_LINE> out = np.zeros((newpt.shape)) <NEW_LINE> derivs = np.zer... | evaluate derivative of posterior variance at newpt | 625941c99b70327d1c4e0e6d |
def filepath(self): <NEW_LINE> <INDENT> today = date.today().strftime('%Y-%m-%d') <NEW_LINE> filename = 'failed-files-{}'.format(today) <NEW_LINE> return os.path.join(self._output_directory, filename) | Returns a full path to the email report for the processing run
in this report's working directory.
:returns: Full path to the processing run's email report. | 625941c95510c4643540f47e |
def needsQuitButton(self): <NEW_LINE> <INDENT> return False | due to no window decoration, own quit button
might be needed so that users can quit modRana when
they want to | 625941c98a43f66fc4b540fe |
def twoSum(self, numbers, target): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for i in range(len(numbers)): <NEW_LINE> <INDENT> cand = target - numbers[i] <NEW_LINE> if cand in d: <NEW_LINE> <INDENT> return [i+1, d[cand]+1] <NEW_LINE> <DEDENT> d[numbers[i]] = i | :type numbers: List[int]
:type target: int
:rtype: List[int] | 625941c9bd1bec0571d906c7 |
def read_table(table_name, engine): <NEW_LINE> <INDENT> df = pd.read_sql_table(table_name, engine) <NEW_LINE> df.columns = map(renaming_mapper, list(df.columns)) <NEW_LINE> return df | :param table_name:
:param engine:
:return: | 625941c9187af65679ca51b7 |
def get_wksp_index_dist_and_label(workspace, **kwargs): <NEW_LINE> <INDENT> specNum = kwargs.pop('specNum', None) <NEW_LINE> wkspIndex = kwargs.pop('wkspIndex', None) <NEW_LINE> if workspace.getNumberHistograms() == 1: <NEW_LINE> <INDENT> specNum = None <NEW_LINE> wkspIndex = 0 <NEW_LINE> <DEDENT> if (specNum is not No... | Get workspace index, whether the workspace is a distribution,
and label for the spectrum
:param workspace: a Workspace2D or an EventWorkspace | 625941c95fc7496912cc3a16 |
def getDateFromInternalClock(self): <NEW_LINE> <INDENT> result = self.__sendCmdAndGetNotEmptyLine(cmd=GSMTC35.__NORMAL_AT+"CCLK?", content="+CCLK: ") <NEW_LINE> if result == "" or len(result) <= 8 or result[:7] != "+CCLK: ": <NEW_LINE> <INDENT> logging.error("Command to get internal clock failed") <NEW_LINE> return -1 ... | Get the date from the GSM module internal clock
return: (datetime.datetime) Date stored in the GSM module or -1 if an error occured | 625941c963b5f9789fde717e |
def Versions(): <NEW_LINE> <INDENT> s = [ 'Version information:', '\tTime and date: %s' % time.asctime(), '\tPlatform: %s' % platform.platform(), '\tPython version: %s' % sys.version.replace('\n', ' '), '\tphydms version: %s' % phydmslib.__version__, ] <NEW_LINE> for modname in ['Bio', 'cython', 'numpy', 'scipy', 'matp... | Returns a string with version information.
You would call this function if you want a string giving detailed
informationon the version of ``phydms`` and the associated packages that
it uses. | 625941c98c3a873295158452 |
def remove_unfinished(self): <NEW_LINE> <INDENT> for learner in self.learners: <NEW_LINE> <INDENT> learner.remove_unfinished() | Remove uncomputed data from the learners. | 625941c9cad5886f8bd27072 |
def amplitude(signal): <NEW_LINE> <INDENT> indices_max = argrelextrema(signal, np.greater) <NEW_LINE> indices_min = argrelextrema(signal, np.less) <NEW_LINE> maxima = signal[indices_max[0]].max() <NEW_LINE> minima = signal[indices_min[0]].min() <NEW_LINE> return maxima - minima | signal must be a np array | 625941c9d268445f265b4f06 |
def test_hdp_fit_topics_with_fake_data(): <NEW_LINE> <INDENT> n_topics = 3 <NEW_LINE> n_topic_truncate = 10 <NEW_LINE> topics_threshold = 0.1 <NEW_LINE> words_per_topic = 10 <NEW_LINE> tf = make_doc_word_matrix(n_topics=n_topics, words_per_topic=words_per_topic, docs_per_topic=100, words_per_doc=50, shuffle=True, rando... | Test HDP fit with fake data
Top words in large topics should be grouped correctly
(small topic can be ignored.) | 625941c907f4c71912b1151a |
@api.route("/register", methods=["POST"]) <NEW_LINE> def create_client(): <NEW_LINE> <INDENT> form = ClientForm().validate_for_api() <NEW_LINE> promise = { ClientTypeEnum.USER_EMAIL: __register_user_by_email } <NEW_LINE> promise[ClientTypeEnum(form.type.data)]() <NEW_LINE> return Success() | :return:
客户端 注册 | 625941c9cc40096d615959e9 |
def equalAndThen(self, x, y, msg, k): <NEW_LINE> <INDENT> if isinstance(x, onnx.TensorProto) and isinstance(y, onnx.TensorProto): <NEW_LINE> <INDENT> self.equalAndThen(x.name, y.name, msg, k) <NEW_LINE> t1 = onnx.numpy_helper.to_array(x) <NEW_LINE> t2 = onnx.numpy_helper.to_array(y) <NEW_LINE> new_msg = "{}In embedded ... | Helper for implementing 'requireEqual' and 'checkEqual'. Upon failure,
invokes continuation 'k' with the error message. | 625941c931939e2706e4cf04 |
def transform(self, img): <NEW_LINE> <INDENT> return cv2.warpPerspective(img, self.M, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR) | Transform perspective of image
Args:
img: input image | 625941c95fdd1c0f98dc02cb |
def __init__(self): <NEW_LINE> <INDENT> self.DataInfoList = None <NEW_LINE> self.RequestId = None | :param DataInfoList: Billable bandwidth of live stream relaying.
:type DataInfoList: list of BandwidthInfo
:param RequestId: The unique request ID, which is returned for each request. RequestId is required for locating a problem.
:type RequestId: str | 625941c9f9cc0f698b140695 |
@utils.test_case_logger <NEW_LINE> def test_rtc9762_tc_rec_016_multiple_unique(stream): <NEW_LINE> <INDENT> total_recordings = 3 <NEW_LINE> web_service_objs = [] <NEW_LINE> recording_pool = None <NEW_LINE> recording = None <NEW_LINE> try: <NEW_LINE> <INDENT> queue = Queue.Queue() <NEW_LINE> start_time = utils.get_forma... | Create multiple recordings with copy type as UNIQUE | 625941c924f1403a92600bff |
def generate(basename, xml): <NEW_LINE> <INDENT> if basename.endswith('.js'): <NEW_LINE> <INDENT> filename = basename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = basename + '.js' <NEW_LINE> <DEDENT> msgs = [] <NEW_LINE> enums = [] <NEW_LINE> filelist = [] <NEW_LINE> for x in xml: <NEW_LINE> <INDENT> msgs.e... | generate complete javascript implementation | 625941c96e29344779a626ab |
def n_validator(data, p, classifier, *args): <NEW_LINE> <INDENT> np.random.shuffle(data) <NEW_LINE> partition = data.shape[0]/p <NEW_LINE> total = 0 <NEW_LINE> for i in range(p): <NEW_LINE> <INDENT> start = round(partition * i) <NEW_LINE> end = round(partition * (i + 1)) <NEW_LINE> training = np.delete(data, range(sta... | Takes in a total data set, and partitions it in several different ways,
testing the classifier on the data during each partition | 625941c9fbf16365ca6f625c |
def run(self): <NEW_LINE> <INDENT> sample = self.db.view_sample(self.task.sample_id) <NEW_LINE> if sample: <NEW_LINE> <INDENT> filesize = sample.file_size <NEW_LINE> if filesize < 100 * 1024 * 1024: <NEW_LINE> <INDENT> results = {} <NEW_LINE> results = RunDumi(task_id=self.task.id, results=results).run() <NEW_LINE> Run... | Run manager thread. | 625941c915fb5d323cde0ba8 |
def Item_gauge(self, range, align, str, sizer, szpadding, percent, sizeGauge=(280, 45), fontSize=20, txtColor=wx.BLUE): <NEW_LINE> <INDENT> g = PG.PyGauge(self, -1, range=range, size=(sizeGauge)) <NEW_LINE> gfont = wx.Font(fontSize, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) <NEW_LINE> g.SetBackgroun... | :param range: Максимальное значение
:param align:
:param str: Надпись на полосе индикатора
:param sizer:
:param szpadding:
:param percent: Отображать ли % False, True
:param sizeGauge: Размер полосы индикатора
:param fontSize: Шрифт надписи на полосе индикатора
:param txtColor: Цвет надписи на полосе индикатора
:return... | 625941c97cff6e4e81117a1e |
def _encrypt_file_part(file, server_secret, client_secret, path=True): <NEW_LINE> <INDENT> passphrase = server_secret + client_secret <NEW_LINE> message = PGPMessage.new( file=path, message=file, compression=CompressionAlgorithm.Uncompressed) <NEW_LINE> cipher_message = message.encrypt(passphrase=passphrase, cipher=Sym... | Encrypts a given file part for uploading to SendSafely.
:param file: The path of the file (as a String) or a file as bytes. Set path param to False if using bytes.
:param server_secret: The server secret, may be obtained through using
SendSafely.get_package_information(package_id)
:param client_secret: The client_secre... | 625941c9eab8aa0e5d26dbf0 |
def read_datum_for_year(year): <NEW_LINE> <INDENT> datum_filename = DATUM_DIR / f"datum_{year}_sec.csv" <NEW_LINE> try: <NEW_LINE> <INDENT> df = pd.read_csv(datum_filename) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> warn(f"No datum file found for the year {year}; check for '{datum_filename}'") <N... | Read specific datum and prepare datetime index | 625941c9a79ad161976cc1de |
def _getWildcardForms(self, searchStr, **options): <NEW_LINE> <INDENT> def isReadingEntity(entity, cache={}): <NEW_LINE> <INDENT> if entity not in cache: <NEW_LINE> <INDENT> cache[entity] = self._readingFactory.isReadingEntity(entity, self._dictInstance.READING, **self._dictInstance.READING_OPTIONS) <NEW_LINE> <DEDENT>... | Gets reading decomposition and prepares wildcards. Needs a method
:meth:`~cjklib.dictionary.search._SimpleReadingWildcardBase._getReadings`
to do the actual decomposition. | 625941c921a7993f00bc7d87 |
def top(topfn, test=None, **kwargs): <NEW_LINE> <INDENT> __pillar__.update(kwargs.get("pillar", {})) <NEW_LINE> st_kwargs = __salt__.kwargs <NEW_LINE> __opts__["grains"] = __grains__.value() <NEW_LINE> opts = salt.utils.state.get_sls_opts(__opts__, **kwargs) <NEW_LINE> if salt.utils.args.test_mode(test=test, **kwargs):... | Execute a specific top file instead of the default
CLI Example:
.. code-block:: bash
salt '*' state.top reverse_top.sls
salt '*' state.top reverse_top.sls exclude=sls_to_exclude
salt '*' state.top reverse_top.sls exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]" | 625941c996565a6dacc8f764 |
def __init__(self): <NEW_LINE> <INDENT> self.isstring = False <NEW_LINE> self.nodes = {} | Initialize your data structure here. | 625941c9566aa707497f4603 |
def search(self, qtotal, topk, queries): <NEW_LINE> <INDENT> url = 'http://' + self.host + ':' + str(self.port) + '/search' <NEW_LINE> data_request = {'qtotal':qtotal, 'topk': topk, 'queries': queries} <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.post(url, data=json.dumps(data_request), headers=headers) <NEW... | 查询向量
:param qtotal: 查询的向量个数
:param topk: 查询topk个相似的向量
:param queries: 查询向量的list
:type list[list]
:return: | 625941c923e79379d52ee5fd |
def play_episode(self, episode): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.episode = episode <NEW_LINE> self._started = self.episode.progress <NEW_LINE> self.set_state(Player.BUFFERING) <NEW_LINE> if episode.local_path and os.path.isfile(episode.absolute_local_path): <NEW_LINE> <INDENT> uri = Gst.filename_to_uri(... | Start the playback of an episode
Parameters
----------
episode : Episode | 625941c94f6381625f114ad3 |
def unique_slugify(instance, value,site, slug_field_name='slug', queryset=None, slug_separator='-'): <NEW_LINE> <INDENT> slug_field = instance._meta.get_field(slug_field_name) <NEW_LINE> slug = getattr(instance, slug_field.attname) <NEW_LINE> slug_len = slug_field.max_length <NEW_LINE> slug = slugify(value) <NEW_LINE> ... | Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all()`` queryset fro... | 625941c94f6381625f114ad4 |
def rccd(df, n=59, m=21, k=28): <NEW_LINE> <INDENT> _rccd = pd.DataFrame() <NEW_LINE> _rccd['date'] = df.date <NEW_LINE> rc = df.close / df.close.shift(n) * 100 <NEW_LINE> arc = sma(rc.shift(), n) <NEW_LINE> dif = _ma(arc.shift(), m) - _ma(arc.shift(), k) <NEW_LINE> _rccd['rccd'] = sma(dif, n) <NEW_LINE> return _rccd | # TODO: 计算结果错误和同花顺不同,检查不出来为什么
异同离差变化率指数 rate of change convergence divergence rccd(59,21,28)
RC=收盘价/REF(收盘价,N)×100%
ARC=EMA(REF(RC,1),N,1)
DIF=MA(ref(ARC,1),N1)-MA MA(ref(ARC,1),N2)
RCCD=SMA(DIF,N,1) | 625941c9bd1bec0571d906c8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.