code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.__attr_func = type(
''.join([type(self).__name__, 'Funcs']),
(),
{
'__module__': type(self).__module__,
'__slots__': tuple(set(slots))
}
)() | def _attr_func_(self, slots) | Does not work as expected, makes an empty object with a new __slots__
definition. | 6.440552 | 5.722228 | 1.125532 |
"Used to lazily-evaluate & memoize an attribute."
func = getattr(self._attr_func_, name)
ret = func()
setattr(self._attr_data_, name, ret)
setattr(
type(self),
name,
property(
functools.partial(self._simple_get_, name)
... | def _loadable_get_(name, self) | Used to lazily-evaluate & memoize an attribute. | 5.511492 | 3.853872 | 1.430118 |
"Used to raise an exception for attributes unable to be evaluated yet."
raise AttributeError(
"'{typename}' object has no attribute '{name}'".format(
typename=type(self).__name__,
name=name
)
) | def _setable_get_(name, self) | Used to raise an exception for attributes unable to be evaluated yet. | 6.990626 | 2.881394 | 2.426126 |
"Used to set the attribute a single time using the given function."
setattr(self._attr_data_, name, func())
if hasattr(self._attr_func_, name):
delattr(self._attr_func_, name)
setattr(
type(self),
name,
property(
functool... | def _setable_set_(name, self, func) | Used to set the attribute a single time using the given function. | 5.547297 | 4.094938 | 1.354672 |
"Initially sets up an attribute."
if doc is None:
doc = 'The {name} attribute.'.format(name=name)
if not hasattr(self._attr_func_, name):
attr_prop = property(
functools.partial(self._setable_get_, name),
functools.partial(self._setable_s... | def _set_attr(self, name, doc=None, preload=False) | Initially sets up an attribute. | 2.968709 | 2.693166 | 1.102312 |
"Resets an attribute (or adds a new attribute) to be lazily-evaluated."
keys = set(self)
if name not in keys:
try:
data, funcs = zip(*[
(
(
key, (
getattr(self._at... | def _reset_attr(self, name, func=None, doc=None, preload=False) | Resets an attribute (or adds a new attribute) to be lazily-evaluated. | 2.406732 | 2.201254 | 1.093346 |
if len(seq) < 4:
return ''
if seq == [252, 1, 6, 0]:
return '-2/3 EV'
if seq == [253, 1, 6, 0]:
return '-1/2 EV'
if seq == [254, 1, 6, 0]:
return '-1/3 EV'
if seq == [0, 1, 6, 0]:
return '0 EV'
if seq == [2, 1, 6, 0]:
return '+1/3 EV'
if s... | def ev_bias(seq) | First digit seems to be in steps of 1/6 EV.
Does the third value mean the step size? It is usually 6,
but it is 12 for the ExposureDifference.
Check for an error condition that could cause a crash.
This only happens if something has gone really wrong in
reading the Nikon MakerNote.
http://tomti... | 2.939592 | 2.736284 | 1.074301 |
TEST_IP = 'http://httpbin.org/ip'
html = requests.get(TEST_IP)
ip = json.loads(html.text)['origin']
return ip | def get_self_ip() | 获取本机公网ip地址 | 3.450206 | 2.689152 | 1.283009 |
ip = 'http://ip.chinaz.com/' + ip
html = requests.get(ip)
ip_info = BeautifulSoup(html.text, 'lxml')
ip_loc = ip_info.find_all('span', {'class': 'Whwtdhalf w50-0'})
return ip_loc[-1].text | def get_ip_location(ip) | 获取ip的地理位置信息 | 5.571455 | 5.26447 | 1.058313 |
file_name = os.path.split(url)[1]
file = urlopen(url)
with open(file_name, 'wb') as f:
f.write(file.read())
print("文件下载成功:%s " % file_name) | def download(url) | 输入文件url,下载该文件 | 2.711135 | 2.383381 | 1.137516 |
if buttons == gtk.BUTTONS_OK:
default = gtk.RESPONSE_OK
return _message_dialog(type, short, long, parent=parent, buttons=buttons,
default=default, **kw) | def simple(type, short, long=None,
parent=None, buttons=gtk.BUTTONS_OK, default=None, **kw) | A simple dialog
:param type: The type of dialog
:param short: The short description
:param long: The long description
:param parent: The parent Window to make this dialog transient to
:param buttons: A buttons enum
:param default: A default response | 2.742245 | 3.647279 | 0.75186 |
assert not (patterns and filter)
if multiple:
if action is not None and action != gtk.FILE_CHOOSER_ACTION_OPEN:
raise ValueError('`multiple` is only valid for the action '
'`gtk.FILE_CHOOSER_ACTION_OPEN`.')
action = gtk.FILE_CHOOSER_ACTION_OPEN
... | def open_filechooser(title, parent=None, patterns=None,
folder=None, filter=None, multiple=False,
_before_run=None, action=None) | An open dialog.
:param parent: window or None
:param patterns: file match patterns
:param folder: initial folder
:param filter: file filter
Use of filter and patterns at the same time is invalid. | 1.929013 | 1.92028 | 1.004548 |
filechooser = gtk.FileChooserDialog(title, parent,
gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
if current_name:
filech... | def save(title='Save', parent=None, current_name='', folder=None,
_before_run=None, _before_overwrite=None) | Displays a save dialog. | 2.208351 | 2.186331 | 1.010072 |
'''
.. versionadded:: v0.19
Parameters
----------
images : list
Filepaths to images or :class:`gtk.Pixbuf` instances.
delay_s : float, optional
Number of seconds to display each frame.
Default: ``1.0``.
loop : bool, optional
If ``True``, restart animation af... | def animation_dialog(images, delay_s=1., loop=True, **kwargs) | .. versionadded:: v0.19
Parameters
----------
images : list
Filepaths to images or :class:`gtk.Pixbuf` instances.
delay_s : float, optional
Number of seconds to display each frame.
Default: ``1.0``.
loop : bool, optional
If ``True``, restart animation after last ima... | 3.085898 | 2.070134 | 1.490676 |
cols = df.columns
res = []
for col in cols:
length = len(df[col])
not_nas = len(df[col].dropna())
nas = length - not_nas
rate = round(nas/length, 4)
# add unique value
uv = len(df[col].unique())
res_ = (col, nas, not_nas, rate, uv)
res.app... | def count_nans(df) | Count the total number of NaNs in every column
Parameters
--------------------
df pd.DataFrame
Returns
--------------------
nas_df pd.DataFrame | 3.382946 | 3.475944 | 0.973245 |
path_split = os.path.split(path)
while path_split[1]:
if in_armstrong_project(path):
return path
path = path_split[0]
path_split = os.path.split(path)
# we ran out of parents
return None | def find_project_dir(path=os.getcwd()) | Attempt to find the project root, returns None if not found | 3.609094 | 3.406668 | 1.059421 |
"Given a list of pathnames, returns the longest common leading component"
if not m:
return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0:
return ''
... | def _commonprefix(m) | Given a list of pathnames, returns the longest common leading component | 2.451353 | 2.131664 | 1.149971 |
if self.use_advanced and cache_info:
hkeys = headers.keys()
if cache_info.access_time and "If-Modified-Since" not in hkeys:
headers['If-Modified-Since'] = cache_info.access_time.strftime(
"%a, %d %b %Y %H:%M:%S GMT"
)
... | def prepare_headers(self, headers, cache_info=None) | Prepare headers object for request (add cache information
:param headers: Headers object
:type headers: dict
:param cache_info: Cache information to add
:type cache_info: floscraper.models.CacheInfo
:return: Prepared headers
:rtype: dict | 2.193397 | 2.214844 | 0.990317 |
key = hashlib.md5(url).hexdigest()
accessed = self._cache_meta_get(key)
if not accessed:
# not previously cached
self.debug("From inet {}".format(url))
return None, None
if isinstance(accessed, dict):
cached = CacheInfo.from_dict... | def get(self, url, ignore_access_time=False) | Try to retrieve url from cache if available
:param url: Url to retrieve
:type url: str | unicode
:param ignore_access_time: Should ignore the access time
:type ignore_access_time: bool
:return: (data, CacheInfo)
None, None -> not found in cache
None, Cach... | 3.846551 | 3.537194 | 1.087458 |
key = hashlib.md5(url).hexdigest()
access_time = None
if not cache_info:
cache_info = CacheInfo()
if not access_time:
cache_info.access_time = now_utc()
self._cache_meta_set(key, cache_info.to_dict()) | def update(self, url, cache_info=None) | Update cache information for url
:param url: Update for this url
:type url: str | unicode
:param cache_info: Cache info
:type cache_info: floscraper.models.CacheInfo
:rtype: None | 4.190128 | 4.168485 | 1.005192 |
key = hashlib.md5(url).hexdigest()
try:
self._cache_set(key, html)
except:
self.exception("Failed to write cache")
return
self.update(url, cache_info) | def put(self, url, html, cache_info=None) | Put response into cache
:param url: Url to cache
:type url: str | unicode
:param html: HTML content of url
:type html: str | unicode
:param cache_info: Cache Info (default: None)
:type cache_info: floscraper.models.CacheInfo
:rtype: None | 5.113117 | 5.790996 | 0.882943 |
'''
Parameters
----------
df_points : pandas.DataFrame
Table with at least ``x`` and ``y`` columns.
point : pandas.Series
Series with at least ``x`` and ``y`` keys.
Returns
-------
pandas.Series
Row of :data:`df_points` table with point closest to specified
... | def find_closest(df_points, point) | Parameters
----------
df_points : pandas.DataFrame
Table with at least ``x`` and ``y`` columns.
point : pandas.Series
Series with at least ``x`` and ``y`` keys.
Returns
-------
pandas.Series
Row of :data:`df_points` table with point closest to specified
:data:`po... | 4.592361 | 1.755615 | 2.615814 |
inner_part = re.compile(r'\(\(.*?\)\)')
m = inner_part.search(uri)
inner_value = ''
if m is not None:
inner_value = uri[m.start():m.end()]
uri = uri[:m.start()]+'__inner_part__'+uri[m.end():]
# regex straight from STD 66 section B
regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]... | def urisplit(uri) | Basic URI Parser according to STD66 aka RFC3986
>>> urisplit("scheme://authority/path?query#fragment")
('scheme', 'authority', 'path', 'query', 'fragment') | 3.878861 | 3.857753 | 1.005472 |
(scheme, authority, path, query, fragment) = uri
result = ''
if scheme:
result += scheme + ':'
if authority:
result += '//' + authority
if path:
result += path
if query:
result += '?' + query
if fragment:
result += '#' + fragment
return result | def uriunsplit(uri) | Reverse of urisplit()
>>> uriunsplit(('scheme','authority','path','query','fragment'))
"scheme://authority/path?query#fragment" | 1.639 | 1.929803 | 0.849309 |
if '@' in authority:
userinfo, hostport = authority.split('@', 1)
else:
userinfo, hostport = None, authority
if userinfo and ':' in userinfo:
user, passwd = userinfo.split(':', 1)
else:
user, passwd = userinfo, None
if hostport and ':' in hostport:
host, ... | def split_authority(authority) | Basic authority parser that splits authority into component parts
>>> split_authority("user:password@host:port")
('user', 'password', 'host', 'port') | 1.688506 | 1.797499 | 0.939364 |
(user, passwd, host, port) = authority
result = ''
if user:
result += user
if passwd:
result += ':' + passwd
result += '@'
result += host
if port:
result += ':' + port
return result | def join_authority(authority) | Reverse of split_authority()
>>>join_authority(('user', 'password', 'host', 'port'))
"user:password@host:port" | 2.686364 | 2.94449 | 0.912336 |
import posixpath
bscheme, bauthority, bpath, bquery, bfragment = urisplit(base)
uscheme, uauthority, upath, uquery, ufragment = urisplit(url)
if uscheme is not None and bscheme != uscheme:
return url
if uauthority is not None:
bauthority, bpath, bquery, bfragment = \
... | def urljoin(base, url) | Join a base URL and a (possiby relative) URL.
base - base url
url - a (possibly relative) URL to join to the base URL
Returns the result as an absolute URL. | 2.305646 | 2.378671 | 0.9693 |
return tuple([self.scheme_of(uri)] + list(self.parser_for(uri)(defaults).parse(uri))) | def parse(self, uri, defaults=None) | Parse the URI.
uri is the uri to parse.
defaults is a scheme-dependent list of values to use if there
is no value for that part in the supplied URI.
The return value is a tuple of scheme-dependent length. | 10.695623 | 10.904038 | 0.980886 |
return self.parser_for(pieces[0])(defaults).unparse(pieces) | def unparse(self, pieces, defaults=None) | Join the parts of a URI back together to form a valid URI.
pieces is a tuble of URI pieces. The scheme must be in pieces[0] so that
the rest of the pieces can be interpreted. | 11.154519 | 13.772384 | 0.809919 |
return self._parsers.get(self.scheme_of(uri), DefaultURIParser) | def parser_for(self, uri) | Return the Parser object used to parse a particular URI.
Parser objects are required to have only 'parse' and 'unparse' methods. | 10.029092 | 12.497902 | 0.802462 |
wdir = pathlib.Path(wdir)
extensions = ["*.log", "*.dat", "*.txt"]
for ext in extensions:
for ff in wdir.glob(ext):
ff.unlink()
if rmdir:
wdir.rmdir() | def clear_temp(wdir, rmdir=True) | Remove all files in wdir | 3.284059 | 3.041216 | 1.079851 |
wdir = pathlib.Path(wdir)
check_simulation(wdir)
field_file = wdir / "V_0Ereim.dat"
a = np.loadtxt(field_file)
assert shape_grid[0] == int(
shape_grid[0]), "resulting x-size is not an integer"
assert shape_grid[1] == int(
shape_grid[1]), "resulting y-size is not an integer... | def load_field(wdir, shape_grid) | Extract electric field from simulation file "V_0Ereim.dat"
Parameters
----------
wdir: str or pathlib.Path
path to the working directory
shape_grid: tuple of ints
the shape of the simulation data grid
Notes
-----
These are the files present in the working directory
bhf... | 3.69323 | 3.38735 | 1.090301 |
wavelength_um = wavelength_nm / 1000
# size simulation tuple
sizeum = list(size_simulation_um)
shape_grid = list(shape_grid)
# The size of the simulation must be zero
# if there is only one grid point.
if shape_grid[0] == 1:
sizeum[0] = 0
if shape_grid[1] == 1:
siz... | def simulate_sphere(radius_sphere_um=2.5,
size_simulation_um=[7, 7],
shape_grid=(50, 50),
refractive_index_medium=1.0,
refractive_index_sphere=1.01,
measurement_position_um=2.5,
wavelength_nm=500,
... | Parameters
----------
radius_sphere_um : float
Radius of sphere in um
size_simulation_um : list of floats
Size of simulation volume in lateral dimension in um.
If a float is given, then a square simulation size is assumed. If
a tuple is given, then a rectangular shape is assu... | 2.92601 | 3.033183 | 0.964666 |
wdir = pathlib.Path(wdir)
cmd = "{pathbhfield} {mpdigit} {wl:f} {r_core:f} {r_coat:f} " \
+ "{n_grid_x:d} {xspan_min:f} {xspan_max:f} " \
+ "{n_grid_y:d} {yspan_min:f} {yspan_max:f} " \
+ "{n_grid_z:d} {zspan_min:f} {zspan_max:f} " \
+ "{case} {Kreibig:f} {n_med:f} {... | def run_simulation(wdir, arp=True, **kwargs) | Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
n_grid_x xspan_min xspan_max
n_grid_y yspan_... | 4.975042 | 3.057174 | 1.627333 |
wdir = pathlib.Path(wdir)
field = wdir / "V_0Ereim.dat"
if not (field.exists() and
field.stat().st_size > 130):
msg = "Output {} does not exist or is too small!".format(field)
raise BHFIELDExecutionError(msg) | def check_simulation(wdir) | Check bhdebug.txt to make sure that you specify enough digits to
overcome roundoff errors. | 7.740445 | 6.990527 | 1.107276 |
''' Executes a `sketchtool list` command and parse the output
:cmd: A sketchtool list command :type <list>
:src_path: File to export. :type <str>
:returns: A list of pages. Artboards & slices are included in the page hierarchy
'''
cmd.extend([src_path])
logger.debug(u'Executing cmd: %s' % cmd)
result =... | def list_cmd(cmd, src_path) | Executes a `sketchtool list` command and parse the output
:cmd: A sketchtool list command :type <list>
:src_path: File to export. :type <str>
:returns: A list of pages. Artboards & slices are included in the page hierarchy | 6.183575 | 2.323711 | 2.661078 |
''' Return slices as a flat list '''
pages = list_slices(src_path)
slices = []
for page in pages:
slices.extend(page.slices)
return slices | def slices(src_path) | Return slices as a flat list | 5.409128 | 4.263031 | 1.268846 |
''' Return artboards as a flat list '''
pages = list_artboards(src_path)
artboards = []
for page in pages:
artboards.extend(page.artboards)
return artboards | def artboards(src_path) | Return artboards as a flat list | 3.905795 | 3.15187 | 1.239199 |
''' Generates a preview of src_path as PNG.
:returns: A list of preview paths, one for each page.
'''
previews = []
for page in list_artboards(src_path):
previews.append(page.export())
for artboard in page.artboards:
previews.append(artboard.export())
return previews | def preview(src_path) | Generates a preview of src_path as PNG.
:returns: A list of preview paths, one for each page. | 4.952571 | 3.124628 | 1.585012 |
content = "%s%s%s" % (username, self.shared_secret, request_url)
return hashlib.sha256(content.encode('utf8')).hexdigest() | def get_password(self, username, request_url) | Calculate the password as per the API specification.
:param username:
:param request_url:
:return: password (string) | 3.703361 | 4.051959 | 0.913968 |
message = "%s%s%s%s" % (self.api_key, nonce, timestamp, signed_id)
if self._pub_key is None:
warnings.warn("Skipping RSA signature verification. Please pass public key on class initialization to ensure highest level of security!")
return True
try:
r... | def verify_signature(self, signature, nonce, timestamp, signed_id) | Verify the server response signature.
:param signature:
:param nonce:
:param timestamp:
:param signed_id: either transactionid, documentid or marketplacemerchantid
:return: true of false | 4.029064 | 4.338806 | 0.928611 |
auth_json = response_json.get('auth', {})
nonce = auth_json.get('nonce', '')
timestamp = auth_json.get('timestamp', '')
signature = binascii.unhexlify(auth_json.get('signature', ''))
signed_id = response_json.get(signed_id_name, '')
return self.verify_signatur... | def verify_response(self, response_json, signed_id_name='transactionid') | Verify the response message.
:param response_json:
:param signed_id_name:
:return: | 2.363477 | 2.396338 | 0.986287 |
return str((amount.quantize(Decimal('.01'), rounding=ROUND_FLOOR) * 100).quantize(Decimal('0'))) | def convert_decimal_to_hundreds(self, amount) | Convert Decimal(10.10) to string "1010"
:param amount:
:return: | 4.411629 | 4.621989 | 0.954487 |
'''
Returns HTML as a BeautifulSoup element.
'''
components_soup = Tag(name=self.tagname, builder=BUILDER)
components_soup.attrs = self.attributes
for c in flatten(self.components):
if hasattr(c, 'soup'):
components_soup.append(c.soup())
... | def soup(self) | Returns HTML as a BeautifulSoup element. | 5.629534 | 5.030365 | 1.11911 |
'''
Returns a flattened list of all plugins used by page components.
'''
plugins = []
for c in self.components:
if hasattr(c, 'plugins'):
plugins += c.plugins()
elif isinstance(c, Lib):
plugins.append(c)
elif... | def plugins(self, deduplicate=False) | Returns a flattened list of all plugins used by page components. | 3.302944 | 2.477469 | 1.333193 |
'''
Running plugins and adding an HTML doctype to the
generated Tag HTML.
'''
dom = BeautifulSoup('<!DOCTYPE html>')
# BeautifulSoup behaves differently if lxml is installed or not,
# and will create a basic HTML structure if lxml is installed.
if... | def soup(self) | Running plugins and adding an HTML doctype to the
generated Tag HTML. | 13.123137 | 6.982367 | 1.879468 |
return self.place_id and other.place_id \
and self.place_id == other.place_id | def _eq__(self, other) | Compare the current place object to another passed to the comparison
method. The two place objects must have the same identification, even
if some of their attributes might be different.
@param other: a ``Place`` instance to compare with the current place
object.
@return: ... | 5.729093 | 7.553319 | 0.758487 |
'''Load all classes from modules of a given `package_str`. All class instances are stored in a case-insensitive `dict`
and returned. If a package doesn't contain any class `None` is returned'''
_logger.debug('Loading all modules from %s', package_str)
package = importlib.import_module(package_str)
... | def load_classes(package_str) | Load all classes from modules of a given `package_str`. All class instances are stored in a case-insensitive `dict`
and returned. If a package doesn't contain any class `None` is returned | 2.406353 | 1.981462 | 1.214433 |
'''Retrieve from the internal cache a class instance. All arguments are case-insensitive'''
if (package_str in _dynamo_cache) and (classname in _dynamo_cache[package_str]):
return _dynamo_cache[package_str][classname]
return None | def get(package_str, classname) | Retrieve from the internal cache a class instance. All arguments are case-insensitive | 5.174573 | 3.236185 | 1.598973 |
if val is None:
return ast.Name('None', ast.Load())
elif isinstance(val, int):
return ast.Num(val)
elif isinstance(val, bool):
return ast.Name(bytes(val), ast.Load())
elif isinstance(val, str):
return ast.Str(val)
raise TypeError(u'no literal for {0}'.format(type... | def ex_literal(val) | An int, float, long, bool, string, or None literal with the given
value. | 2.543932 | 2.604741 | 0.976655 |
if not isinstance(expr, ast.expr):
expr = ex_literal(expr)
return ast.Assign([ex_lvalue(name)], expr) | def ex_varassign(name, expr) | Assign an expression into a single variable. The expression may
either be an `ast.expr` object or a value to be used as a literal. | 4.838834 | 4.280107 | 1.130541 |
if isinstance(func, str):
func = ex_rvalue(func)
args = list(args)
for i in range(len(args)):
if not isinstance(args[i], ast.expr):
args[i] = ex_literal(args[i])
if sys.version_info[:2] < (3, 5):
return ast.Call(func, args, [], None, None)
else:
ret... | def ex_call(func, args) | A function-call expression with only positional parameters. The
function may be an expression or the name of a function. Each
argument may be an expression or a value to be used as a literal. | 2.611917 | 2.494929 | 1.04689 |
func_def = ast.FunctionDef(
name=name,
args=ast.arguments(
args=[ast.arg(arg=n, annotation=None) for n in arg_names],
kwonlyargs=[],
kw_defaults=[],
defaults=[ex_literal(None) for _ in arg_names],
),
body=statements,
decora... | def compile_func(arg_names, statements, name='_the_func', debug=False) | Compile a list of statements as the body of a function and return
the resulting Python function. If `debug`, then print out the
bytecode of the compiled function. | 2.54185 | 2.585477 | 0.983126 |
parser = Parser(template)
parser.parse_expression()
parts = parser.parts
remainder = parser.string[parser.pos:]
if remainder:
parts.append(remainder)
return Expression(parts) | def _parse(template) | Parse a top-level template string Expression. Any extraneous text
is considered literal text. | 5.51494 | 5.0004 | 1.1029 |
if self.ident in env.values:
# Substitute for a value.
return env.values[self.ident]
else:
# Keep original text.
return self.original | def evaluate(self, env) | Evaluate the symbol in the environment, returning a Unicode
string. | 8.669431 | 7.372896 | 1.175851 |
ident = self.ident
expr = ex_rvalue(VARIABLE_PREFIX + ident)
return [expr], set([ident]), set() | def translate(self) | Compile the variable lookup. | 27.987541 | 22.456896 | 1.246278 |
if self.ident in env.functions:
arg_vals = [expr.evaluate(env) for expr in self.args]
try:
out = env.functions[self.ident](*arg_vals)
except Exception as exc:
# Function raised exception! Maybe inlining the name of
# th... | def evaluate(self, env) | Evaluate the function call in the environment, returning a
Unicode string. | 5.781174 | 5.300885 | 1.090605 |
varnames = set()
ident = self.ident
funcnames = set([ident])
arg_exprs = []
for arg in self.args:
subexprs, subvars, subfuncs = arg.translate()
varnames.update(subvars)
funcnames.update(subfuncs)
# Create a subexpression ... | def translate(self) | Compile the function call. | 5.118998 | 4.892696 | 1.046253 |
out = []
for part in self.parts:
if isinstance(part, str):
out.append(part)
else:
out.append(part.evaluate(env))
return u''.join(map(str, out)) | def evaluate(self, env) | Evaluate the entire expression in the environment, returning
a Unicode string. | 3.003041 | 2.556729 | 1.174564 |
expressions = []
varnames = set()
funcnames = set()
for part in self.parts:
if isinstance(part, str):
expressions.append(ex_literal(part))
else:
e, v, f = part.translate()
expressions.extend(e)
... | def translate(self) | Compile the expression to a list of Python AST expressions, a
set of variable names used, and a set of function names. | 3.080185 | 2.280398 | 1.350723 |
# Append comma (ARG_SEP) to the list of special characters only when
# parsing function arguments.
extra_special_chars = ()
special_char_re = self.special_char_re
if self.in_argument:
extra_special_chars = (ARG_SEP,)
special_char_re = re.compile(
... | def parse_expression(self) | Parse a template expression starting at ``pos``. Resulting
components (Unicode strings, Symbols, and Calls) are added to
the ``parts`` field, a list. The ``pos`` field is updated to be
the next character after the expression. | 3.861269 | 3.767754 | 1.02482 |
assert self.pos < len(self.string)
assert self.string[self.pos] == SYMBOL_DELIM
if self.pos == len(self.string) - 1:
# Last character.
self.parts.append(SYMBOL_DELIM)
self.pos += 1
return
next_char = self.string[self.pos + 1]
... | def parse_symbol(self) | Parse a variable reference (like ``$foo`` or ``${foo}``)
starting at ``pos``. Possibly appends a Symbol object (or,
failing that, text) to the ``parts`` field and updates ``pos``.
The character at ``pos`` must, as a precondition, be ``$``. | 2.831479 | 2.63794 | 1.073367 |
assert self.pos < len(self.string)
assert self.string[self.pos] == FUNC_DELIM
start_pos = self.pos
self.pos += 1
ident = self._parse_ident()
if not ident:
# No function name.
self.parts.append(FUNC_DELIM)
return
if s... | def parse_call(self) | Parse a function call (like ``%foo{bar,baz}``) starting at
``pos``. Possibly appends a Call object to ``parts`` and update
``pos``. The character at ``pos`` must be ``%``. | 2.572729 | 2.40111 | 1.071475 |
# Try to parse a subexpression in a subparser.
expressions = []
while self.pos < len(self.string):
subparser = Parser(self.string[self.pos:], in_argument=True)
subparser.parse_expression()
# Extract and advance past the parsed expression.
... | def parse_argument_list(self) | Parse a list of arguments starting at ``pos``, returning a
list of Expression objects. Does not modify ``parts``. Should
leave ``pos`` pointing to a } character or the end of the
string. | 5.110365 | 4.737855 | 1.078624 |
remainder = self.string[self.pos:]
ident = re.match(r'\w*', remainder).group(0)
self.pos += len(ident)
return ident | def _parse_ident(self) | Parse an identifier and return it (possibly an empty string).
Updates ``pos``. | 4.118417 | 3.654049 | 1.127083 |
return self.expr.evaluate(Environment(values, functions)) | def interpret(self, values={}, functions={}) | Like `substitute`, but forces the interpreter (rather than
the compiled version) to be used. The interpreter includes
exception-handling code for missing variables and buggy template
functions but is much slower. | 13.500236 | 15.823786 | 0.853161 |
try:
res = self.compiled(values, functions)
except Exception: # Handle any exceptions thrown by compiled version.
res = self.interpret(values, functions)
return res | def substitute(self, values={}, functions={}) | Evaluate the template given the values and functions. | 6.834825 | 6.696309 | 1.020685 |
expressions, varnames, funcnames = self.expr.translate()
argnames = []
for varname in varnames:
argnames.append(VARIABLE_PREFIX + varname)
for funcname in funcnames:
argnames.append(FUNCTION_PREFIX + funcname)
func = compile_func(
ar... | def translate(self) | Compile the template to a Python function. | 3.333317 | 3.152797 | 1.057257 |
result = {}
qparts = query.split('&')
for item in qparts:
key, value = item.split('=')
key = key.strip()
value = value.strip()
result[key] = unquote_plus(value)
return result | def parse_query_string(query) | parse_query_string:
very simplistic. won't do the right thing with list values | 2.224574 | 2.098107 | 1.060277 |
"simple function to merge three parts into an uri"
uri = "%s://%s%s" % (parts[0], parts[1], parts[2])
if parts[3]:
extra = '?'+urlencode(parts[3])
uri += extra
return uri | def uri_from_parts(parts) | simple function to merge three parts into an uri | 4.753551 | 3.084972 | 1.540873 |
"return some attributes as a list"
netloc = ''
if self.vpath_connector:
netloc = '(('+self.vpath_connector+'))'
elif self.authority:
netloc = self.authority
else:
netloc = self.netloc
return [
self.scheme,
netloc... | def as_list(self) | return some attributes as a list | 5.403294 | 4.706911 | 1.147949 |
if not isinstance(value, basestring):
return False
regex = r'\x00-\x08\x0B\x0C\x0E-\x1F\x7F'
if not space:
regex += r'\x20'
if tab:
regex += r'\x09'
if crlf:
regex += r'\x0A\x0D'
return re.match(r'[' + regex + ']', value, re.U) is None | def is_print(value, space = True, tab = False, crlf = False) | Returns True if is print or False otherwise | 2.240793 | 2.274132 | 0.98534 |
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.lexists(path):
os.remove(path) | def rm_rf(path) | Recursively (if needed) delete path. | 1.986216 | 2.011277 | 0.987539 |
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def file_writelines_flush_sync(path, lines) | Fill file at @path with @lines then flush all buffers
(Python and system buffers) | 2.975352 | 3.125978 | 0.951815 |
dirname = os.path.dirname(filepath)
if dirname and dirname != os.path.curdir and not os.path.isdir(dirname):
os.makedirs(dirname)
return open(filepath, 'w') | def file_w_create_directories(filepath) | Recursively create some directories if needed so that the directory where
@filepath must be written exists, then open it in "w" mode and return the
file object. | 2.308815 | 2.589324 | 0.891667 |
# trivial no substitution early detection:
if '{{' not in line and '\\' not in line:
return line
st = NORM
out = ""
curvar = ""
for c in line:
if st is NORM:
if c == '{':
st = ONE
elif c == '\\':
st = LIT
el... | def linesubst(line, variables) | In a string, substitute '{{varname}}' occurrences with the value of
variables['varname'], '\\' being an escaping char...
If at first you don't understand this function, draw its finite state
machine and everything will become crystal clear :) | 3.105267 | 2.981797 | 1.041408 |
if target_file:
LOG.info("In process of generating file %r", target_file)
if not charset:
return [linesubst(line, variables) for line in lines]
ret = []
for line in lines:
linesub = linesubst(line, variables)
if isinstance(line, unicode):
ret.append(lin... | def txtsubst(lines, variables, target_file=None, charset=None) | Log that target_file is going to be generated, and calculate its
content by applying the linesubst() transformation with the given
variables to each given lines. | 3.358136 | 2.758779 | 1.217255 |
request_data = {
"amount": self.base.convert_decimal_to_hundreds(amount),
"currency": self.currency,
"purpose": purpose,
"capture": capture
}
if payment_reference:
request_data['paymentreference'] = payment_reference
... | def create_new_sale(self, amount, purpose, payment_reference=None, order_id=None, channel_id=None, capture=True) | Create new sale.
:param amount:
:param purpose:
:param payment_reference:
:param order_id:
:param channel_id:
:param capture:
:return: tuple (transaction_id, payment_token_number, status) | 2.695702 | 2.464353 | 1.093878 |
url = "%s%s%s/status" % (self.api_endpoint, constants.TRANSACTION_STATUS_ENDPOINT, transaction_id)
username = self.base.get_username()
password = self.base.get_password(username=username, request_url=url)
response = requests.get(url, auth=HTTPBasicAuth(username=username, passw... | def fetch_transaction_status(self, transaction_id) | Get the transaction current status.
:param transaction_id:
:return: | 3.680244 | 3.946116 | 0.932624 |
request_data = {
"amount": self.base.convert_decimal_to_hundreds(capture_amount),
"currency": self.currency,
"message": message
}
url = "%s%s%s/capture" % (self.api_endpoint, constants.TRANSACTION_STATUS_ENDPOINT, transaction_id)
username = ... | def capture_sale(self, transaction_id, capture_amount, message=None) | Capture existing preauth.
:param transaction_id:
:param capture_amount:
:param message:
:return: status code | 3.493937 | 3.585385 | 0.974494 |
import inspect
caller_file = inspect.stack()[2][1]
if os.path.exists(caller_file):
return os.path.abspath(os.path.dirname(caller_file))
else:
return os.path.abspath(os.getcwd()) | def caller_folder() | Returns the folder where the code of the caller's caller lives | 2.175243 | 2.004528 | 1.085165 |
cache_info = None
if self.cache_info:
cache_info = self.cache_info.to_dict()
return {
'cache_info': cache_info,
'html': self.html,
'scraped': self.scraped,
'raw': self.raw
} | def to_dict(self) | Response as dict
:return: response
:rtype: dict | 2.949424 | 2.854105 | 1.033397 |
if d is None:
return None
return Response(
d.get('html'),
CacheInfo.from_dict(d.get('cache_info')),
d.get('scraped'),
d.get('raw')
) | def from_dict(d) | Response from dict
:param d: Dict to load
:type d: dict
:return: response
:rtype: Response | 5.100488 | 4.526225 | 1.126875 |
try:
if not input:
if type == Types.TYPE_STRING:
return ''
else:
return None
if type == Types.TYPE_STRING:
if isinstance(input, datetime.date):
return input.strftime('%Y-%... | def convert(input, type) | Converts input value to request type
:param input: input value
:param type: type to cast
:return: converted value | 1.976322 | 2.01317 | 0.981697 |
for column in df:
df[column] = df[column].astype(object).where(df[column].notnull(), None)
return df.to_dict(orient='records') | def df2list(df) | Converts pandas.DataFrame values into list
:param df: pandas.DataFrame
:return: list | 2.706636 | 2.841834 | 0.952426 |
board = board or base.Board() # empty board by default
tile_h, tile_w = self._TILE_SHAPE[0:2]
board_shape = tile_h * 8, tile_w * 8, 3
board_image = numpy.zeros(board_shape, dtype=numpy.uint8)
# place each tile on the image
for (row, col), tile in board.positions... | def _create_board_image_cv(self, board=None) | Return a cv image of the board or empty board if not provided. | 2.993435 | 2.805753 | 1.066892 |
tile_h, tile_w = self._TILE_SHAPE[0:2]
# get a single bounding box
(row_1, col_1), (row_2, col_2) = swap
t = tile_h * min(row_1, row_2)
b = tile_h * (1 + max(row_1, row_2))
l = tile_w * min(col_1, col_2)
r = tile_w * (1 + max(col_1, col_2))
top_le... | def _draw_swap_cv(self, board_image, swap) | Add a white tile border to indicate the swap. | 2.467482 | 2.35956 | 1.045738 |
# convert BGR to RGB
image_cv_rgb = data.cv2.cvtColor(image_cv, data.cv2.COLOR_BGR2RGB)
# convert opencv to PIL
image_pil = PIL_Image.fromarray(image_cv_rgb)
# convert PIL to tkinter
return ImageTk.PhotoImage(image_pil) | def _convert_cv_to_tk(self, image_cv) | Convert an OpenCV image to a tkinter PhotoImage | 2.561685 | 2.712867 | 0.944272 |
self._analyze_start_time = time.time()
self._clear_ui()
try:
self._analysis_process.terminate() # clear anything existing
except AttributeError: # there wasn't actually a process
pass
# self._analysis_process = _AsyncReadyFunction(self._analysis... | def _analyze(self) | (Re)start analysis of the game on screen. | 6.422663 | 5.740832 | 1.118769 |
if self._analysis_process is None:
return
# handle time out
timed_out = time.time() - self._analyze_start_time > self.time_limit
if timed_out:
self._handle_results('Analysis timed out but managed\n'
' to get lower turn res... | def _scheduled_check_for_summaries(self) | Present the results if they have become available or timed out. | 7.692661 | 7.237089 | 1.06295 |
self.summaries.rotate(-1)
current_summary = self.summaries[0]
self._update_summary(current_summary) | def _next(self) | Get the next summary and present it. | 7.306829 | 4.101885 | 1.781334 |
self.summaries.rotate()
current_summary = self.summaries[0]
self._update_summary(current_summary) | def _previous(self) | Get the previous summary and present it. | 8.009748 | 4.552618 | 1.759372 |
if message is None:
message = ''
message_label = self._parts['notification label']
message_label.config(text=message)
self._base.update() | def _update_notification(self, message=None) | Update the message area with blank or a message. | 6.779555 | 5.006171 | 1.35424 |
board_image_label = self._parts['board image label']
# get content for update or use blanks when no summary
if summary:
# make a board image with the swap drawn on it
# board, action, text = summary.board, summary.action, summary.text
board_image_cv =... | def _update_summary(self, summary=None) | Update all parts of the summary or clear when no summary. | 4.523605 | 4.279806 | 1.056965 |
assert len(return_type) <= 1, 'You can specify at most one return type.'
arg_msg = '%s must be %s, not %s.'
return_msg = 'must return %s, not %s.'
def f(func):
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
# convert args to call args
... | def types(*return_type, **arg_types) | Assert types of the function arguments and return value.
:param return_type: expected type of the return value
:param arg_types: expected types of the arguments
:example:
@types(float, x=int, y=float, z=ListOf(int))
def f(x, y, z):
return x * y + sum(z) | 2.249312 | 2.489747 | 0.90343 |
# Pre-process the request
try:
self.procstack.proc_request(self)
except exc.ShortCircuit, e:
self._debug("Request pre-processing short-circuited")
# Short-circuited; we have an (already processed) response
return e.response
self... | def send(self) | Issue the request.
Uses httplib2.Http support for handling redirects. Returns an
httplib2.Response, which may be augmented by the
proc_response() method.
Note that the default implementation of proc_response() causes
an appropriate exception to be raised if the response code i... | 4.515399 | 4.009665 | 1.126129 |
# Raise exceptions for error responses
if resp.status >= 400:
e = exc.exception_map.get(resp.status, exc.HTTPException)
self._debug(" Response was a %d fault, raising %s",
resp.status, e.__name__)
raise e(resp) | def proc_response(self, resp) | Process response hook.
Process non-redirect responses received by the send() method.
May augment the response. The default implementation causes
an exception to be raised if the response status code is >=
400. | 5.91436 | 6.017276 | 0.982896 |
'''
used to send async notifications
:param method:
:param method_args:
:param method_kwargs:
:param done_callback:
:param done_kwargs:
:param loop:
:return:
'''
_future = self.pool.submit(method, *method_args, **method_kwargs)
... | def submit(self, method, method_args=(), method_kwargs={}, done_callback=None, done_kwargs={}, loop=None) | used to send async notifications
:param method:
:param method_args:
:param method_kwargs:
:param done_callback:
:param done_kwargs:
:param loop:
:return: | 3.365983 | 2.976618 | 1.130808 |
# If we have a datetime object
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
# Else if we have a decimal object
elif isinstance(obj, Decimal):
return '{0:f}'.format(obj)
# Bubble back up to the parent default
return json.JSONEncoder.default(self, obj) | def default(self, obj) | Default
Called when the regular Encoder can't figure out what to do with the type
Args:
self (CEncoder): A pointer to the current instance
obj (mixed): An unknown object that needs to be encoded
Returns:
str: A valid JSON string representing the object | 3.009291 | 3.057697 | 0.984169 |
super(LabelCommand, self).add_arguments()
self.parser.add_argument('labels', metavar=self.label, nargs="+") | def add_arguments(self) | Add the label argument by default, no need to specify it in args. | 5.407078 | 3.936049 | 1.373732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.