text
stringlengths
78
104k
score
float64
0
0.18
def asRGBA(self): """ Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *info* reflect the returned pixels, not the source image. ...
0.000984
def get_view_name(view_cls, suffix=None): """ Given a view class, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. """ name = view_cls.__name__ name = formatting....
0.001898
def is_request_sent(request, relation='ceph'): """Check to see if a functionally equivalent request has already been sent Returns True if a similair request has been sent @param request: A CephBrokerRq object """ states = get_request_states(request, relation=relation) for rid in states.keys():...
0.002513
def _opt_call_from_base_type(self, value): """Call _from_base_type() if necessary. If the value is a _BaseValue instance, unwrap it and call all _from_base_type() methods. Otherwise, return the value unchanged. """ if isinstance(value, _BaseValue): value = self._call_from_base_type(value...
0.005814
def _prepare_coords(lons1, lats1, lons2, lats2): """ Convert two pairs of spherical coordinates in decimal degrees to numpy arrays of radians. Makes sure that respective coordinates in pairs have the same shape. """ lons1 = numpy.radians(lons1) lats1 = numpy.radians(lats1) assert lons1.s...
0.002079
def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs): """ Get all the items in a group, in a scenario. """ user_id = int(kwargs.get('user_id')) if scenario is None: scenario = _get_scenario(scenario_id, user_id) _check_network_ownership(scenario.network_id, user...
0.001894
def convert_code_to_value(M_c, cidx, code): """ For a column with categorical data, this function takes the 'code': the integer used to represent a specific value, and returns the corresponding raw value (e.g. 'Joe' or 234.23409), which is always encoded as a string. Note that the underlying store ...
0.005548
def p_case_clause(self, p): """case_clause : CASE expr COLON source_elements""" p[0] = ast.Case(expr=p[2], elements=p[4])
0.014599
def instruction_RTI(self, opcode): """ The saved machine state is recovered from the hardware stack and control is returned to the interrupted program. If the recovered E (entire) bit is clear, it indicates that only a subset of the machine state was saved (return address and con...
0.009224
def deleteCertificate(self, certName): """ This operation deletes an SSL certificate from the key store. Once a certificate is deleted, it cannot be retrieved or used to enable SSL. Inputs: certName - name of the cert to delete """ params = {"f" : "js...
0.005172
def ProcessEvent( self, event, parser_chain=None, file_entry=None, query=None): """Processes an event before it written to the storage. Args: event (EventObject|EventData): event or event data. parser_chain (Optional[str]): parsing chain up to this point. file_entry (Optional[dfvfs.File...
0.007961
def _queue_response_channel(self, obj): """Generate the feedback channel name from the object's id. :param obj: The Channels message object. """ return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID])
0.010791
def iter_import_chunks(self): """Iterate over space-separated import chunks in a file.""" chunk = [] last_line = None for leaf in self.python_file.tree.body: if isinstance(leaf, (ast.Import, ast.ImportFrom)): # we've seen previous imports but this import is not in the same chunk if...
0.01013
def __spawn(self): """通过手动方式, 指定字段类型与默认值, - 如果配置文件有变动, 需要手动在这里添加 - 如果配置字段未在这里指出, 则默认为 string, 使用时需要手动转换 """ dat = { 'log.enabled': False, 'log.file_pth': '{}/{}.log'.format(self._pth, self._cfg_name), 'log.file_backups': 3, ...
0.004505
def config_to_equation(poi=None): """ Generates a product.equation file for the given product name. It generates it from the <product_name>.config file in the products folder. For that you need to have your project imported to featureIDE and set the correct settings. """ from . import utils ...
0.003099
def histogram_day_counts( df, variable ): """ Create a week-long histogram of counts of the variable for each day. It is assumed that the DataFrame index is datetime and that the variable `weekday_name` exists. """ if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]: ...
0.022222
def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i)
0.009852
def decrypt_result(self, *args, **kwargs): """ Decrypts ProcessData result with comm keys :param args: :param kwargs: :return: """ if self.response is None: raise ValueError('Empty response') if self.response.response is None \ ...
0.001599
def resolve_lookups(variable, context, provider): """Resolve a set of lookups. Args: variable (:class:`stacker.variables.Variable`): The variable resolving it's lookups. context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseP...
0.001064
def set_bar(self, bar, value): """Set bar to desired color. Bar should be a value of 0 to 23, and value should be OFF, GREEN, RED, or YELLOW. """ if bar < 0 or bar > 23: # Ignore out of bounds bars. return # Compute cathode and anode value. c = (b...
0.004724
def pyc_to_py(path_to_file): """Change some file extensions to those which are more likely to be text >>> pyc_to_py('vim.pyc') == 'vim.py' True """ stem, ext = os.path.splitext(path_to_file) if ext == '.pyc': return '%s.py' % stem return path_to_file
0.003484
def get_stored_cert_serials(store): ''' Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store> ''' cmd = "certutil.exe -store {0}...
0.001901
def crop_image(image, threshold): """ Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника ...
0.004458
def append(self, val): """Append byte string val to buffer If the result exceeds the length of the buffer, behavior depends on whether instance was initialized as strict. In strict mode, a ValueError is raised. In non-strict mode, the buffer is extended as necessary. """ ...
0.003527
def pickle_data(data, picklefile): """Helper function to pickle `data` in `picklefile`.""" with open(picklefile, 'wb') as f: pickle.dump(data, f, protocol=2)
0.00578
def show_security_group_rule(self, security_group_rule, **_params): """Fetches information of a certain security group rule.""" return self.get(self.security_group_rule_path % (security_group_rule), params=_params)
0.007874
def sliding(self, size, step=1): """ Groups elements in fixed size blocks by passing a sliding window over them. The last window has at least one element but may have less than size elements :param size: size of sliding window :param step: step size between windows :ret...
0.00907
def Clamond(Re, eD, fast=False): r'''Calculates Darcy friction factor using a solution accurate to almost machine precision. Recommended very strongly. For details of the algorithm, see [1]_. Parameters ---------- Re : float Reynolds number, [-] eD : float Relative roug...
0.008875
def varify_user_lock(repository_path, session_token): """ Verify that a returning user has a valid token and their lock has not expired """ with open(cpjoin(repository_path, 'user_file'), 'r') as fd2: content = fd2.read() if len(content) == 0: return False try: res = json.loads(content)...
0.012685
def com_google_fonts_check_name_trailing_spaces(ttFont): """Name table records must not have trailing spaces.""" failed = False for name_record in ttFont['name'].names: name_string = name_record.toUnicode() if name_string != name_string.strip(): failed = True name_key = tuple([name_record.plat...
0.013464
def run(self): """ Receives the serial data into the self._raw buffer :return: """ run_once = True while (run_once or self._threaded) and self.end is False: self.service_tx_queue() self.parse_messages() run_once = False if...
0.004348
def make_error_block(self, block, block_number): """This function constructs the error correction block of the given data block. This is *very complicated* process. To understand the code you need to read: * http://www.thonky.com/qr-code-tutorial/part-2-error-correction/ * http:...
0.007513
def aggregate(self, reducer, seed=default, result_selector=identity): '''Apply a function over a sequence to produce a single result. Apply a binary function cumulatively to the elements of the source sequence so as to reduce the iterable to a single value. Note: This method uses immed...
0.000899
def parse_rrule(component, tz=UTC): """ Extract a dateutil.rrule object from an icalendar component. Also includes the component's dtstart and exdate properties. The rdate and exrule properties are not yet supported. :param component: icalendar component :param tz: timezone for DST handling...
0.005137
def assignParameters(self,**kwds): ''' Assign an arbitrary number of attributes to this agent. Parameters ---------- **kwds : keyword arguments Any number of keyword arguments of the form key=value. Each value will be assigned to the attribute named in s...
0.011186
def _has_homonym_in_upper_function_scope(self, node, index): """ Return True if there is a node with the same name in the to_consume dict of an upper scope and if that scope is a function :param node: node to check for :type node: astroid.Node :param index: index of the ...
0.007833
def qrange(self, name, offset, limit): """ Return a ``limit`` slice of the list ``name`` at position ``offset`` ``offset`` can be negative numbers just like Python slicing notation Similiar with **Redis.LRANGE** :param string name: the queue name :param int offset: the...
0.007236
def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use th...
0.001929
def soma_radii(nrn_pop, neurite_type=NeuriteType.soma): ''' Get the radii of the somata of a population of neurons Note: If a single neuron is passed, a single element list with the radius of its soma member is returned. ''' assert neurite_type == NeuriteType.soma, 'Neurite type must be...
0.002469
def nguHanh(tenHanh): """ Args: tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M, Thuy hoặc T, Hoa hoặc H, Tho hoặc O Returns: Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành Raises: Exception: Description """ if tenHanh in ["Kim",...
0.000831
def gpg_app_put_key( blockchain_id, appname, keyname, key_data, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ): """ Put an application GPG key. Stash the private key locally to an app-specific keyring. Return {'status': True, 'key_url': ..., 'key_data': ...} on success ...
0.014604
def from_torch_layers(cls, module_graph, variable): """Recover something like neural net layers from PyTorch Module's and the compute graph from a Variable. Example output for a multi-layer RNN. We confusingly assign shared embedding values to the encoder, but ordered next to the decode...
0.002342
def load_manifest(app, filename='manifest.json'): '''Load an assets json manifest''' if os.path.isabs(filename): path = filename else: path = pkg_resources.resource_filename(app, filename) with io.open(path, mode='r', encoding='utf8') as stream: data = json.load(stream) _regi...
0.002747
def token_generator(self, texts, **kwargs): """Yields tokens from texts as `(text_idx, word)` Args: texts: The list of texts. **kwargs: Supported args include: n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default. batch_si...
0.003571
def match_alphabet(self, pattern): """Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations. """ s = {} for char in pattern: s[char] = 0 for i in range(len(pattern)): s[pattern[i]] |= 1 << (len(patte...
0.008696
def fetch_cached(task_id, wait=0, broker=None): """ Return the processed task from the cache backend """ if not broker: broker = get_broker() start = time() while True: r = broker.cache.get('{}:{}'.format(broker.list_key, task_id)) if r: task = SignedPackage.l...
0.001161
def get_logs(self, request): """ Get logs from log service. Unsuccessful opertaion will cause an LogException. Note: for larger volume of data (e.g. > 1 million logs), use get_log_all :type request: GetLogsRequest :param request: the GetLogs request parameters class. ...
0.00558
def get_free_gpus(max_procs=0): """ Checks the number of processes running on your GPUs. Parameters ---------- max_procs : int Maximum number of procs allowed to run on a gpu for it to be considered 'available' Returns ------- availabilities : list(bool) List of...
0.004329
def depth_january_average_ground_temperature(self, value=None): """Corresponds to IDD Field `depth_january_average_ground_temperature` Args: value (float): value for IDD Field `depth_january_average_ground_temperature` Unit: C if `value` is None it will not b...
0.004684
def rsi(series, window=14): """ compute the n period relative strength indicator """ # 100-(100/relative_strength) deltas = np.diff(series) seed = deltas[:window + 1] # default values ups = seed[seed > 0].sum() / window downs = -seed[seed < 0].sum() / window rsival = np.zeros_l...
0.00117
def write_nex(data, sidx, pnames): """ write the nexus output file from the tmparr[seqarray] and tmparr[maparr] """ ## grab seq data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: s...
0.008533
def _days_to_seconds(cls, val, **kwargs): ''' converts a number of days to seconds ''' zero_value = kwargs.get('zero_value', 0) if val is not None: if val == 0: return zero_value return val * 86400 else: return 'Not Defi...
0.006173
def pass_q_v1(self): """Assing the actual value of the lower joint of of the subreach downstream to the outlet sequence.""" der = self.parameters.derived.fastaccess new = self.sequences.states.fastaccess_new out = self.sequences.outlets.fastaccess out.q[0] += new.qjoints[der.nmbsegments]
0.003205
def _convert_todo(self, p_todo): """ Converts a Todo instance (Topydo) to an icalendar Todo instance. """ def _get_uid(p_todo): """ Gets a unique ID from a todo item, stored by the ical tag. If the tag is not present, a random value is assigned to it and returned. ...
0.001695
def print_data(data_sources): """ Print dataset information in tabular form """ if not data_sources: return headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"] data_list = [] for data_source in data_sources: data_list.append([data_source.name, ...
0.002114
def get_stripped_prefix(source, prefix): """Go through source, extracting every key/value pair where the key starts with the given prefix. """ cut = len(prefix) return { k[cut:]: v for k, v in source.items() if k.startswith(prefix) }
0.003663
def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is...
0.003229
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.network.v2015_06_15.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.network.v2016_09_01.models>` * 2016-12-01: :mod:`v2016_12_01....
0.00573
def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" ...
0.002158
def engineer_info(self, action): """ Returns: dict: engineer command information - arguments (list<dict>): command arguments - args (list): args to pass through to click.argument - kwargs (dict): keyword arguments to pass through to c...
0.004762
def _get_app_module(self): # type: () -> Callable """Returns a module which binds the current app and configuration. :return: configuration callback :rtype: Callable """ def configure(binder): # type: (Binder) -> Callable binder.bind(ServiceAppli...
0.006757
def execute(self, args): """Execute the hook followed by the playbook using the hook as tag.""" hook_name = os.path.basename(args[0]) extra_vars = None if hook_name in self._actions: extra_vars = self._actions[hook_name](args[1:]) else: super(AnsibleHooks,...
0.004283
def set_viewport(self, *args): """Set the OpenGL viewport This is a wrapper for gl.glViewport. Parameters ---------- *args : tuple X and Y coordinates, plus width and height. Can be passed in as individual components, or as a single tuple with fo...
0.008351
def thread_view(request, pk): ''' View an individual thread. ''' if request.is_ajax(): if not request.user.is_authenticated(): return HttpResponse(json.dumps(dict()), content_type="application/json") try: user_profile = UserProfile.objects....
0.002017
def create_id2amendment_info(path, tag): """Searches for JSON files in this repo and returns a map of amendment id ==> (`tag`, dir, amendment filepath) where `tag` is typically the shard name """ d = {} for triple in os.walk(path): root, files = triple[0], triple[2] for filename ...
0.003617
def decls( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of declarations, that are matched defined criteria""" return (...
0.002878
def get_time_period(period_name): """ Given a time period name, fetch the hydra-compatible time abbreviation. """ time_abbreviation = time_map.get(period_name.lower()) if time_abbreviation is None: raise Exception("Symbol %s not recognised as a time period"%period_name) ret...
0.008798
def init(): ''' Initialize the library ''' globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) globals()["sockfd"] = globals()["sock"].fileno()
0.00578
def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.form...
0.001006
def elekta_icon_fbp(ray_transform, padding=False, filter_type='Hann', frequency_scaling=0.6, parker_weighting=True): """Approximation of the FDK reconstruction used in the Elekta Icon. Parameters ---------- ray_transform : `RayTransform` The ray transform...
0.000652
def load_config(path=None, defaults=None): """ Loads and parses an INI style configuration file using Python's built-in configparser module. If path is specified, load it. If ``defaults`` (a list of strings) is given, try to load each entry as a file, without throwing any error if the operation fail...
0.001179
def format_explanation(explanation, original_msg=None): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visi...
0.001414
def get_map_data(self): """ Returns a serializable data set describing the map location """ return { 'containerSelector': '#' + self.get_map_element_id(), 'center': self.map_center_description, 'marker': self.map_marker_description or self.map_center_...
0.004115
def actions(self, state): '''Returns a list of the pieces we can move to the empty space.''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') actions = [] if row_e > 0: actions.append(rows[row_e - 1][col_e]) if row_e < 2: actio...
0.003824
def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d outliers' % (0, self.oiter, len(self.outmask))) def M(x): return np.delete(x, np.concatenate( [self...
0.001071
def getRole(self, label): """Get the :class:`rtcclient.models.Role` object by the label name :param label: the label name of the role :return: the :class:`rtcclient.models.Role` object :rtype: :class:`rtcclient.models.Role` """ if not isinstance(label, six.string_types)...
0.002037
def AddClient(self, client): """Adds a client to the index. Args: client: A VFSGRRClient record to add or update. """ client_id, keywords = self.AnalyzeClient(client) self.AddKeywordsForName(client_id, keywords)
0.004184
def flush(self, timeout=1.0): """Immediately processes all pending messages on the SUB channel. Callers should use this method to ensure that :method:`call_handlers` has been called for all messages that have been received on the 0MQ SUB socket of this channel. This method is t...
0.002215
def _filter_by_pattern(self, pattern): """Filter the Filter the Data Collection based on a list of booleans.""" try: _len = len(pattern) except TypeError: raise TypeError("pattern is not a list of Booleans. Got {}".format( type(pattern))) _filt_val...
0.009615
def _insert_contents(self, fzpage, newcont, overlay): """_insert_contents(self, fzpage, newcont, overlay) -> PyObject *""" return _fitz.Tools__insert_contents(self, fzpage, newcont, overlay)
0.009709
def _get_column_type(self,column): """ Return 'numeric' if the column is of type integer or real, otherwise return 'string'. """ ctype = column.GetType() if ctype in [ogr.OFTInteger, ogr.OFTReal]: return 'numeric' else: return 'string'
0.010033
def merge_resources(resource_list): """Merge multiple resources to get a new resource. Resources earlier in the list take precedence: if multiple resources share a label key, use the value from the first resource in the list with that key. The combined resource's type will be the first non-null type in...
0.001236
def install_excepthook(hook_type="color", **kwargs): """ This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the construct...
0.001116
def linear_density(im, bins=25, voxel_size=1, log=False): r""" Determines the probability that a point lies within a certain distance of the opposite phase *along a specified direction* This relates directly the radial density function defined by Torquato [1], but instead of reporting the probabili...
0.000567
def _create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 if self._stopped.is_set(): break try: self._connection = Connection(self.hostname, ...
0.002591
def copy_pkg(self, pkg, src_only=False): "Install boost deps from the third_party directory" if getattr(self, 'no_' + pkg) is None: print('Copying boost dependencies') to_copy = pkg, else: return src = os.path.join('third_party', *to_copy) #...
0.002833
def gen_all(self): """Generator of all borders""" borderfuncs = [ self.get_b, self.get_r, self.get_t, self.get_l, self.get_tl, self.get_tr, self.get_rt, self.get_rb, self.get_br, self.get_bl, self.get_lb, self.get_lt, ] for borderfunc in borderfuncs:...
0.005698
def InsertData(self, table_id, fd, schema, job_id): """Insert data into a bigquery table. If the table specified doesn't exist, it will be created with the specified schema. Args: table_id: string table id fd: open file descriptor containing the newline separated JSON schema: BigQuer...
0.003542
def sendEmail(self, url, attempt, email, _sendEmail=_sendEmail): """ Send an email for the given L{_PasswordResetAttempt}. @type url: L{URL} @param url: The URL of the password reset page. @type attempt: L{_PasswordResetAttempt} @param attempt: An L{Item} representing a...
0.002304
def bind_fields_to_model_cls(cls, model_fields): """Bind fields to model class.""" return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields)
0.010526
def prepare_outdir(self): """create temp directory.""" self._outdir = self.outdir if self._outdir is None: self._tmpdir = TemporaryDirectory() self.outdir = self._tmpdir.name elif isinstance(self.outdir, str): mkdirs(self.outdir) else: ...
0.004896
def _vertex_list_to_dataframe(ls, id_column_name): """ Convert a list of vertices into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) df = pd.DataFrame({id_column_name: [v....
0.004819
def _update_simulation_start_cards(self): """ Update GSSHA cards for simulation start """ if self.simulation_start is not None: self._update_card("START_DATE", self.simulation_start.strftime("%Y %m %d")) self._update_card("START_TIME", self.simulation_start.strfti...
0.012048
def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None: """ Specify the state prior to the test execution. Multiple invocations don't override the state but extend it instead. In general, the elements of `state_definitions` are nested dictionaries of the following form: .. code-bl...
0.002541
def energy(self, v, h=None): """Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) ...
0.004264
def mtf_image_transformer_base_imagenet(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 hparams.d_ff = 2048 hparams.hidden_size = 512 hparams.num_decoder_layers = 12 hparams.le...
0.028319
def timing_decorator(func): """Prints the time func takes to execute.""" @functools.wraps(func) def wrapper(*args, **kwargs): """ Wrapper for printing execution time. Parameters ---------- print_time: bool, optional whether or not to print time function t...
0.001366
def tag(ctx, corpus, output): """Tag chemical entities and write CHEMDNER annotations predictions file.""" click.echo('chemdataextractor.chemdner.tag') for line in corpus: pmid, title, abstract = line.strip().split(u'\t') # print(pmid) counter = 1 d = Document(Title(title), P...
0.004539
def run_build_lib(folder): """Run the doxygen make command in the designated folder.""" try: retcode = subprocess.call("cd %s; make" % folder, shell=True) retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True) retcode = subprocess.call("mkdir _build", shell=True) ret...
0.003091
def benchmark(cores, args): """ benchmark is used for Processing per core translation. Each core translates the whole input file. Return after all translations done. :param cores: the number of cores used for translation, each core will launch a thread to translate :param args: input parameters ...
0.010676