code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
cb.clear()
model = gtk.ListStore(str)
for i in items:
model.append([i])
cb.set_model(model)
if type(cb) == gtk.ComboBoxEntry:
cb.set_text_column(0)
elif type(cb) == gtk.ComboBox:
cell = gtk.CellRendererText()
cb.pack_start(cell, True)
cb.add_attribute... | def combobox_set_model_from_list(cb, items) | Setup a ComboBox or ComboBoxEntry based on a list of strings. | 2.021684 | 1.774174 | 1.139507 |
name = "seq"
if isinstance(subcons[0], six.string_types):
name = subcons[0]
subcons = subcons[1:]
return IndexingAdapter(Sequence(name, *subcons), -1) | def LastOf(*subcons) | Create an adapter which uses only the last construct.
If first argument is a string it will be the name. | 4.172264 | 4.062524 | 1.027013 |
# pylint: disable=protected-access
tool_key = devpipeline_core.toolsupport.choose_tool_key(
current_target, devpipeline_scm._SCM_TOOL_KEYS
)
return devpipeline_core.toolsupport.tool_builder(
current_target.config, tool_key, devpipeline_scm.SCMS, current_target
) | def _make_scm(current_target) | Create an Scm for a component.
Arguments
component - The component being operated on. | 6.523608 | 7.676482 | 0.849817 |
try:
scm = _make_scm(current_target)
src_dir = current_target.config.get("dp.src_dir")
shared_dir = current_target.config.get("dp.src_dir_shared")
scm.checkout(repo_dir=src_dir, shared_dir=shared_dir)
scm.update(repo_dir=src_dir)
except devpipeline_core.toolsupport.M... | def checkout_task(current_target) | Update or a local checkout.
Arguments
target - The target to operate on. | 5.159672 | 5.450191 | 0.946696 |
# Try to interpret any JSON
try:
resp.obj = json.loads(resp.body)
self._debug(" Received entity: %r", resp.obj)
except ValueError:
resp.obj = None
self._debug(" No received entity; body %r", resp.body)
# Now, call superclass me... | def proc_response(self, resp) | Process JSON data found in the response. | 5.686725 | 5.81921 | 0.977233 |
# Attach the object to the request
json.dump(obj, req)
# Also set the content-type header
req['content-type'] = self._content_type | def _attach_obj(self, req, obj) | Helper method to attach obj to req as JSON data. | 6.142427 | 5.311673 | 1.156402 |
if module_path.find('.egg') == -1:
return None
_module_absolute_path = os.path.abspath(module_path)
egg_paths = [os.path.relpath(_module_absolute_path, egg_path)
for egg_path in [egg_path for egg_path in sys.path
if REGEX_EGG_PACKAGE_PATH.match(egg_path) \
a... | def find_module_egg_path(module_path) | Find the path of the deployed egg package that may contain the
specified module path.
@param module_path: the path of a Python module.
@return: the absolute path of the deployed egg package that contains
the specified module path, or ``None`` if no deployed egg
package contains this modu... | 2.870704 | 2.928588 | 0.980235 |
try:
f = open(settings.DJANGOSPAM_LOG, "a")
f.write("%s: %s method %s page %s user agent %s\n" % \
(datetime.datetime.now(), ltype, method, page, user_agent))
f.close()
except:
if settings.DJANGOSPAM_FAIL_ON_LOG:
exc_type, exc_value = sys.exc_inf... | def log(ltype, method, page, user_agent) | Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>" | 2.711229 | 2.451492 | 1.105951 |
out = {}
for key in self._func_names:
out[key[len(self._prefix):]] = getattr(self, key)
return out | def functions(self) | Returns a dictionary containing the functions defined in this
object. The keys are function names (as exposed in templates)
and the values are Python functions. | 4.37147 | 3.922196 | 1.114546 |
text = self.tmpl_asciify(text)
text = re.sub(r'[^a-zA-Z]+', ' ', text)
return re.sub(r'\s+', ' ', text) | def tmpl_alpha(self, text) | * synopsis: ``%alpha{text}``
* description: This function first ASCIIfies the given text, then all \
non alphabet characters are replaced with whitespaces. | 3.299846 | 3.095006 | 1.066184 |
text = self.tmpl_asciify(text)
text = re.sub(r'[^a-zA-Z0-9]+', ' ', text)
return re.sub(r'\s+', ' ', text) | def tmpl_alphanum(self, text) | * synopsis: ``%alphanum{text}``
* description: This function first ASCIIfies the given text, then all \
non alpanumeric characters are replaced with whitespaces. | 2.861231 | 2.890858 | 0.989752 |
ger_umlaute = {'ae': u'ä',
'oe': u'ö',
'ue': u'ü',
'Ae': u'Ä',
'Oe': u'Ö',
'Ue': u'Ü'}
for replace, search in ger_umlaute.items():
text = text.replace(search, replace)
... | def tmpl_asciify(text) | * synopsis: ``%asciify{text}``
* description: Translate non-ASCII characters to their ASCII \
equivalents. For example, “café” becomes “cafe”. Uses the mapping \
provided by the unidecode module. | 3.232423 | 3.750786 | 0.861799 |
for char in chars:
text = text.replace(char, '')
return text | def tmpl_delchars(text, chars) | * synopsis: ``%delchars{text,chars}``
* description: Delete every single character of “chars“ in “text”. | 2.801434 | 3.763052 | 0.744458 |
import re
return re.sub(r'([' + chars + r'])\1*', r'\1', text) | def tmpl_deldupchars(text, chars=r'-_\.') | * synopsis: ``%deldupchars{text,chars}``
* description: Search for duplicate characters and replace with only \
one occurrance of this characters. | 5.293545 | 4.625577 | 1.144407 |
skip = int(skip)
count = skip + int(count)
return join_str.join(text.split(sep)[skip:count]) | def tmpl_first(text, count=1, skip=0, sep=u'; ', join_str=u'; ') | * synopsis: ``%first{text}`` or ``%first{text,count,skip}`` or \
``%first{text,count,skip,sep,join}``
* description: Returns the first item, separated by ; . You can use \
%first{text,count,skip}, where count is the number of items \
(default 1) and skip is number to skip (de... | 3.417419 | 4.630086 | 0.73809 |
try:
int_condition = _int_arg(condition)
except ValueError:
if condition.lower() == "false":
return falseval
else:
condition = int_condition
if condition:
return trueval
else:
return falseval | def tmpl_if(condition, trueval, falseval=u'') | If ``condition`` is nonempty and nonzero, emit ``trueval``;
otherwise, emit ``falseval`` (if provided).
* synopsis: ``%if{condition,truetext}`` or \
``%if{condition,truetext,falsetext}``
* description: If condition is nonempty (or nonzero, if it’s a \
number), then retur... | 3.634737 | 3.929013 | 0.925102 |
if field in self.values:
return trueval
else:
return falseval | def tmpl_ifdef(self, field, trueval=u'', falseval=u'') | If field exists return trueval or the field (default) otherwise,
emit return falseval (if provided).
* synopsis: ``%ifdef{field}``, ``%ifdef{field,text}`` or \
``%ifdef{field,text,falsetext}``
* description: If field exists, then return truetext or field \
(default). Oth... | 4.162552 | 6.61362 | 0.629391 |
if field not in self.values or \
(field in self.values and not self.values[field]) or \
re.search(r'^\s*$', self.values[field]):
return falseval
else:
return trueval | def tmpl_ifdefnotempty(self, field, trueval=u'', falseval=u'') | If field is not emtpy return trueval or the field (default)
otherwise, emit return falseval (if provided).
* synopsis: ``%ifdefnotempty{field,text}`` or \
``%ifdefnotempty{field,text,falsetext}``
* description: If field is not empty, then return truetext. \
Otherwise, re... | 2.961709 | 3.759191 | 0.787858 |
for char in chars:
text = text.replace(char, replace)
return text | def tmpl_replchars(text, replace, chars) | * synopsis: ``%replchars{text,chars,replace}``
* description: Replace the characters “chars” in “text” with \
“replace”.
* example: ``%replchars{text,ex,-}`` > ``t--t`` | 2.669271 | 4.027231 | 0.662805 |
max_size = int(max_size)
if len(text) <= max_size:
return text
text = textwrap.wrap(text, max_size)[0]
import re
text = re.sub(r'\W+$', '', text)
return text.strip() | def tmpl_shorten(text, max_size=32) | Shorten the given text to ``max_size``
* synopsis: ``%shorten{text}`` or ``%shorten{text,max_size}``
* example: ``%shorten{$title,32}``
* description: Shorten “text” on word boundarys. | 2.876443 | 3.660816 | 0.785738 |
return time.strftime(fmt, time.strptime(text, cur_fmt)) | def tmpl_time(text, fmt, cur_fmt) | Format a time value using `strftime`.
* synopsis: ``%time{date_time,format,curformat}``
* description: Return the date and time in any format accepted by \
strftime. For example, to get the year some music was added to \
your library, use %time{$added,%Y}. | 3.330582 | 7.310021 | 0.455619 |
'''
Copy selected notebook template to notebook directory.
## Notes ##
- An exception is raised if the parent of the selected file is the
notebook directory.
- If notebook with same name already exists in notebook directory,
offer is made to overwrite (t... | def on_new(self, button) | Copy selected notebook template to notebook directory.
## Notes ##
- An exception is raised if the parent of the selected file is the
notebook directory.
- If notebook with same name already exists in notebook directory,
offer is made to overwrite (the new copy of the f... | 3.440563 | 2.175483 | 1.581517 |
# bhfield
# make sure the binary is available on the system
paths = _bhfield.fetch.get_binaries()
if package_dir:
# Copy the binaries to the `resources` directory
# of qpsphere.
pdir = RESCR_PATH
outpaths = []
for pp in paths:
target = pdir / pp.... | def download_binaries(package_dir=False) | Download all binaries for the current platform
Parameters
----------
package_dir: bool
If set to `True`, the binaries will be downloaded to the
`resources` directory of the qpsphere package instead of
to the users application data directory. Note that this
might require admi... | 8.094931 | 6.420664 | 1.260762 |
paths = []
if package_dir:
pdir = RESCR_PATH
else:
pdir = CACHE_PATH
for pp in pdir.iterdir():
if pp.name != "shipped_resources_go_here":
paths.append(pp)
for pp in paths:
pp.unlink() | def remove_binaries(package_dir=False) | Remove all binaries for the current platform
Parameters
----------
package_dir: bool
If True, remove all binaries from the `resources`
directory of the qpsphere package. If False,
remove all binaries from the user's cache directory. | 7.248223 | 7.918254 | 0.915381 |
@functools.wraps(func)
def wrapper(*args, **kw):
start = time.time()
print('Running `%s()` ...' % func.__name__)
res = func(*args, **kw)
end = time.time()
print('Function `%s()` running elapsed %.2f s' %
(func.__name__, end - start))
return res... | def elapsed(func) | A decorator for calculating time elapsed when execute function | 2.677697 | 2.504548 | 1.069134 |
import logging
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# set format
formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# file handler
fh = logging.FileHandler(log_... | def create_logger(log_file, name='logger', cmd=True) | define a logger for your program
parameters
------------
log_file file name of log
name name of logger
example
------------
logger = create_logger('example.log',name='logger',)
logger.info('This is an example!')
logger.warning('This is a warn!') | 1.48938 | 1.620238 | 0.919236 |
vector1 = np.mat(vector1)
vector2 = np.mat(vector2)
return np.sqrt((vector1 - vector2) * (vector1 - vector2).T).item() | def euclidean_distant(vector1, vector2) | 欧式距离 | 2.552085 | 2.190941 | 1.164835 |
vector1 = np.mat(vector1)
vector2 = np.mat(vector2)
return np.sum(np.abs(vector1 - vector2)) | def manhattan_distant(vector1, vector2) | 曼哈顿距离 | 2.140158 | 1.866038 | 1.146899 |
vector1 = np.mat(vector1)
vector2 = np.mat(vector2)
vector1_norm = np.linalg.norm(vector1)
vector2_norm = np.linalg.norm(vector2)
dot_norm = vector1_norm * vector2_norm
dot_vs = np.dot(vector1, vector2)
return np.divide(dot_vs, dot_norm).item() | def cosine_distant(vector1, vector2) | 余弦距离 | 2.211557 | 2.121326 | 1.042535 |
if len(vector1) < 3:
return 1.0
return 0.5 + 0.5 * np.corrcoef(vector1, vector2, rowvar=0)[0][1] | def pearson_similar(vector1, vector2) | 皮尔逊相关系数 | 2.973352 | 2.902948 | 1.024253 |
kwargs = _normalize(**kwargs)
cor = _Chain()
cor.add(_LessThan1M(l10n, **kwargs))
cor.add(_LessThan1H(l10n, **kwargs))
cor.add(_LessThan23H(l10n, **kwargs))
cor.add(_LessThan6D1H(l10n, **kwargs))
cor.add(_LessThan25D10H(l10n, **kwargs))
cor.add(_LessThan11MM(l10n, **kwargs))
co... | def relative_time_to_text(l10n=locales.get(_default), **kwargs) | Return an aproximate textual representation of the provioded duration of
time.
Examples:
relative_time_to_text(hours=6, minutes=34) -> "six and a half hours"
relative_time_to_text(years=5, months=8, days=5) -> "less than six years"
Keyword arguments:
l10n -- The locale of the language for the ... | 2.837823 | 3.193127 | 0.888729 |
if not self._size:
self._size = os.path.getsize(self._path)
return self._size | def size(self) | size in bytes | 3.376212 | 2.792583 | 1.208992 |
cipher_key = self.gen_key(32)
in_file_path = block.latest_file_info.path
dst_file_path = block.processed_data_file_info.path + self.get_extension()
self.log.debug("Encrypting file '%s' with key '%s' to file '%s'",
in_file_path, cipher_key, dst_file_path)
... | def do_heavy_work(self, block) | Expects Compressor Block like objects | 3.034846 | 2.978592 | 1.018886 |
if not out_filename:
out_filename = in_filename + '.enc'
iv = ''.join(chr(random.randint(0, 0xFF)) for _ in range(16))
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
wit... | def encrypt_file(cls, key, in_filename, out_filename=None, chunksize=64 * 1024) | Encrypts a file using AES (CBC mode) with the
given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
in_filename:
Name of the input file
... | 1.303424 | 1.371049 | 0.950676 |
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
... | def decrypt_file(cls, key, in_filename, out_filename=None, chunksize=24 * 1024) | Decrypts a file using AES (CBC mode) with the
given key. Parameters are similar to encrypt_file,
with one difference: out_filename, if not supplied
will be in_filename without its last extension
(i.e. if in_filename is 'aaa.zip.enc' then
out_filename will be '... | 1.468358 | 1.462987 | 1.003671 |
print(yellow("# Setting up environment...\n", True))
virtualenv.init()
virtualenv.update_requirements()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your virtual environment.")) | def init() | Execute init tasks for all components (virtualenv, pip). | 10.021424 | 8.583191 | 1.167564 |
"A decorator to commit to the storage if autocommit is set to True."
@wraps(f)
def wrapper(self, *args, **kwargs):
result = f(self, *args, **kwargs)
if self._meta.commit_ready():
self.commit()
return result
return wrapper | def autocommit(f) | A decorator to commit to the storage if autocommit is set to True. | 4.461594 | 3.011683 | 1.481429 |
return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k]) | def intersect(d1, d2) | Intersect dictionaries d1 and d2 by key *and* value. | 2.364207 | 2.067292 | 1.143625 |
"Set value to the key store."
# if key already in data, update indexes
if not isinstance(value, dict):
raise BadValueError(
'The value {} is incorrect.'
' Values should be strings'.format(value))
_value = deepcopy(value)
if key in self.... | def set(self, key, value) | Set value to the key store. | 6.548314 | 5.905797 | 1.108794 |
"Insert value in the keystore. Return the UUID key."
key = str(uuid4())
self.set(key, value)
return key | def insert(self, value) | Insert value in the keystore. Return the UUID key. | 11.343208 | 4.259105 | 2.663285 |
"Delete a `key` from the keystore."
if key in self.data:
self.delete_from_index(key)
del self.data[key] | def delete(self, key) | Delete a `key` from the keystore. | 6.655725 | 5.107335 | 1.30317 |
if not isinstance(value, dict):
raise BadValueError(
'The value {} is incorrect.'
' Values should be strings'.format(value))
if key in self.data:
v = self.get(key)
v.update(value)
else:
v = value
sel... | def update(self, key, value) | Update a `key` in the keystore.
If the key is non-existent, it's being created | 4.289016 | 4.43708 | 0.96663 |
"Delete the `key_to_delete` for the record found with `key`."
v = self.get(key)
if key_to_delete in v:
del v[key_to_delete]
self.set(key, v) | def del_key(self, key, key_to_delete) | Delete the `key_to_delete` for the record found with `key`. | 3.841933 | 2.761115 | 1.391442 |
"Commit data to the storage."
if self._meta.path:
with open(self._meta.path, 'wb') as fd:
raw = deepcopy(self.raw)
# LAZY INDEX PROCESSING
# Save indexes only if not lazy
lazy_indexes = self.lazy_indexes # Keep this list safe
... | def commit(self) | Commit data to the storage. | 4.179296 | 4.138167 | 1.009939 |
"Return the items in the keystore with keys in `keys`."
return dict((k, v) for k, v in self.data.items() if k in keys) | def keys_to_values(self, keys) | Return the items in the keystore with keys in `keys`. | 7.235117 | 3.918609 | 1.846348 |
"Return a set of keys filtered according to the given arguments."
self._used_index = False
keys = set(self.data.keys())
for key_filter, v_filter in kwargs.items():
if key_filter in self.indexes:
self._used_index = True
if v_filter not in self.i... | def filter_keys(self, **kwargs) | Return a set of keys filtered according to the given arguments. | 3.400241 | 2.971998 | 1.144093 |
"Search keys whose values match with the searched values"
searched = {key: value}
return set([k for k, v in self.data.items() if
intersect(searched, v) == searched]) | def simple_filter(self, key, value) | Search keys whose values match with the searched values | 11.267102 | 6.187457 | 1.820959 |
keys = self.filter_keys(**kwargs)
return self.keys_to_values(keys) | def filter(self, **kwargs) | Filter data according to the given arguments. | 7.109794 | 6.591948 | 1.078557 |
"Delete references from the index of the key old value(s)."
old_value = self.data[key]
keys = set(old_value.keys()).intersection(self.indexes.keys())
for index_name in keys:
if old_value[index_name] in self.indexes[index_name]:
del self.indexes[index_name][old... | def delete_from_index(self, key) | Delete references from the index of the key old value(s). | 4.14115 | 2.672534 | 1.549522 |
"Update the index with the new key/values."
for k, v in value.items():
if k in self.indexes:
# A non-string index value switches it into a lazy one.
if not isinstance(v, six.string_types):
self.index_defs[k]['type'] = 'lazy'
... | def update_index(self, key, value) | Update the index with the new key/values. | 4.417658 | 3.927726 | 1.124737 |
if name not in self.indexes or recreate:
self.build_index(name, _type) | def create_index(self, name, recreate=False, _type='default') | Create an index.
If recreate is True, recreate even if already there. | 4.748064 | 5.414755 | 0.876875 |
"Build the index related to the `name`."
indexes = {}
has_non_string_values = False
for key, item in self.data.items():
if idx_name in item:
value = item[idx_name]
# A non-string index value switches it into a lazy one.
if not i... | def build_index(self, idx_name, _type='default') | Build the index related to the `name`. | 4.18297 | 3.742116 | 1.117809 |
"Clean index values after loading."
for idx_name, idx_def in self.index_defs.items():
if idx_def['type'] == 'lazy':
self.build_index(idx_name)
for index_name, values in self.indexes.items():
for value in values:
if not isinstance(values[val... | def _clean_index(self) | Clean index values after loading. | 4.343848 | 3.594123 | 1.208598 |
command = TaskCommand(tasks=tasks, *args, **kwargs)
return command | def make_command(tasks, *args, **kwargs) | Create a TaskCommand with defined tasks.
This is a helper function to avoid boiletplate when dealing with simple
cases (e.g., all cli arguments can be handled by TaskCommand), with no
special processing. In general, this means a command only needs to run
established tasks.
Arguments:
tasks - ... | 4.45982 | 8.337571 | 0.534906 |
if args is None:
args = sys.argv[1:]
try:
command.execute(args)
except IOError as failure:
if failure.errno == errno.EPIPE:
# This probably means we were piped into something that terminated
# (e.g., head). Might be a better way to handle this, but for ... | def execute_command(command, args) | Runs the provided command with the given args.
Exceptions, if any, are propogated to the caller.
Arguments:
command - something that extends the Command class
args - A list of command line arguments. If args is None, sys.argv
(without the first argument--assumed to be the command name) wil... | 3.854189 | 3.92517 | 0.981916 |
self.parser.add_argument(
"--version",
action="version",
version="%(prog)s {} (core {})".format(
version, devpipeline_core.version.STRING
),
) | def set_version(self, version) | Add the --version string with appropriate output.
Arguments:
version - the version of whatever provides the command | 6.766436 | 6.245686 | 1.083378 |
args = self.parser.parse_args(*args, **kwargs)
self.process(args) | def execute(self, *args, **kwargs) | Initializes and runs the tool.
This is shorhand to parse command line arguments, then calling:
self.setup(parsed_arguments)
self.process() | 4.882701 | 3.263736 | 1.496047 |
executor = _get_executor(arguments)
resolver = _get_resolver(arguments)
dep_manager = resolver(targets, full_config, self._task_order)
task_queue = dep_manager.get_queue()
config_info = devpipeline_core.configinfo.ConfigInfo(executor)
try:
failed = [... | def process_targets(self, targets, full_config, arguments) | Calls the tasks with the appropriate options for each of the targets. | 4.514913 | 4.481085 | 1.007549 |
lines = []
try:
while True:
line = input()
if line != '':
lines.append(line)
else:
break
except (EOFError, KeyboardInterrupt):
return '\n'.join(lines) | def _user_input() -> str | A helper function which waits for user multi-line input.
:return: A string input by user, separated by ``'\\n'``. | 2.813015 | 2.427397 | 1.15886 |
if not self.__infile_path:
return Path(self.__infile_path).expanduser()
return None | def infile_path(self) -> Optional[PurePath] | Read-only property.
:return: A ``pathlib.PurePath`` object or ``None``. | 6.618644 | 8.236254 | 0.803599 |
stream = self.stream # In case that ``self.stream`` is changed.
stream.seek(0)
for line in stream:
yield line | def generator(self) -> Iterator[str] | Create a generate that iterates the whole content of the file or string.
:return: An iterator iterating the lines of the text stream, separated by ``'\\n'`` or ``'\\r'``. | 6.878072 | 6.663952 | 1.032131 |
stream = self.stream # In case that ``self.stream`` is changed.
stream.seek(0)
for line in stream:
yield line, stream.tell() | def generator_telling_position(self) -> Iterator[Tuple[str, int]] | Create a generate that iterates the whole content of the file or string, and also tells which offset is now.
:return: An iterator iterating tuples, containing lines of the text stream,...
separated by ``'\\n'`` or ``'\\r'``; and the offset (in bytes) of current line. | 6.820129 | 5.836873 | 1.168456 |
stream = self.stream # In case that ``self.stream`` is changed.
stream.seek(offset, whence)
for line in stream:
yield line | def generator_starts_from(self, offset, whence: Optional[int] = 0) -> Iterator[str] | Create a generate that iterates the whole content of the file or string, starting from *offset* bytes.
:param offset: Change the stream position to the given byte *offset*....
*offset* is interpreted relative to the position indicated by *whence*. The default value for whence is ``SEEK_SET``.
... | 6.234199 | 6.709587 | 0.929148 |
s: str = self.content[begin:end + 1]
for line in s:
yield line | def generator_between(self, begin: int, end: int) -> Iterator[str] | Create a generate that iterates the whole content of the file or string, starting from *begin* index,
end by *end* index. **Not byte!**
:param begin: An integer labels the starting index.
:param end: An integer labels the ending index.
:return: An iterator of string. | 7.245975 | 9.912793 | 0.730972 |
parts = obj_name.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m | def obj_for_name(obj_name) | Instantiate class or function
:param obj_name: class or function name
:return: instance of class or function | 2.156595 | 2.432319 | 0.886641 |
# In ideal case this should be done using serializer. A temp measure right now
cerberus_type_map = {
'string': str,
'integer': int,
'float': float,
}
for field, validator in schema.items():
field_type = validator['type']
if field_type in ['integer', 'string',... | async def type_cast_payload(schema: dict, payload: dict) | Make schema little forgiving! use case: multipart data | 3.807081 | 3.585948 | 1.061666 |
regex = r'\* ' + key + ': '
if inline_code:
regex = regex + '``(.*)``'
else:
regex = regex + '(.*)'
value = re.findall(regex, string)
if value:
return value[0].replace('``', '')
else:
return False | def extract_value(self, string, key, inline_code=True) | Extract strings from the docstrings
.. code-block:: text
* synopsis: ``%shorten{text, max_size}``
* example: ``%shorten{$title, 32}``
* description: Shorten “text” on word boundarys. | 3.042893 | 3.983173 | 0.763937 |
length = len(text)
indentation = (' ' * indent)
return indentation + text + '\n' + indentation + ('-' * length) | def underline(self, text, indent=4) | Underline a given text | 4.800588 | 4.64969 | 1.032453 |
return textwrap.fill(
text,
width=width,
initial_indent=' ' * indent,
subsequent_indent=' ' * indent,
) | def format(self, text, width=78, indent=4) | Apply textwrap to a given text string | 2.23257 | 2.182404 | 1.022987 |
output = ''
for f in self.functions:
output += self.underline(f) + '\n\n'
if f in self.synopsises and isinstance(self.synopsises[f], str):
output += self.format(self.synopsises[f]) + '\n'
if f in self.descriptions and isinstance(
... | def get(self) | Retrieve a formated text string | 2.462353 | 2.367556 | 1.04004 |
m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b)
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = 1.0 / m * np.dot(X, (A - Y).T)
db = 1.0 / m * np.sum(A - Y)
assert (dw.shape == w.shape)
assert (db.dtype == float)
cost = ... | def propagate(w, b, X, Y) | Implement the cost function and its gradient for the propagation
Arguments:
w weights, a numpy array of size (dim, 1)
b bias, a scalar
X data of size (dim, number of examples)
Y true "label" vector of size (1, number of examples)
Return:
cost negative log-likelih... | 1.776742 | 2.009596 | 0.884129 |
costs = []
for i in range(num_iterations):
# Cost and gradient calculation
grads, cost = propagate(w, b, X, Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w - learning_rate * dw
b = b - learning_r... | def LR_train(w, b, X, Y, num_iterations, learning_rate, print_cost=True) | This function optimizes w and b by running a gradient descent algorithm
Arguments:
w weights, a numpy array of size (dim, 1)
b bias, a scalar
X data of shape (dim, number of examples)
Y true "label" vector, of shape (1, number of examples)
num_iterations number of i... | 1.497719 | 1.412811 | 1.060098 |
m = X.shape[1]
Y_prediction = np.zeros((1, m))
w = w.reshape(X.shape[0], 1)
A = sigmoid(np.dot(w.T, X) + b)
for i in range(A.shape[1]):
if A[0, i] > 0.5:
Y_prediction[0, i] = 1.0
else:
Y_prediction[0, i] = 0.0
assert (Y_prediction.shape == (1, m))... | def LR_predict(w, b, X) | Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -- a numpy array (vector) contai... | 1.692216 | 1.754123 | 0.964707 |
print('X_train shape:', X_train.shape)
# initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
print('w shape:', w.shape)
# Gradient descent
parameters, grads, costs = LR_train(w, b, X_train, Y_train, num_iterations,
learni... | def model(X_train, Y_train, X_test, Y_test, num_iterations=2000,
learning_rate=0.5, print_cost=True) | Builds the logistic regression model by calling the function
implemented above
Arguments:
X_train training set represented by a numpy array of shape (dim, m_train)
Y_train training labels represented by a numpy array (vector) of shape (1, m_train)
X_test test set represented by a numpy... | 1.710744 | 1.85062 | 0.924416 |
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show() | def plot_lc(d) | plot learning curve
Arguments:
d Returned by model function. Dictionary containing information about the model. | 3.579708 | 2.785114 | 1.2853 |
if isinstance(level,(int,long)):
return level
try:
return(int(logging.getLevelName(level.upper())))
except:
raise ValueError('illegal loglevel %s' % level) | def getLogLevelNo(level) | Return numerical log level or raise ValueError.
A valid level is either an integer or a string such as WARNING etc. | 3.840999 | 3.729061 | 1.030018 |
qargv = []
cmdwords = list(sys.argv)
if useBasename:
cmdwords[0] = os.path.basename(cmdwords[0])
for s in cmdwords:
# any white space or special characters in word so we need quoting?
if re.search(r'\s|\*|\?', s):
if "'" in s:
qargv.append('"%s"' ... | def cmdLine(useBasename=False) | Return full command line with any necessary quoting. | 3.314892 | 3.092068 | 1.072063 |
if isinstance(exception, CmdError) or not debugFlag:
error(str(exception))
else:
import traceback
traceback.print_exc()
error(str(exception)) # or log complete traceback as well?
if abortFlag:
sys.exit(1) | def handleError(exception, debugFlag=False, abortFlag=True) | Error handling utility. Print more or less error information
depending on debug flag. Unless abort is set False, exits with
error code 1. | 5.13454 | 5.602026 | 0.91655 |
if batch:
return
if acceptByDefault:
msg += ' - are you sure [y] ? '
else:
msg += ' - are you sure [n] ? '
while True:
reply = raw_input(msg).lower()
print
if reply == '':
reply = 'y' if acceptByDefault else 'n'
if reply == 'y':
... | def confirm(msg, acceptByDefault=False, exitCodeOnAbort=1, batch=False) | Get user confirmation or abort execution.
confirm returns True (if user confirms) or False (if user declines
and exitCodeOnAbort is None) or aborts with sys.exit(exitCodeOnAbort)
(if user declines and exitCodeOnAbort is not None).
Depending on acceptByDefault, the default answer (if user presses
R... | 3.130092 | 3.102973 | 1.00874 |
if dryrun:
debug('would run cmd: %s' % cmd)
return (0, '', None)
debug('running cmd: %s' % cmd)
outputBuffer = []
interactive = os.environ.get('PYTHONINSPECT',None)
if interactive:
del os.environ['PYTHONINSPECT']
p = subprocess.Popen(cmd,
st... | def run(cmd, printOutput=False,
exceptionOnError=False, warningOnError=True,
parseForRegEx=None, regExFlags=0,
printOutputIfParsed=False, printErrorsIfParsed=False, exceptionIfParsed=False,
dryrun=None) | Run cmd and return (status,output,parsedOutput).
Unless dryrun is set True, cmd is run using subprocess.Popen. It
returns the exit status from cmd, its output, and any output found
by searching for the regular expression parseForRegEx. cmd is
logged at the debug level.
The parameters are:
cmd... | 2.282177 | 2.251295 | 1.013717 |
self.logger.log(self.loglevel, text, extra={'terminator': None}) | def write(self, text) | Write text. An additional attribute terminator with a value of
None is added to the logging record to indicate that StreamHandler
should not add a newline. | 10.213598 | 4.907028 | 2.081423 |
try:
msg = self.format(record)
if isinstance(msg,unicode):
if hasattr(self.stream, "encoding") and self.stream.encoding:
# Stream should take care of encoding, but do it explicitly to
# prevent bug in Python 2.6 - see
... | def emit(self, record) | Emit a record. Unless record.terminator is set, a trailing
newline will be written to the output stream. | 2.854043 | 2.781443 | 1.026101 |
# See /usr/lib64/python2.7/logging/__init__.py, StreamHander.flush()
self.acquire()
try:
if self.stream and hasattr(self.stream, "flush"):
self.stream.flush()
except IOError as e:
if self.abortOnIOError:
sys.exit('IOError: ... | def flush(self) | Flush the stream.
In contrast to StreamHandler, errors are not caught so the program doesn't iterate
through tons of logging errors e.g. in case of a broken pipe. | 4.204803 | 3.613944 | 1.163494 |
if self.triggerLevelNo is not None and record.levelno>=self.triggerLevelNo:
self.triggered = True
logging.handlers.BufferingHandler.emit(self,record) | def emit(self, record) | Emit record after checking if message triggers later sending of e-mail. | 6.490941 | 4.815672 | 1.347878 |
if self.triggered and len(self.buffer) > 0:
# Do not send empty e-mails
text = []
for record in self.buffer:
terminator = getattr(record, 'terminator', '\n')
s = self.format(record)
if terminator is not None:
... | def flush(self) | Send messages by e-mail.
The sending of messages is suppressed if a trigger severity
level has been set and none of the received messages was at
that level or above. In that case the messages are
discarded. Empty e-mails are discarded. | 2.815651 | 2.540665 | 1.108234 |
if self.parseTool == 'argparse':
if args and args[0] == '': # no short option
args = args[1:]
return self.parser.add_argument(*args, **kwargs)
else:
return self.parser.add_option(*args, **kwargs) | def add_option(self, *args, **kwargs) | Add optparse or argparse option depending on CmdHelper initialization. | 3.955275 | 3.502281 | 1.129343 |
if self.parseTool == 'argparse':
self.options = self.parser.parse_args() # called options for backward compat.
else:
(self.options, self.args) = self.parser.parse_args()
# If -i is given, make sure we go into interactive mode at the end
try:
... | def parse(self) | Parse options and handle defaults.
When using OptionParser, returns tuple (options,args) of
options and list of non-option command line arguments. When
using ArgumentParser, returns Namespace object containing both
options and arguments. In other words, parse() returns the
same ... | 2.873721 | 2.832687 | 1.014486 |
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# If no printing chars
if not string:
return str(seq)
return string | def make_string(seq) | Don't throw an exception when given an out of range character. | 4.825822 | 4.638764 | 1.040325 |
x = 0
for c in string:
x = (x << 8) | ord_(c)
return x | def s2n_motorola(string) | Extract multi-byte integer in Motorola format (little endian). | 4.454219 | 3.436352 | 1.296205 |
x = 0
y = 0
for c in string:
x = x | (ord_(c) << y)
y += + 8
return x | def s2n_intel(string) | Extract multi-byte integer in Intel format (big endian). | 5.351652 | 4.415653 | 1.211973 |
with io.open(os.path.join(os.path.dirname(__file__), file_path_name), mode='rt', encoding='utf-8') as fd:
return fd.read() | def read_file(file_path_name) | Read the content of the specified file.
@param file_path_name: path and name of the file to read.
@return: content of the specified file. | 2.508032 | 3.007846 | 0.83383 |
try:
folder, index, self.script, self.selection, interlude = self.next(
self.folders, self.ensemble,
strict=strict, roles=roles
)
except TypeError:
raise GeneratorExit
with self.script as dialogue:
model = d... | def run(self, react=True, strict=True, roles=1) | Select a cast and perform the next scene.
:param bool react: If `True`, then Property directives are executed
at the point they are encountered. Pass `False` to skip them
so they can be enacted later on.
:param bool strict: Only fully-cast scripts to be performed.
:param... | 8.86399 | 7.263107 | 1.220413 |
print("merge images in %s ..." % path)
if not pdf_name:
pdf_name = os.path.join(path, '%s.pdf' % os.path.split(path)[1])
file_list = os.listdir(path)
# filter pic in path
pic_names = []
img_suffix = ['.png', '.jpg', '.jpeg']
for x in file_list:
_, suffix = os.path.split... | def img2pdf(path, pdf_name=None) | 合并path目录下的所有图片到pdf文件中
:param path: str
图片路径
:param pdf_name: str
默认值 图片路径.pdf; pdf文件名 | 2.205459 | 2.218874 | 0.993955 |
self.connection = self.get_connection()
self.connection.last_used = time.time()
self.connection.pre_call_hook(self, func)
return func(self, *args, **argd) | def with_connection(func, self, *args, **argd) | with_connection: decorator; make sure that there is a connection available
for action. Set the connections 'last_used' attribute to current timestamp.
We always get a fresh connection from the CONNECTION REGISTRY since the
'extras' could have changed. | 3.669734 | 3.029908 | 1.21117 |
if scheme not in self.schemes:
raise NoSchemeError(
'There is no handler registered for "{}" (available: {})'.format(scheme, list(self.schemes.keys()))
)
key = (
scheme,
hostname,
port,
username,
... | def get_connection(self,
scheme='',
hostname=None,
port=None,
username=None,
password=None,
vpath_connector=None,
**extras
) | get_connection: get connection for 'scheme' or create a new one.
@type scheme: str
@param scheme: the scheme to use (i.e. 'file', 'ssh', etc.)
@type hostname: str|None
@param hostname: the hostname (extracted from parsed uri)
@type port: str|None
@param port: the port ... | 2.996382 | 3.137969 | 0.95488 |
while True:
self.cleanup()
now = time.time()
try:
while (time.time() - now) < self.clean_interval:
if not self.run_clean_thread:
return
time.sleep(1)
except:
r... | def cleaner(self) | cleaner: method to be run in a thread to check for stale connections. | 4.07118 | 3.596242 | 1.132065 |
self.run_clean_thread = False
self.cleanup(True)
if self.cleaner_thread.isAlive():
self.cleaner_thread.join() | def shutdown(self) | shutdown: to be run by atexit handler. All open connection are closed. | 5.461858 | 5.123961 | 1.065945 |
try:
first, second = self.uri.rsplit('/', 1)
except ValueError:
first = ''
second = self.uri
# we might be already on the root
if first.endswith('//'):
first = first + '/'
if not first:
first = '.'
retur... | def split(self) | split: like os.path.split
@rtype: tuple(URI, str)
@return: a 2 tuple. The first element is a URI instance and the second
a string, representing the basename. | 5.672426 | 5.061576 | 1.120684 |
parts = self.uri.split('/')
if not parts:
return ''
if len(parts) > 1:
if not parts[-1]:
return parts[-2]
else:
return parts[-1]
else:
return parts[-1] | def last(self) | last: similar to 'basename', but makes sure that the last part is
really returned.
example: URI('/some/dir/').basename() will return '' while
URI('/some/dir/').last() will return 'dir'.
@return: last part of uri
@rvalue: str | 2.996586 | 2.594655 | 1.154907 |
sep = self.sep
if sep != '/':
args = [x.replace(sep, '/') for x in args]
args = (
[self.parse_result.path.rstrip('/')] +
[x.strip('/') for x in args[:-1]] +
[args[-1]]
)
parts = self.parse_result.as_list()
parts... | def join(self, *args) | join: join paths parts together to represent a path.
@return: URI instance of joined path
@rtype: URI | 3.978104 | 3.854398 | 1.032095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.