code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def create(gitpath, cache=None):
if gitpath.startswith(config.LIBRARY_PREFIX):
path = gitpath[len(config.LIBRARY_PREFIX):]
return Library(*path.split('/'), cache=cache) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier subscript identifier slice call identifier argument_list attribute identifi... | Create a Library from a git path. |
def publishing_prepare_published_copy(self, draft_obj):
mysuper = super(PublishingModel, self)
if hasattr(mysuper, 'publishing_prepare_published_copy'):
mysuper.publishing_prepare_published_copy(draft_obj) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identi... | Prepare published copy of draft prior to saving it |
def _init_client():
if client is not None:
return
global _mysql_kwargs, _table_name
_mysql_kwargs = {
'host': __opts__.get('mysql.host', '127.0.0.1'),
'user': __opts__.get('mysql.user', None),
'passwd': __opts__.get('mysql.password', None),
'db': __opts__.get('mysql.d... | module function_definition identifier parameters block if_statement comparison_operator identifier none block return_statement global_statement identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_lis... | Initialize connection and create table if needed |
def success(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags,
fail_silently=fail_silently) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end default_parameter identifier false block expression_statement call identifier argument_list attribute identifier identifier identifier attribute identifier identifier identifier ... | Add a message with the ``SUCCESS`` level. |
def asrgb(self, *args, **kwargs):
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement... | Read image data from file and return RGB image as numpy array. |
def clear_components(self):
ComponentRegistry._component_overlays = {}
for key in self.list_components():
self.remove_component(key) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier | Clear all of the registered components |
def draw_canvas():
for x in range(len(world)):
for y in range(len(world[x])):
if world[x][y].value:
color = world[x][y].color_alive.get_as_hex()
else:
color = world[x][y].color_dead.get_as_hex()
canvas.itemconfig(canvas_grid[x][y], fill=col... | module function_definition identifier parameters block for_statement identifier call identifier argument_list call identifier argument_list identifier block for_statement identifier call identifier argument_list call identifier argument_list subscript identifier identifier block if_statement attribute subscript subscri... | Render the tkinter canvas based on the state of ``world`` |
def decode_network_packet(buf):
off = 0
blen = len(buf)
while off < blen:
ptype, plen = header.unpack_from(buf, off)
if plen > blen - off:
raise ValueError("Packet longer than amount of data in buffer")
if ptype not in _decoders:
raise ValueError("Message type... | module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier identifier block expression_statement assignment pattern_list identifier... | Decodes a network packet in collectd format. |
def __start(self):
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_thread.daemon = True
self.running = True
self.dispatcher_threa... | module function_definition identifier parameters identifier block assert_statement not_operator attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument ... | Starts the real-time engine that captures tasks. |
def delete(self):
'Delete this file and return the new, deleted JFSFile'
r = self.jfs.post(url=self.path, params={'dl':'true'})
return r | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argu... | Delete this file and return the new, deleted JFSFile |
def parse_file(infile, exit_on_error=True):
try:
a, b, mag = np.atleast_2d(
np.genfromtxt(
infile,
usecols=[0, 1, 2],
delimiter=','
... | module function_definition identifier parameters identifier default_parameter identifier true block try_statement block expression_statement assignment pattern_list identifier identifier identifier attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier... | Parse a comma-separated file with columns "ra,dec,magnitude". |
def windowed_iterable(self):
effective_offset = max(0,self.item_view.iterable_index)
for i,item in enumerate(self.iterable):
if i<effective_offset:
continue
elif i>=(effective_offset+self.item_view.iterable_fetch_size):
return
yield ite... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list integer attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_... | That returns only the window |
def focused_data_item(self) -> typing.Optional[DataItem.DataItem]:
return self.__focused_display_item.data_item if self.__focused_display_item else None | module function_definition identifier parameters identifier type subscript attribute identifier identifier attribute identifier identifier block return_statement conditional_expression attribute attribute identifier identifier identifier attribute identifier identifier none | Return the data item with keyboard focus. |
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None):
ensure_directories(mount_point, lower_dir, upper_dir)
if not mount_table:
mount_table = MountTable.load()
if mount_table.is_mounted(mount_point):
raise AlreadyMounted()
options = "rw,lowerdir=%s,... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement call identifier argument_list identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute id... | Execute the mount. This requires root |
def _get_on_demand_syllabus(self, class_name):
url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format(
class_name=class_name)
page = get_page(self._session, url)
logging.debug('Downloaded %s (%d bytes)', url, len(page))
return page | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier ident... | Get the on-demand course listing webpage. |
def write_capability_list(self, capabilities=None,
outfile=None, links=None):
capl = CapabilityList(ln=links)
capl.pretty_xml = self.pretty_xml
if (capabilities is not None):
for name in capabilities.keys():
capl.add_capability(name=name,... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribut... | Write a Capability List to outfile or STDOUT. |
def cli(config_path, verbose):
global config, store
if not config_path:
config_path = '/etc/record_recommender.yml'
config = get_config(config_path)
setup_logging(config)
store = FileStore(config) | module function_definition identifier parameters identifier identifier block global_statement identifier identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list... | Record-Recommender command line version. |
def open(self, auto_commit=None, schema=None):
if schema is None:
schema = self.schema
ac = auto_commit if auto_commit is not None else schema.auto_commit
exe = ExecutionContext(self.path, schema=schema, auto_commit=ac)
if not os.path.isfile(self.path) or os.path.getsize(self... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_e... | Create a context to execute queries |
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None,
**kwargs):
cls.validate(data)
inst = cls(api_key=api_key)
endpoint = ''
return inst.request('POST',
endpoint=endpoint,
data=data,
... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier... | Create an event on your PagerDuty account. |
def template_to_text(tmpl, debug=0):
tarr = []
for item in tmpl.itertext():
tarr.append(item)
text = "{{%s}}" % "|".join(tarr).strip()
if debug > 1:
print("+ template_to_text:")
print(" %s" % text)
return text | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expr... | convert parse tree template to text |
def delete_policy(self, pol_id):
if pol_id not in self.policies:
LOG.error("Invalid policy %s", pol_id)
return
del self.policies[pol_id]
self.policy_cnt -= 1 | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement delete_statemen... | Deletes the policy from the local dictionary. |
def sbo_list():
sbo_packages = []
for pkg in os.listdir(_meta_.pkg_path):
if pkg.endswith("_SBo"):
sbo_packages.append(pkg)
return sbo_packages | module function_definition identifier parameters block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content stri... | Return all SBo packages |
def bech32_polymod(values):
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
chk ^= generator[i] if ((top >> i) & 1) else 0
return chk | module function_definition identifier parameters identifier block expression_statement assignment identifier list integer integer integer integer integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier binary_operator identifier int... | Internal function that computes the Bech32 checksum. |
def process_format(self, kind, context):
result = None
while True:
chunk = yield result
if chunk is None:
return
split = -1
line = chunk.line
try:
ast.parse(line)
except SyntaxError as e:
split = line.rfind(' ', 0, e.offset)
result = chunk.clone(line='_bless(' + line[:split].rstrip(... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier none while_statement true block expression_statement assignment identifier yield identifier if_statement comparison_operator identifier none block return_statement expression_statement assi... | Handle transforming format string + arguments into Python code. |
def _parse_service_env_vars(self, env_vars):
env = {}
for var in env_vars:
k, v = var.split('=')
env.update({k: v})
return env | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_co... | Return a dict based on `key=value` pair strings. |
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False):
self.searchString = searchString
self.category = category
self.math = math
self.game = game
self.searchFiles = searchFiles
self.extension = extension | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_stateme... | Call this function with all the settings to use for future operations on a repository, must be called FIRST |
def locale_escape(string, errors='replace'):
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier i... | Mangle non-supported characters, for savages with ascii terminals. |
def compute(self):
self._compute_window_size()
smooth = []
residual = []
x, y = self.x, self.y
self._update_values_in_window()
self._update_mean_in_window()
self._update_variance_in_window()
for i, (xi, yi) in enumerate(zip(x, y)):
if ((i - sel... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier list expression_statement assignment pattern_list identifier identifier expression_list att... | Perform the smoothing operations. |
def resource_urls(request):
url_parsed = urlparse(settings.SEARCH_URL)
defaults = dict(
APP_NAME=__description__,
APP_VERSION=__version__,
SITE_URL=settings.SITE_URL.rstrip('/'),
SEARCH_TYPE=settings.SEARCH_TYPE,
SEARCH_URL=settings.SEARCH_URL,
SEARCH_IP='%s://%s:... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifie... | Global values to pass to templates |
def find(self, path, all=False):
try:
start, _, extn = path.rsplit('.', 2)
except ValueError:
return []
path = '.'.join((start, extn))
return find(path, all=all) or [] | module function_definition identifier parameters identifier identifier default_parameter identifier false block try_statement block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer excep... | Work out the uncached name of the file and look that up instead |
def _is_valid_id(self, inpt):
from dlkit.abstract_osid.id.primitives import Id as abc_id
if isinstance(inpt, abc_id):
return True
else:
return False | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier identifier aliased_import dotted_name identifier identifier if_statement call identifier argument_list identifier identifier block return_statement true else_clause block retur... | Checks if input is a valid Id |
def workbook_data(self):
document = XML(
fn=os.path.splitext(self.fn)[0]+'.xml',
root=Element.workbook())
shared_strings = [
str(t.text) for t in
self.xml('xl/sharedStrings.xml')
.root.xpath(".//xl:t", namespaces=self.NS)]
for key... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier binary_operator subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer string string_s... | return a readable XML form of the data. |
def _get_manifest_list(self, image):
if image in self.manifest_list_cache:
return self.manifest_list_cache[image]
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_insecure,
... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement subscript attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribu... | try to figure out manifest list |
def created_slices(self, user_id=None):
if not user_id:
user_id = g.user.id
Slice = models.Slice
qry = (
db.session.query(Slice)
.filter(
sqla.or_(
Slice.created_by_fk == user_id,
Slice.changed_by_fk == u... | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expres... | List of slices created by this user |
def regions(self):
url = "%s/regions" % self.root
params = {"f": "json"}
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string strin... | gets the regions value |
def consume_queue(queue, cascade_stop):
while True:
try:
item = queue.get(timeout=0.1)
except Empty:
yield None
continue
except thread.error:
raise ShutdownException()
if item.exc:
raise item.exc
if item.is_stop:
... | module function_definition identifier parameters identifier identifier block while_statement true block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier float except_clause identifier block expression_statement yield none conti... | Consume the queue by reading lines off of it and yielding them. |
def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp | module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement string string_start string_content string_end import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier ex... | Returns a copy of seq, sorted by natural string sort. |
def shape(self):
try:
return self.__shape
except AttributeError:
shape = tuple(len(vec) for vec in self.coord_vectors)
self.__shape = shape
return shape | module function_definition identifier parameters identifier block try_statement block return_statement attribute identifier identifier except_clause identifier block expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier for_in_clause identifier attribut... | Number of grid points per axis. |
def tcp_server(tcp_addr, settings):
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.bind(tcp_addr)
sock.listen(1)
logging.info("Waiting for connection on %s", tcp_addr)
conn, addr = sock.accept()
logging.info("Acc... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_stat... | Start up the tcp server, send the settings. |
def dry(self, *args, **kwargs):
return 'Would have executed:\n%s%s' % (
self.name, Args(self.spec).explain(*args, **kwargs)) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier call attribute call identifier argument_list attribute ... | Perform a dry-run of the task |
def stop_video_recording(self):
self.runner.info_log("Stopping video recording...")
self.execute_command("./stop_recording.sh")
sleep(5)
self.scp_file_remote_to_local(
self.remote_video_recording_file_path,
self.local_video_recording_file_path
) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_e... | Stop the video recording |
def asyncStarMap(asyncCallable, iterable):
deferreds = starmap(asyncCallable, iterable)
return gatherResults(deferreds, consumeErrors=True) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier true | itertools.starmap for deferred callables |
def save(self, *args, **kwargs):
if self.created is None:
self.created = tz_now()
if self.modified is None:
self.modified = self.created
super(Thread, self).save(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list if_statement compa... | Fill 'created' and 'modified' attributes on first create |
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]:
if fields == ALL:
fields = allowed_fields.keys()
else:
fields = tuple(fields)
unknown_fields = set(fields) - allowed_fields.keys()
if unknown_fields:
raise ValueError('Unknown fields: {}'.f... | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute ... | Clean lookup fields and check for errors. |
def validateFilepath( self ):
if ( not self.isValidated() ):
return
valid = self.isValid()
if ( not valid ):
fg = self.invalidForeground()
bg = self.invalidBackground()
else:
fg = self.validForeground()
bg = self.validBackground... | module function_definition identifier parameters identifier block if_statement parenthesized_expression not_operator call attribute identifier identifier argument_list block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expressi... | Alters the color scheme based on the validation settings. |
def topic_path(cls, project, topic):
return google.api_core.path_template.expand(
"projects/{project}/topics/{topic}", project=project, topic=topic
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifie... | Return a fully-qualified topic string. |
def np2model_tensor(a):
"Tranform numpy array `a` to a tensor of the same type."
dtype = model_type(a.dtype)
res = as_tensor(a)
if not dtype: return res
return res.type(dtype) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifie... | Tranform numpy array `a` to a tensor of the same type. |
def And(*args: Union[Bool, bool]) -> Bool:
union = []
args_list = [arg if isinstance(arg, Bool) else Bool(arg) for arg in args]
for arg in args_list:
union.append(arg.annotations)
return Bool(z3.And([a.raw for a in args_list]), union) | module function_definition identifier parameters typed_parameter list_splat_pattern identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement assignment identifier list expression_statement assignment identifier list_comprehension conditional_expre... | Create an And expression. |
def queue_resize(self):
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement boolean_operator boolean_operator ide... | request the element to re-check it's child sprite sizes |
def client_list_entries_multi_project(
client, to_delete
):
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_IDS):
do_something_with(entry) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier... | List entries via client across multiple projects. |
def strict_logical(self, value):
if value is not None:
if not isinstance(value, bool):
raise TypeError(
'f90nml: error: strict_logical must be a logical value.')
else:
self._strict_logical = value | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause ... | Validate and set the strict logical flag. |
def _distance_stats_sqr_fast_generic(x, y, dcov_function):
covariance_xy_sqr = dcov_function(x, y)
variance_x_sqr = dcov_function(x, x)
variance_y_sqr = dcov_function(y, y)
denominator_sqr_signed = variance_x_sqr * variance_y_sqr
denominator_sqr = np.absolute(denominator_sqr_signed)
denominator ... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier... | Compute the distance stats using the fast algorithm. |
def save(self, resq=None):
if not resq:
resq = ResQ()
data = {
'failed_at' : datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
'payload' : self._payload,
'exception' : self._exception.__class__.__name__,
'error' : self._parse_message... | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end... | Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info. |
def google_get_data(self, config, response):
params = {
'access_token': response['access_token'],
}
payload = urlencode(params)
url = self.google_api_url + 'userinfo?' + payload
req = Request(url)
json_str = urlopen(req).read()
return json.loads(json_s... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier a... | Make request to Google API to get profile data for the user. |
def contains_circle(self, pt, radius):
return (self.l < pt.x - radius and self.r > pt.x + radius and
self.t < pt.y - radius and self.b > pt.y + radius) | module function_definition identifier parameters identifier identifier identifier block return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier binary_operator attribute identifier identifier identifier comparison_operator attribut... | Is the circle completely inside this rect? |
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None):
if not isinstance(string, str):
string = str(string)
if rgb is None and ansi is None:
raise TerminalColorMapException(
'colorize: must specify one named parameter: rgb or ansi')
if rgb... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement not_operator call identifier argument_list identifier identifier block expression_statement as... | Returns the colored string |
def to_json(self, *args, **kwargs):
return json.dumps(self.serialize(), *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier | Convert Entity to JSON. |
def contains_one_of(*fields):
message = 'Must contain any one of the following fields: {0}'.format(', '.join(fields))
def check_contains(endpoint_fields):
for field in fields:
if field in endpoint_fields:
return
errors = {}
for field in fields:
err... | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier function_... | Enables ensuring that one of multiple optional fields is set |
def publish(self, distribution, storage=""):
try:
return self._publishes[distribution]
except KeyError:
self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.storage))
return self._publishes[distribution] | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block try_statement block return_statement subscript attribute identifier identifier identifier except_clause identifier block expression_statement assignment subscript attribute identifier... | Get or create publish |
def _explain(self, tree):
self._explaining = True
self._call_list = []
old_call = self.connection.call
def fake_call(command, **kwargs):
if command == "describe_table":
return old_call(command, **kwargs)
self._call_list.append((command, kwargs))
... | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier list expression_statement assignment identifier attribute attribute identifier identifier identifier function_... | Set up the engine to do a dry run of a query |
def create(pid_type, pid_value, status, object_type, object_uuid):
from .models import PersistentIdentifier
if bool(object_type) ^ bool(object_uuid):
raise click.BadParameter('Speficy both or any of --type and --uuid.')
new_pid = PersistentIdentifier.create(
pid_type,
pid_value,
... | module function_definition identifier parameters identifier identifier identifier identifier identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier if_statement binary_operator call identifier argument_list identifier call identifier argument_list identifier b... | Create new persistent identifier. |
def disable_hidden_api_blacklist(self):
version_codename = self._ad.adb.getprop('ro.build.version.codename')
sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk'))
if self._ad.is_rootable and (sdk_version >= 28
or version_codename == 'P'):
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list... | If necessary and possible, disables hidden api blacklist. |
def reload(self):
pid = self._read_pidfile()
if pid is None or pid != os.getpid():
raise DaemonError(
'Daemon.reload() should only be called by the daemon process '
'itself')
new_environ = os.environ.copy()
new_environ['DAEMONOCLE_RELOAD'] = 't... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier none comparison_operator identifier call attribute identifier identifier argument_list block raise_... | Make the daemon reload itself. |
def _save_settings(self):
if self._autosettings_path == None: return
gui_settings_dir = _os.path.join(_cwd, 'egg_settings')
if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)
path = _os.path.join(gui_settings_dir, self._autosettings_path)
settings = _g.QtCore.Q... | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content ... | Saves all the parameters to a text file. |
def append(self, child):
if not (isinstance(child, CP2KSection) or isinstance(child, CP2KKeyword)):
raise TypeError("The child must be a CP2KSection or a CP2KKeyword, got: %s." % child)
l = self.__index.setdefault(child.name, [])
l.append(child)
self.__order.append(child) | module function_definition identifier parameters identifier identifier block if_statement not_operator parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator str... | Add a child section or keyword |
def mean_se(series, mult=1):
m = np.mean(series)
se = mult * np.sqrt(np.var(series) / len(series))
return pd.DataFrame({'y': [m],
'ymin': m-se,
'ymax': m+se}) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argum... | Calculate mean and standard errors on either side |
def uninitialize(cls) -> None:
if not cls._initialized:
return
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False | module function_definition identifier parameters identifier type none block if_statement not_operator attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assign... | Removes the ``SIGCHLD`` handler. |
async def upcoming(self, details: bool = False) -> list:
endpoint = 'dailystats'
key = 'DailyStats'
if details:
endpoint += '/details'
key = 'DailyStatsDetails'
data = await self._request('get', endpoint)
return data[key] | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier false type identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_... | Return watering statistics for the next 6 days. |
def _parse_date_input(date_input, default_offset=0):
if date_input:
try:
return parse_date_input(date_input)
except ValueError as err:
raise CommandError(force_text(err))
else:
return get_midnight() - timedelta(days=default_offset) | module function_definition identifier parameters identifier default_parameter identifier integer block if_statement identifier block try_statement block return_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argume... | Parses a date input. |
def pandoc_process(app, what, name, obj, options, lines):
if not lines:
return None
input_format = app.config.mkdsupport_use_parser
output_format = 'rst'
text = SEP.join(lines)
text = pypandoc.convert_text(text, output_format, format=input_format)
del lines[:]
lines.extend(text.split... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement not_operator identifier block return_statement none expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identi... | Convert docstrings in Markdown into reStructureText using pandoc |
def _get(self, q, params=''):
if (q[-1] == '/'): q = q[:-1]
headers = {'Content-Type': 'application/json'}
r = requests.get('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),
headers=headers)
ret = DotDict(r.json())
... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block if_statement parenthesized_expression comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignme... | Generic GET wrapper including the api_key |
def close(self):
"Stop the output stream, but further download will still perform"
if self.stream:
self.stream.close(self.scheduler)
self.stream = None | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_... | Stop the output stream, but further download will still perform |
def numpy_to_texture(image):
if not isinstance(image, np.ndarray):
raise TypeError('Unknown input type ({})'.format(type(image)))
if image.ndim != 3 or image.shape[2] != 3:
raise AssertionError('Input image must be nn by nm by RGB')
grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)... | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier a... | Convert a NumPy image array to a vtk.vtkTexture |
def load(cls, keys):
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversations | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier if_state... | Load a set of conversations by their keys. |
def s3_get(url: str, temp_file: IO) -> None:
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignme... | Pull a file directly from S3. |
def pull_from_origin(repo_path):
LOG.info("Pulling from origin at %s." % repo_path)
command = GIT_PULL_CMD.format(repo_path)
resp = envoy.run(command)
if resp.status_code != 0:
LOG.exception("Pull failed.")
raise GitException(resp.std_err)
else:
LOG.info("Pull successful.") | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expr... | Execute 'git pull' at the provided repo_path. |
def _change_volume(self, increase):
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_s... | Change volume using amixer |
def saveProfile( self ):
manager = self.parent()
prof = manager.currentProfile()
save_prof = manager.viewWidget().saveProfile()
prof.setXmlElement(save_prof.xmlElement()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call att... | Saves the current profile to the current settings from the view widget. |
async def async_discovery(session):
bridges = []
response = await async_request(session.get, URL_DISCOVER)
if not response:
_LOGGER.info("No discoverable bridges available.")
return bridges
for bridge in response:
bridges.append({'bridgeid': bridge['id'],
... | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier await call identifier argument_list attribute identifier identifier identifier if_statement not_operator identifier block expression_statement call attribute ident... | Find bridges allowing gateway discovery. |
def _getTypename(self, defn):
return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER' | module function_definition identifier parameters identifier identifier block return_statement conditional_expression string string_start string_content string_end boolean_operator boolean_operator attribute attribute identifier identifier identifier comparison_operator string string_start string_content string_end attr... | Returns the SQL typename required to store the given FieldDefinition |
def raise_msg_to_str(msg):
if not is_string_like(msg):
msg = '\n'.join(map(str, msg))
return msg | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list call identifier argument_list identi... | msg is a return arg from a raise. Join with new lines |
def main():
options = handle_options()
elecs, d_obs = readin_volt(options.d_obs)
elecs, d_est = readin_volt(options.d_est)
elecs, d_estTC = readin_volt(options.d_estTC)
volt_corr = calc_correction(d_obs,
d_est,
d_estTC,
... | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identif... | Function to remove temperature effect from field data |
def read_epilogue(self):
with open(self.filename, "rb") as fp_:
fp_.seek(self.mda['total_header_length'])
data = np.fromfile(fp_, dtype=hrit_epilogue, count=1)
self.epilogue.update(recarray2dict(data)) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argum... | Read the epilogue metadata. |
def _merge_cluster(old, new):
logger.debug("_merge_cluster: %s to %s" % (old.id, new.id))
logger.debug("_merge_cluster: add idls %s" % old.loci2seq.keys())
for idl in old.loci2seq:
new.add_id_member(old.loci2seq[idl], idl)
return new | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement call attribute ide... | merge one cluster to another |
def create(self):
data = self._node_data()
data["node_id"] = self._id
if self._node_type == "docker":
timeout = None
else:
timeout = 1200
trial = 0
while trial != 6:
try:
response = yield from self._compute.post("/projec... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_opera... | Create the node on the compute server |
def resume(self, data):
'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object'
if not hasattr(data, 'read'):
data = six.BytesIO(data)
if self.size == -1:
log.debug('%r is an incomplete file, but .size is unknown. Refreshing... | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute... | Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object |
def GetUnreachableHosts(hostnames, ssh_key):
ssh_status = AreHostsReachable(hostnames, ssh_key)
assert(len(hostnames) == len(ssh_status))
nonresponsive_hostnames = [host for (host, ssh_ok) in
zip(hostnames, ssh_status) if not ssh_ok]
return nonresponsive_hostnames | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier assert_statement parenthesized_expression comparison_operator call identifier argument_list identifier call identifier argument_list identifier expr... | Returns list of hosts unreachable via ssh. |
def server_list_min(self):
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier ... | List minimal information about servers |
def poll_for_server_running(job_id):
sys.stdout.write('Waiting for server in {0} to initialize ...'.format(job_id))
sys.stdout.flush()
desc = dxpy.describe(job_id)
while(SERVER_READY_TAG not in desc['tags'] and desc['state'] != 'failed'):
time.sleep(SLEEP_PERIOD)
sys.stdout.write('.')
... | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identif... | Poll for the job to start running and post the SERVER_READY_TAG. |
def application_unauthenticated(request, token, state=None, label=None):
application = base.get_application(secret_token=token)
if application.expires < datetime.datetime.now():
return render(
template_name='kgapplications/common_expired.html',
context={'application': application... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator attribute... | An somebody is trying to access an application. |
def _encode_mapping(name, value, check_keys, opts):
data = b"".join([_element_to_bson(key, val, check_keys, opts)
for key, val in iteritems(value)])
return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00" | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause ... | Encode a mapping type. |
def clean_docstring(docstring):
docstring = docstring.strip()
if '\n' in docstring:
if docstring[0].isspace():
return textwrap.dedent(docstring)
else:
first, _, rest = docstring.partition('\n')
return first + '\n' + textwrap.dedent(rest)
return docstring | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content escape_sequence string_end identifier block if_statement call attribute subscript identifier... | Dedent docstring, special casing the first line. |
def _skip(options):
values = [options.missing_direct_deps, options.unnecessary_deps]
return all(v == 'off' for v in values) | module function_definition identifier parameters identifier block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier return_statement call identifier generator_expression comparison_operator identifier string string_start string_content string_end for_in_clau... | Return true if the task should be entirely skipped, and thus have no product requirements. |
def close(self):
if self.read_option('save_pointer'):
self._update_last_pointer()
super(S3Writer, self).close() | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement call attribute call identifier argument_list ... | Called to clean all possible tmp files created during the process. |
def shutdown(self) -> None:
self._is_handshake_completed = False
try:
self._flush_ssl_engine()
except IOError:
pass
try:
self._ssl.shutdown()
except OpenSSLError as e:
if 'SSL_shutdown:uninitialized' not in str(e) and 'shutdown whil... | module function_definition identifier parameters identifier type none block expression_statement assignment attribute identifier identifier false try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement try_statement block expression_state... | Close the TLS connection and the underlying network socket. |
def verifymessage(self, address, signature, message):
return self.req("verifymessage", [address, signature, message]) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end list identifier identifier identifier | Verify a signed message. |
def tar_and_copy_usr_dir(usr_dir, train_dir):
tf.logging.info("Tarring and pushing t2t_usr_dir.")
usr_dir = os.path.abspath(os.path.expanduser(usr_dir))
top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container")
tmp_usr_dir = os.path.join(top_dir, usr_dir_lib.INTERNAL_USR_DIR_PACKAGE)
shutil.rmtree(to... | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier arg... | Package, tar, and copy usr_dir to GCS train_dir. |
def file_length(in_file):
fid = open(in_file)
data = fid.readlines()
fid.close()
return len(data) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list retu... | Function to return the length of a file. |
def scoped_connection(func):
def _with(series, *args, **kwargs):
connection = None
try:
connection = series._connection()
return func(series, connection, *args, **kwargs)
finally:
series._return( connection )
return _with | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute ide... | Decorator that gives out connections. |
def rar3_type(btype):
if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC:
return "*UNKNOWN*"
return block_strs[btype - rf.RAR_BLOCK_MARK] | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block return_statement string string_start string_content string_end return_statement subscript id... | RAR3 type code as string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.