code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
default_lang = self.babel.default_locale.language default_title = self.babel.default_locale.get_display_name( default_lang) yield (default_lang, default_title) for l, title in current_app.config.get('I18N_LANGUAGES', []): yield l, title
def iter_languages(self)
Iterate over list of languages.
3.973471
3.733287
1.064336
if self._languages_cache is None: self._languages_cache = list(self.iter_languages()) return self._languages_cache
def get_languages(self)
Get list of languages.
3.698369
3.210186
1.152073
if self._locales_cache is None: langs = [self.babel.default_locale] for l, dummy_title in current_app.config.get('I18N_LANGUAGES', []): langs.append(self.babel.load_locale(l)) self._locales_cache = langs return self._locales_cache
def get_locales(self)
Get a list of supported locales. Computes the list using ``I18N_LANGUAGES`` configuration variable.
3.854538
3.690489
1.044452
vars_to_skip = ('__dict__', '__weakref__') def wrapper(cls): copied_dict = { key: value for key, value in cls.__dict__.items() if key not in vars_to_skip } return metaclass(cls.__name__, cls.__bases__, copied_dict) return wrapper
def add_metaclass(metaclass)
Class decorator for creating a class with a metaclass. Adapted from the six project: https://pythonhosted.org/six/
2.54528
2.89479
0.879262
'''When this is used only for peeking reuslt `new_nodes` can be any type with `host` and `port` attributes ''' param = gen_distribution(nodes, new_nodes) param['max_slaves_limit'] = max_slaves_limit return cls(**param)
def from_nodes(cls, nodes, new_nodes, max_slaves_limit=None)
When this is used only for peeking reuslt `new_nodes` can be any type with `host` and `port` attributes
10.839616
3.348663
3.236998
for filename in self.args: path = os.path.abspath(filename) yield { 'name': path, # 'file_dep': [path], 'actions': [(self.fun, (filename,))], }
def _gen_tasks(self)
generate doit tasks for each file
5.259085
4.133126
1.272423
if self.log_filename: print('Output will be logged to `%s`.' % self.log_filename) start_time = time.strftime(self.timestamp_fmt) print('Started %s' % start_time) if self.log_filename: orig_stdout = sys.stdout orig_stderr = sys.stderr ...
def start(self)
Begin executing tasks.
2.586106
2.477943
1.04365
return generate_tasks('taskname that shows up in log', self._gen_tasks()), self.DOIT_CONFIG
def load_tasks(self, cmd, params, args)
implements loader interface, return (tasks, config)
62.625626
37.07053
1.689364
if getattr(iterable, "popleft", False): def next_item(coll): return coll.popleft() elif getattr(iterable, "popitem", False): def next_item(coll): return coll.popitem() else: def next_item(coll): return coll.pop() while True: try: ...
def drain(iterable)
Helper method that empties an iterable as it is iterated over. Works for: * ``dict`` * ``collections.deque`` * ``list`` * ``set``
2.573901
2.939024
0.875767
avg = int(n / m) remain = n - m * avg data = list(itertools.repeat(avg, m)) for i in range(len(data)): if not remain: break data[i] += 1 remain -= 1 return data
def divide(n, m)
Divide integer n to m chunks
3.094612
3.108516
0.995527
target = [] while len(target) < n and nodes: for ip, node_group in list(nodes.items()): if not node_group: nodes.pop(ip) continue target.append(node_group.pop(0)) if len(target) >= n: break return target
def spread(nodes, n)
Distrubute master instances in different nodes { "192.168.0.1": [node1, node2], "192.168.0.2": [node3, node4], "192.168.0.3": [node5, node6] } => [node1, node3, node5]
3.476964
3.087226
1.126242
ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc
def is_local_url(target)
Determine if URL is safe to redirect to.
2.0401
1.818255
1.12201
for target in request.values.get('next'), request.referrer: if target and is_local_url(target): return target
def get_redirect_target()
Get URL to redirect to and ensure that it is local.
4.564818
3.772231
1.210111
# Check if language is available. lang_code = lang_code or request.values.get('lang_code') languages = dict(current_app.extensions['invenio-i18n'].get_languages()) if lang_code is None or lang_code not in languages: abort(404 if request.method == 'GET' else 400) # Set language in sessi...
def set_lang(lang_code=None)
Set language in session and redirect.
2.707018
2.570563
1.053084
blueprint = Blueprint( 'invenio_i18n', __name__, template_folder='templates', static_folder='static', ) if register_default_routes: blueprint.add_url_rule('/', view_func=set_lang, methods=['POST']) blueprint.add_url_rule('/<lang_code>', view_func=set_lan...
def create_blueprint(register_default_routes=True)
Create Invenio-I18N blueprint.
2.102647
1.801092
1.167429
with open(filepath, 'rb') as f: content = f.read() return compile_into_spirv(content, stage, filepath, optimization=optimization, warnings_as_errors=warnings_as_errors)
def compile_file_into_spirv(filepath, stage, optimization='size', warnings_as_errors=False)
Compile shader file into Spir-V binary. This function uses shaderc to compile your glsl file code into Spir-V code. Args: filepath (strs): Absolute path to your shader file stage (str): Pipeline stage in ['vert', 'tesc', 'tese', 'geom', 'frag', 'comp'] optimiza...
2.329175
3.206519
0.726387
# extract parameters stage = stages_mapping[stage] lang = languages_mapping[language] opt = opt_mapping[optimization] # initialize options options = lib.shaderc_compile_options_initialize() lib.shaderc_compile_options_set_source_language(options, lang) lib.shaderc_compile_options_s...
def compile_into_spirv(raw, stage, filepath, language="glsl", optimization='size', suppress_warnings=False, warnings_as_errors=False)
Compile shader code into Spir-V binary. This function uses shaderc to compile your glsl or hlsl code into Spir-V code. You can refer to the shaderc documentation. Args: raw (bytes): glsl or hlsl code (bytes format, not str) stage (str): Pipeline stage in ['vert', 'tesc', 'tese', 'geom', ...
2.352511
2.37804
0.989265
expfiles = [] for file in files: if os.path.isdir(file): for dirpath, dirnames, filenames in os.walk(file): for filename in filenames: expfiles.append(os.path.join(dirpath, filename)) else: expfiles.append(file) for path in ex...
def expand_folder(files)
Return a clone of file list files where all directories are recursively replaced with their contents.
1.901605
1.870314
1.01673
if len(sys.argv) > 1: file_list = list(sys.argv[1:]) # make copy else: files_str = input('Select the files you want to process and drag and drop them onto this window, ' 'or type their names separated by spaces. Paths containing spaces should be ' ...
def get_file_list()
Return a list of strings corresponding to file names supplied by drag and drop or standard input.
4.215043
4.084228
1.032029
nodes = [ClusterNode.from_uri(n) for n in args.nodes] cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) echo("Deleting...") for node in nodes: cluster.delete_node(node) cluster.wait()
def delete(args)
Delete nodes from the cluster
4.33179
4.13133
1.048522
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) cluster.reshard()
def reshard(args)
Balance slots in the cluster. This command will try its best to distribute slots equally.
8.827507
9.249476
0.954379
slave = ClusterNode.from_uri(args.node) master = ClusterNode.from_uri(args.master) if not master.is_master(): ctx.abort("Node {!r} is not a master.".format(args.master)) try: slave.replicate(master.name) except redis.ResponseError as e: ctx.abort(str(e)) Cluster.fr...
def replicate(ctx, args)
Make node to be the slave of a master.
3.853721
3.342792
1.152845
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster)) for node in cluster.masters: node.flushall()
def flushall(args)
Execute flushall in all cluster nodes.
6.450469
5.894763
1.094271
t = at if at is not None else time.time() marker = Marker().start(t) labels[label] = marker.dumps()
def start(label, at=None)
Begins the countdown
10.418255
10.715566
0.972254
t = at if at is not None else time.time() if label not in labels: return None timer = Marker().loads(labels[label]) if timer.is_running() or (timer.is_stopped() and not stop_once): timer.stop(t) if remove_from_labels: del labels[label] else: labels[label]...
def stop(label, at=None, remove_from_labels=False, stop_once=True)
Stops the countdown
3.510396
3.542152
0.991035
if label not in labels: return None if "duration" in labels[label]: return Duration(labels[label]["duration"]) if stop_it: return stop(label, at=stop_at) else: return None
def duration(label, stop_it=True, stop_at=None)
Returns duration in seconds for label
3.777044
3.414623
1.106138
http_code = resp.status_code if http_code not in self.http_success_status_codes: raise RequestError( response=resp, message='[HTTP {}] {}'.format(http_code, resp.reason) ) try: body = resp.json() except ValueErr...
def _handle_response(self, resp)
Handle the response from QuadrigaCX. :param resp: Response from QuadrigaCX. :type resp: requests.models.Response :return: Response body. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was not returned.
2.184119
2.192572
0.996145
response = self._session.get( url=self._url + endpoint, params=params, timeout=self._timeout ) return self._handle_response(response)
def get(self, endpoint, params=None)
Send an HTTP GET request to QuadrigaCX. :param endpoint: API endpoint. :type endpoint: str | unicode :param params: URL parameters. :type params: dict :return: Response body from QuadrigaCX. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was not...
2.739718
3.035851
0.902455
nonce = int(time.time() * 10000) hmac_msg = str(nonce) + self._client_id + self._api_key signature = hmac.new( key=self._hmac_key, msg=hmac_msg.encode('utf-8'), digestmod=hashlib.sha256 ).hexdigest() if payload is None: pa...
def post(self, endpoint, payload=None)
Send an HTTP POST request to QuadrigaCX. :param endpoint: API endpoint. :type endpoint: str | unicode :param payload: Request payload. :type payload: dict :return: Response body from QuadrigaCX. :rtype: dict :raise quadriga.exceptions.RequestError: If HTTP OK was...
2.077465
2.130522
0.975097
print("Commands available:\n") for name in dir(self): if not name.startswith("command_"): continue name_clean = name[len("command_"):] print("%s:\n - %s\n" % (name_clean, getattr(self, name).__doc__.strip()))
def command_help(self, *args, **kwargs)
Displays this help menu.
3.255819
3.223393
1.010059
def usage(): print(self.command_setup.__doc__) sys.exit(1) if len(args) == 0: usage() try: # All of these (except mount_opt) map directly to the model properties # We allow several `mount_opt` flags and merge their values, be...
def command_setup(self, *args)
Defines a new sftp file system configuration or edits an old one with the same id. Usage: sftpman setup {options} Available {options}: --id={unique system identifier} You use this to recognize and manage this sftp system. It determines what the local mount poi...
3.669286
3.041718
1.20632
# Intentionally reading the first system_id separately, # because it's required. The others are optional. # This ensures that we'll generate an error if someone tries to call # this without the required argument. system_ids = (system_id,) + system_ids has_failed ...
def command_rm(self, system_id, *system_ids)
Removes a system by id. Usage: sftpman rm {system_id}.. For a list of system ids, see `sftpman ls available`.
4.374099
4.380165
0.998615
checks_pass, failures = self.environment.perform_preflight_check() if checks_pass: print('All checks pass.') else: sys.stderr.write('Problems encountered:\n') for msg in failures: sys.stderr.write(' - %s\n' % msg) sys.exit(...
def command_preflight_check(self)
Detects whether we have everything needed to mount sshfs filesystems.
3.991558
3.808862
1.047966
if list_what in ('available', 'mounted', 'unmounted'): callback = getattr(self.environment, 'get_%s_ids' % list_what) lst = callback() else: lst = [] if len(lst) != 0: print(("\n".join(lst)))
def command_ls(self, list_what)
Lists the available/mounted/unmounted sftp systems. Usage: sftpman ls {what} Where {what} is one of: available, mounted, unmounted
5.011212
4.350243
1.151938
system_ids = (system_id,) + system_ids has_failed = False for system_id in system_ids: try: system = SystemModel.create_by_id(system_id, self.environment) controller = SystemControllerModel(system, self.environment) controller....
def command_mount(self, system_id, *system_ids)
Mounts the specified sftp system, unless it's already mounted. Usage: sftpman mount {id}..
2.408853
2.442552
0.986204
system_ids = (system_id,) + system_ids has_failed = False for system_id in system_ids: try: system = SystemModel.create_by_id(system_id, self.environment) controller = SystemControllerModel(system, self.environment) controller....
def command_umount(self, system_id, *system_ids)
Unmounts the specified sftp system. Usage: sftpman umount {id}..
3.104151
3.185351
0.974508
self._logger.debug("{}: {}".format(self.name, message))
def _log(self, message)
Log a debug message prefixed with order book name. :param message: Debug message. :type message: str | unicode
5.425097
4.7808
1.134768
self._log('get ticker') return self._rest_client.get( endpoint='/ticker', params={'book': self.name} )
def get_ticker(self)
Return the latest ticker information. :return: Latest ticker information. :rtype: dict
7.797841
7.975545
0.977719
self._log('get public orders') return self._rest_client.get( endpoint='/order_book', params={'book': self.name, 'group': int(group)} )
def get_public_orders(self, group=False)
Return public orders that are currently open. :param group: If set to True (default: False), orders with the same price are grouped. :type group: bool :return: Public orders currently open. :rtype: dict
5.808709
5.852087
0.992587
self._log('get public trades') return self._rest_client.get( endpoint='/transactions', params={'book': self.name, 'time': time_frame} )
def get_public_trades(self, time_frame='hour')
Return public trades that were completed recently. :param time_frame: Time frame. Allowed values are "minute" for trades in the last minute, or "hour" for trades in the last hour (default: "hour"). :type time_frame: str | unicode :return: Public trades completed recently...
6.211341
6.444396
0.963836
self._log('get user orders') return self._rest_client.post( endpoint='/open_orders', payload={'book': self.name} )
def get_user_orders(self)
Return user's orders that are currently open. :return: User's orders currently open. :rtype: [dict]
9.668867
8.758258
1.103972
self._log('get user trades') res = self._rest_client.post( endpoint='/user_transactions', payload={ 'book': self.name, 'limit': limit, 'offset': offset, 'sort': sort } ) # TODO Wo...
def get_user_trades(self, limit=0, offset=0, sort='desc')
Return user's trade history. :param limit: Maximum number of trades to return. If set to 0 or lower, all trades are returned (default: 0). :type limit: int :param offset: Number of trades to skip. :type offset: int :param sort: Method used to sort the results by date...
5.838909
6.252786
0.933809
amount = str(amount) self._log("buy {} {} at market price".format(amount, self.major)) return self._rest_client.post( endpoint='/buy', payload={'book': self.name, 'amount': amount} )
def buy_market_order(self, amount)
Place a buy order at market price. :param amount: Amount of major currency to buy at market price. :type amount: int | float | str | unicode | decimal.Decimal :return: Order details. :rtype: dict
6.92204
7.223308
0.958292
amount = str(amount) price = str(price) self._log("buy {} {} at limit price of {} {}".format( amount, self.major, price, self.minor )) return self._rest_client.post( endpoint='/buy', payload={'book': self.name, 'amount': amount, 'price...
def buy_limit_order(self, amount, price)
Place a buy order at the given limit price. :param amount: Amount of major currency to buy at limit price. :type amount: int | float | str | unicode | decimal.Decimal :param price: Limit price. :type price: int | float | str | unicode | decimal.Decimal :return: Order details. ...
4.698486
4.818594
0.975074
#prepare the URL to send the request to url = data['host'] + data['path'] #fixed header content headers = self._DEFAULT_HEADER if self._sessionid: headers['Cookie'] = "skySSEIONID=" + self._sessionid #prepare the payload and add the length to the he...
def request(self, data, request_type: RequestTypes)
internal request method :param session: session object from the Requests package :param data: internal data of your API call :param request: the type of request, based on the RequestType enum :returns: dict with sessionid for a login and the dict of the things for the other cal...
5.25135
4.909852
1.069554
self._user = username self._pass = password return self._login()
def login(self, username, password)
Login method using username and password :param username: the username of your Brunt account :param password: the password of your Brunt account :return: True if successfull :raises: errors from Requests call
5.796177
7.022914
0.825324
# if the user has not logged in in 24 hours, relogin if not self._http._has_session() or datetime.utcnow() >= self._lastlogin + timedelta(hours=24): return self._login() else: return {}
def _is_logged_in(self)
Check whether or not the user is logged in.
7.102682
6.460625
1.09938
login_return = self._is_logged_in() # raise NameError("Please login first using the login function, with username and password") data = { "path": "/thing", "host": "https://sky.brunt.co" } resp = self._http.request(data, RequestTypes.GET) ...
def getThings(self)
Get the things registered in your account :return: dict with things registered in the logged in account and API call status
10.330151
9.873927
1.046205
login_return = self._is_logged_in() if "thingUri" in kwargs: thingUri = kwargs['thingUri'] elif "thing" in kwargs: thing = kwargs['thing'] for t in self._getThings(): if 'NAME' in t: if t['NAME'] == thing and 'thin...
def getState(self, **kwargs)
Get the state of a thing :param thing: a string with the name of the thing, which is then checked using getThings. :param thingUri: Uri (string) of the thing you are getting the state from, not checked against getThings. :return: a dict with the state of the Thing. :raises: ValueError i...
5.568379
4.855126
1.146907
login_return = self._is_logged_in() #check the thing being changed if "thingUri" in kwargs: thingUri = kwargs['thingUri'] elif "thing" in kwargs: thing = kwargs['thing'] for t in self._getThings(): if 'NAME' in t: ...
def changeKey(self, **kwargs)
Change a variable of the thing. Mostly included for future additions. :param key: The value you want to change :param value: The new value :param thing: a string with the name of the thing, which is then checked using getThings. :param thingUri: Uri (string) of the thing you are gettin...
4.292888
3.714296
1.155774
kwargs['key']="requestPosition" kwargs['value']=request_position return self.changeKey(**kwargs)
def changeRequestPosition(self, request_position, **kwargs)
Change the position of the thing. :param request_position: The new position for the slide (0-100) :param thing: a string with the name of the thing, which is then checked using getThings. :param thingUri: Uri (string) of the thing you are getting the state from, not checked against getThings. ...
6.832719
14.803852
0.46155
try: return hv.NdLayout(dataset, kdims=kdims).cols(cols) except Exception as e: self.err(e, self.layout_, "Can not create layout")
def ndlayout_(self, dataset, kdims, cols=3)
Create a Holoview NdLayout from a dictionnary of chart objects
5.691243
5.184731
1.097693
try: return hv.Layout(chart_objs).cols(cols) except Exception as e: self.err(e, self.layout_, "Can not build layout")
def layout_(self, chart_objs, cols=3)
Returns a Holoview Layout from chart objects
6.644267
4.888692
1.359109
c = hv.HLine(self.df[col].mean()) return c
def _hline_bokeh_(self, col)
Returns an horizontal line from a column mean value
12.226857
7.46246
1.638449
try: ds2 = self.clone_() window = np.ones(int(window_size)) / float(window_size) ds2.df[y_label] = np.convolve(self.df[self.y], window, 'same') ds2.chart(self.x, y_label) return ds2.line_() except Exception as e: self.err(e...
def _sline_bokeh(self, window_size, y_label)
Returns a chart with a smooth line from a serie
4.709803
4.229574
1.113541
try: ds2 = self._duplicate_() ds2.timestamps(ds2.x) ds2.lreg("Timestamps", ds2.y) ds2.drop(ds2.y) ds2.df = ds2.df.rename(columns={'Regression': ds2.y}) if "date_format" in self.chart_style: ds2.date("Date", format=s...
def _lreg_bokeh(self, **kwargs)
Returns a Bokeh linear regression line
6.513882
6.284841
1.036443
try: ds2 = self._duplicate_() qi = ds2.df[ds2.y].quantile(inf) qs = ds2.df[ds2.y].quantile(sup) ds2.add("sup", qs) ds2.add("inf", qi) ds2.chart(ds2.x, ds2.y) if chart_type == "point": c = ds2.point_(opts...
def _bokeh_quants(self, inf, sup, chart_type, color)
Draw a chart to visualize quantiles
2.88715
2.882313
1.001678
if isinstance(x_field, list): kdims = x_field else: kdims = [x_field] if isinstance(y_field, list): vdims = y_field else: vdims = [y_field] args = kwargs args["data"] = self.df args["kdims"] = kdims ...
def _get_bokeh_chart(self, x_field, y_field, chart_type, label, opts, style, options={}, **kwargs)
Get a Bokeh chart object
2.397054
2.408206
0.995369
global bokeh_renderer try: renderer = bokeh_renderer p = renderer.get_plot(chart_obj).state script, div = components(p) return script + "\n" + div except Exception as e: self.err(e, self._get_bokeh_html, "...
def _get_bokeh_html(self, chart_obj)
Get the html for a Bokeh chart
5.011273
4.576947
1.094894
# Handle all the various initialization types and get an IO object gct_io = _obtain_io(gct_obj) # Load the GCT file into a DataFrame df = pd.read_csv(gct_io, sep='\t', header=2, index_col=[0, 1], skip_blank_lines=True) # Apply backwards compatible methods _apply_backwards_compatibility(df...
def GCT(gct_obj)
Create a Dataframe with the contents of the GCT file
5.571262
5.27773
1.055617
# Handle all the various initialization types and get an IO object odf_io = _obtain_io(odf_obj) # Read the file as an array of lines raw_lines = odf_io.readlines() # Convert byte strings to unicode strings raw_lines = _bytes_to_str(raw_lines) try: # Read the header count ...
def ODF(odf_obj)
Create a Dataframe with the contents of the ODF file For more information on the ODF format see: http://software.broadinstitute.org/cancer/software/genepattern/file-formats-guide :odf_obj: The ODF file. Accepts a file-like object, a file path, a URL to the file or a string containing the raw...
3.843277
3.790345
1.013965
if headers is None and hasattr(df, 'headers'): headers = df.headers else: raise AttributeError('ODF headers not provided') with open(file_path, 'w') as file: file.write(_header_dict_to_str(headers)) df.to_csv(file, sep='\t', header=False, index=False, mode='w+')
def write_odf(df, file_path, headers=None)
Writes the provided DataFrame to a ODF file. Assumes that the DataFrame matches the structure of those produced by the ODF() function in this library :param df: the DataFrame to write to ODF :param file_path: path to which to write the ODF file :param headers: A dict of ODF headers, if none are pr...
3.391473
3.643495
0.93083
with open(file_path, 'w') as file: file.write('#1.2\n' + str(len(df.index)) + '\t' + str(len(df.columns)) + '\n') df.to_csv(file, sep='\t', mode='w+')
def write_gct(df, file_path)
Writes the provided DataFrame to a GCT file. Assumes that the DataFrame matches the structure of those produced by the GCT() function in this library :param df: :param file_path: :return:
2.401432
2.773914
0.865719
regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional po...
def _is_url(url)
Used to determine if a given string represents a URL
1.18939
1.165139
1.020814
df.row_count = types.MethodType(lambda self: len(self.index), df) df.col_count = types.MethodType(lambda self: len(self.columns), df) df.dataframe = df
def _apply_backwards_compatibility(df)
Attach properties to the Dataframe to make it backwards compatible with older versions of this library :param df: The dataframe to be modified
3.683202
3.440088
1.070671
df.headers = headers df.model = model
def _apply_odf_properties(df, headers, model)
Attach properties to the Dataframe to carry along ODF metadata :param df: The dataframe to be modified :param headers: The ODF header lines :param model: The ODF model type
7.906833
9.168157
0.862423
if len(lines) >= 1 and hasattr(lines[0], 'decode'): return [line.decode('utf-8') for line in lines] else: return lines
def _bytes_to_str(lines)
Convert all lines from byte string to unicode string, if necessary
2.836837
2.433566
1.165712
# Skip blank lines, returning None if not line: return None # Attempt to split by equals sign halves = line.split('=') if len(halves) > 1: key = halves[0].strip() value = halves[1].strip() return {key: value} # Otherwise, attempt to split by colon else...
def _extract_header_value(line)
Extracts a key / value pair from a header line in an ODF file
2.584375
2.575763
1.003343
pair = _extract_header_value(lines[1]) value_list = list(pair.values()) return int(value_list[0])
def _extract_header_number(lines)
Extracts the number of header lines from the second line of the ODF file
5.403394
4.55249
1.18691
header_count = _extract_header_number(lines) header_dict = {} for i in range(2, header_count + 2): pair = _extract_header_value(lines[i]) if not pair: # Ignore empty strings continue header_dict.update(pair) return header_dict
def _parse_header(lines)
Parse the ODF header and return a dict of all key / value pairs
3.741991
3.387313
1.104708
blanks = 0 for i in range(2, count + 2): pair = _extract_header_value(lines[i]) if not pair: blanks += 1 return blanks
def count_header_blanks(lines, count)
Count the number of blank lines in the header
3.945265
4.113047
0.959208
lines = list(map(str.strip, lines)) blank_lines = count_header_blanks(lines, skip) body = lines[skip + blank_lines + 2:] return '\n'.join(body)
def _join_data_lines(lines, skip)
Join all the data lines into a byte string
4.522451
4.333043
1.043713
df = self.df[self.df[column].str.contains(value) == True] if df is None: self.err("Can not select contained data") return self.df = df
def contains(self, column, value)
Set the main dataframe instance to rows that contains a string value in a column
6.125074
5.456439
1.122541
df = self.df[self.df[column].str.contains(value) == False] if df is None: self.err("Can not select contained data") return self.df = df
def ncontains(self, column, value)
Set the main dataframe instance to rows that do not contains a string value in a column
6.068151
5.536458
1.096035
df = self._exact(column, *values) if df is None: self.err("Can not select exact data") self.df = df
def exact(self, column, *values)
Sets the main dataframe to rows that has the exact string value in a column
7.098307
8.399724
0.845064
df = self._exact(column, *values) if df is None: self.err("Can not select exact data") return self._duplicate_(df)
def exact_(self, column, *values)
Returns a Dataswim instance with rows that has the exact string value in a column
8.836998
11.948026
0.73962
self.write(s, level=level, color='white')
def debug(self, s, level=2)
Write a debug message.
7.954269
6.714569
1.184629
self.error(s) type, value, tb = sys.exc_info() self.writelines(traceback.format_stack(), 1) self.writelines(traceback.format_tb(tb)[1:], 1) self.writelines(traceback.format_exception_only(type, value), 1)
def exception(self, s)
Write error message with traceback info.
2.631791
2.523852
1.042767
if level > self.level: return if self.timestamps: timestamp = time.strftime(u'%H:%M:%S ') else: timestamp = u'' with lock: if self.context: self.stream.write(u'%s%s> ' % (timestamp, self.context)) elif s...
def write(self, s, level=0, color=None)
Write message with indentation, context and optional timestamp.
2.750867
2.545208
1.080802
for line in lines: for line in line.rstrip(u'\n').split(u'\n'): self.write(line.rstrip(u'\n'), level=level)
def writelines(self, lines, level=0)
Write multiple messages.
3.360142
3.217341
1.044385
lang_to_form = dict([(form.form.initial['language_id'], form) for form in inline_admin_form]) return [lang_to_form[language_code] for language_code in get_language_code_list()]
def reorder_translation_formset_by_language_code(inline_admin_form)
Shuffle the forms in the formset of multilingual model in the order of their language_ids.
3.808134
3.772244
1.009514
parser.name('tinman') parser.description(__desc__) p = parser.get() p.add_argument('-p', '--path', action='store', dest='path', help='Path to prepend to the Python system path') helper.start(Controller)
def main()
Invoked by the script installed by setuptools.
12.661872
12.117733
1.044904
if self.args.foreground: self.config.application[config.DEBUG] = True
def enable_debug(self)
If the cli arg for foreground is set, set the configuration option for debug.
21.950327
9.398885
2.335418
if self.args.path: sys.path.insert(0, self.args.path) if hasattr(self.config.application, config.PATHS): if hasattr(self.config.application.paths, config.BASE): sys.path.insert(0, self.config.application.paths.base)
def insert_paths(self)
Inserts a base path into the sys.path list if one is specified in the configuration.
3.624862
2.848027
1.272763
children = len(self.living_children) LOGGER.debug('%i active child%s', children, '' if children == 1 else 'ren')
def process(self)
Check up on child processes and make sure everything is running as it should be.
13.857431
9.35775
1.480851
return (self.config.get(config.HTTP_SERVER, dict()).get(config.PORTS) or self.DEFAULT_PORTS)
def ports_to_spawn(self)
Return the list of ports to spawn :rtype: list
11.137795
11.145864
0.999276
if config.PATHS not in self.config.application: self.config.application[config.PATHS] = dict() if config.BASE not in self.config.application[config.PATHS]: self.config.application[config.PATHS][config.BASE] = value
def set_base_path(self, value)
Munge in the base path into the configuration values :param str value: The path value
3.045991
3.457584
0.880959
LOGGER.info('Tinman v%s starting up with Tornado v%s', __version__, tornado_version) # Setup debugging and paths self.enable_debug() self.set_base_path(os.getcwd()) self.insert_paths() # Setup child processes self.children = list() ...
def setup(self)
Additional setup steps.
4.837609
4.686852
1.032166
self.signal_children(signal.SIGABRT) # Wait a few iterations when trying to stop children before terminating waiting = 0 while self.living_children: time.sleep(0.5) waiting += 1 if waiting == self.MAX_SHUTDOWN_WAIT: self.signa...
def shutdown(self)
Send SIGABRT to child processes to instruct them to stop
5.84655
4.582111
1.275951
LOGGER.info('Sending signal %i to children', signum) for child in self.living_children: if child.pid != os.getpid(): os.kill(child.pid, signum)
def signal_children(self, signum)
Send a signal to all children :param int signum: The signal to send
3.99158
4.279332
0.932758
return process.Process(name="ServerProcess.%i" % port, kwargs={'namespace': self.namespace, 'port': port})
def spawn_process(self, port)
Create an Application and HTTPServer for the given port. :param int port: The port to listen on :rtype: multiprocessing.Process
11.591575
11.865293
0.976931
for port in self.ports_to_spawn: process = self.spawn_process(port) process.start() self.children.append(process)
def spawn_processes(self)
Spawn of the appropriate number of application processes
4.104225
3.811088
1.076917
camel = "".join(word.title() for word in value.split("_")) return value[:1].lower() + camel[1:]
def snake_to_camel(value)
Converts a snake_case_string to a camelCaseString. >>> snake_to_camel("foo_bar_baz") 'fooBarBaz'
3.529426
5.476592
0.644457
try: self._check_db() except Exception as e: self.err(e, "Can not connect to database") return if table not in self.db.tables: self.warning("The table " + table + " does not exists") return try: res = self.d...
def getall(self, table)
Get all rows values for a table
3.293222
3.293422
0.999939
try: vals = [] i = 0 for _, row in self.df.iterrows(): current = row[diffcol] try: nextv = self.df[diffcol].iloc[i + 1] except Exception: vals.append(nan) cont...
def diffn(self, diffcol: str, name: str="Diff")
Add a diff column to the main dataframe: calculate the diff from the next value :param diffcol: column to diff from :type diffcol: str :param name: diff column name, defaults to "Diff" :type name: str, optional :example: ``ds.diffn("Col 1", "New col")``
4.137324
3.908086
1.058657
try: df = self.df.copy() previous = 0 i = 0 vals = [df[diffcol].iloc[0]] for _, row in df.iterrows(): val = row[diffcol] - previous new = round(val, 1) previous = row[diffcol] if ...
def diffp(self, diffcol: str, name: str="Diff")
Add a diff column to the main dataframe: calculate the diff from the previous value :param diffcol: column to diff from :type diffcol: str :param name: diff column name, defaults to "Diff" :type name: str, optional :example: ``ds.diffp("Col 1", "New col")``
4.025417
4.205356
0.957212
try: df = self.df.copy() mean = self.df[diffcol].mean() vals = [] for _, row in self.df.iterrows(): num = row[diffcol] if num > 0: diff = int(((num - mean) * 100) / mean) vals.append(...
def diffm(self, diffcol: str, name: str="Diff", default=nan)
Add a diff column to the main dataframe: calculate the diff from the column mean :param diffcol: column to diff from :type diffcol: str :param name: diff column name, defaults to "Diff" :param name: str, optional :param default: column default value, defaults to nan ...
3.874897
3.93631
0.984398
try: d = [] for i, row in self.df.iterrows(): v = (row[col]*100) / serie[i] d.append(v) self.df[name] = d except Exception as e: self.err(e, self._append, "Can not diff column from serie")
def diffsp(self, col: str, serie: "iterable", name: str="Diff")
Add a diff column in percentage from a serie. The serie is an iterable of the same length than the dataframe :param col: column to diff :type col: str :param serie: serie to diff from :type serie: iterable :param name: name of the diff col, defaults to "Diff" :p...
4.857724
4.067136
1.194385
try: df = self.df.copy() df = df.groupby([col]).mean() if index_col is True: df[col] = df.index.values return self._duplicate_(df) except Exception as e: self.err(e, self.gmean_, "Can not meansum column")
def gmean_(self, col: str, index_col: bool=True) -> "Ds"
Group by and mean column :param col: column to group :type col: str :param index_col: :type index_col: bool :return: a dataswim instance :rtype: Ds :example: ``ds2 = ds.gmean("Col 1")``
5.62719
6.51361
0.863913
try: df = self.df.copy() df = df.groupby([col]).sum() if index_col is True: df[col] = df.index.values return self._duplicate_(df) except Exception as e: self.err(e, self.gsum_, "Can not groupsum column")
def gsum_(self, col: str, index_col: bool=True) -> "Ds"
Group by and sum column :param col: column to group :type col: str :param index_col: :type index_col: bool :return: a dataswim instance :rtype: Ds :example: ``ds2 = ds.gsum("Col 1")``
4.688273
5.596938
0.83765