code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def just_log(*texts, sep = ""):
if config.silent:
return
text = _color_sep + "default" + _color_sep2 + sep.join(texts)
array = text.split(_color_sep)
for part in array:
parts = part.split(_color_sep2, 1)
if len(parts) != 2 or not parts[1]:
continue
if not config.color:
print(parts[1], end='')
else:
... | module function_definition identifier parameters list_splat_pattern identifier default_parameter identifier string string_start string_end block if_statement attribute identifier identifier block return_statement expression_statement assignment identifier binary_operator binary_operator binary_operator identifier strin... | Log a text without adding the current time. |
def remove_nesting(dom, tag_name):
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue
if ancestor is dom.documentElement:
break
if ancestor.tagName == tag_name:
unw... | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block for_statement identifier call identifier argument_list identifier block if_statement comparison_operator identifier identifier block continue_statemen... | Unwrap items in the node list that have ancestors with the same tag. |
def height(poly):
num = len(poly) - 1
if abs(poly[num][2] - poly[0][2]) > abs(poly[1][2] - poly[0][2]):
return dist(poly[num], poly[0])
elif abs(poly[num][2] - poly[0][2]) < abs(poly[1][2] - poly[0][2]):
return dist(poly[1], poly[0])
else:
return min(dist(poly[num], poly[0]), dis... | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer if_statement comparison_operator call identifier argument_list binary_operator subscript subscript identifier identifier integer subscript subscri... | Height of a polygon poly |
def clean_email(self):
email = self.cleaned_data.get("email")
qs = User.objects.exclude(id=self.instance.id).filter(email=email)
if len(qs) == 0:
return email
raise forms.ValidationError(
ugettext("This email is already registered")) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute attribute identifier... | Ensure the email address is not already registered. |
def __init_chunked_upload(self):
headers = {
'x-ton-content-type': self.content_type,
'x-ton-content-length': str(self._file_size),
'x-ton-expires': http_time(self.options.get('x-ton-expires', self._DEFAULT_EXPIRE)),
'content-length': str(0),
'content-... | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call identifier argument_list attribute identifier identifier pair... | Initialization for a multi-chunk upload. |
def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
with io.open(file_path, 'rb') as fh:
return guess_file_encoding(fh, default=default) | module function_definition identifier parameters identifier default_parameter identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block return_statement call i... | Wrapper to open that damn file for you, lazy bastard. |
def exit(self, signal=None, frame=None):
self.input_channel.close()
self.client_queue.close()
self.connection.close()
log.info("Worker exiting")
sys.exit(0) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list ... | Properly close the AMQP connections |
def execute(self, **kwargs):
headers = self.header.copy()
headers['soapaction'] = '%s
data = self.envelope.strip() % self._body_builder(kwargs)
url = 'http://%s:%s%s' % (self.address, self.port, self.control_url)
auth = None
if self.password:
auth=HTTPDigestAu... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end bina... | Calls the FritzBox action and returns a dictionary with the arguments. |
def sendgmail(self, subject, recipients, plaintext, htmltext=None, cc=None, debug=False, useMIMEMultipart=True, gmail_account = 'kortemmelab@gmail.com', pw_filepath = None):
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
g... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier true default_parameter identifier string string_start string_content string_end default_paramet... | For this function to work, the password for the gmail user must be colocated with this file or passed in. |
def value_loss(self, model, observations, discounted_rewards):
value_outputs = model.value(observations)
value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards)
return value_loss | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator float call attribute identifier identifier argument_list ... | Loss of value estimator |
def substring_search(query, list_of_strings, limit_results=DEFAULT_LIMIT):
matching = []
query_words = query.split(' ')
query_words.sort(key=len, reverse=True)
counter = 0
for s in list_of_strings:
target_words = s.split(' ')
if(anyword_substring_search(target_words, query_words)):
... | module function_definition identifier parameters identifier identifier default_parameter identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_stat... | main function to call for searching |
def palindromic_substrings_iter(s):
if not s:
yield []
return
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
for rest in palindromic_substrings_iter(s[i:]):
yield [sub] + rest | module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement yield list return_statement for_statement identifier call identifier argument_list call identifier argument_list identifier integer unary_operator integer block expression_statement assignme... | A slightly more Pythonic approach with a recursive generator |
def copy(self):
missing = object()
result = object.__new__(self.__class__)
for name in self.__slots__:
val = getattr(self, name, missing)
if val is not missing:
setattr(result, name, val)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifie... | Create a flat copy of the dict. |
def recentEvents(self):
return Event.objects.filter(
Q(pk__in=self.individualEvents.values_list('pk',flat=True)) |
Q(session__in=self.eventSessions.all()) |
Q(publicevent__category__in=self.eventCategories.all()) |
Q(series__category__in=self.seriesCategories.all(... | module function_definition identifier parameters identifier block return_statement call attribute call attribute attribute identifier identifier identifier argument_list binary_operator binary_operator binary_operator call identifier argument_list keyword_argument identifier call attribute attribute identifier identifi... | Get the set of recent and upcoming events to which this list applies. |
def gethash(compiled):
lines = compiled.splitlines()
if len(lines) < 3 or not lines[2].startswith(hash_prefix):
return None
else:
return lines[2][len(hash_prefix):] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list identifier integer not_operator call attribute subscript identifier integer iden... | Retrieve a hash from a header. |
def output_image(gandi, image, datacenters, output_keys, justify=14,
warn_deprecated=True):
for key in output_keys:
if key in image:
if (key == 'label' and image['visibility'] == 'deprecated' and
warn_deprecated):
image[key] = '%s /!\ DEPRECAT... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier integer default_parameter identifier true block for_statement identifier identifier block if_statement comparison_operator identifier identifier block if_statement parenthesized_expression boolean_o... | Helper to output a disk image. |
def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax):
refs = [bus._i for bus in buses if bus.type == REFERENCE]
Varefs = array([b.v_angle for b in buses if b.type == REFERENCE])
xmin[Va.i1 - 1 + refs] = Varefs
xmax[Va.iN - 1 + refs] = Varefs
return xmin, xmax | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier identifier express... | Adds a constraint on the reference bus angles. |
def _recv_timeout_loop(self):
while self._detect_time:
last_wait = time.time()
self._lock = hub.Event()
self._lock.wait(timeout=self._detect_time)
if self._lock.is_set():
if getattr(self, "_auth_seq_known", 0):
if last_wait > ti... | module function_definition identifier parameters identifier block while_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argum... | A loop to check timeout of receiving remote BFD packet. |
def merge_bytes(binder_strings):
output = None
for byte_string in binder_strings:
binder = Binder().from_bytes(byte_string)
if output is None:
output = binder
else:
output.merge(binder)
return output.to_bytes() | module function_definition identifier parameters identifier block expression_statement assignment identifier none for_statement identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier if_statement comparison_operator identif... | Concatenate multiple serialized binders into one byte string. |
def received_winch(self):
def process_winch():
if self._callbacks:
self._callbacks.terminal_size_changed()
self.call_from_executor(process_winch) | module function_definition identifier parameters identifier block function_definition identifier parameters block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argu... | Notify the event loop that SIGWINCH has been received |
def accounts(self) -> AccountsAggregate:
if not self.__accounts_aggregate:
self.__accounts_aggregate = AccountsAggregate(self.book)
return self.__accounts_aggregate | module function_definition identifier parameters identifier type identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | Returns the Accounts aggregate |
def edate(ctx, date, months):
return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx)) | module function_definition identifier parameters identifier identifier identifier block return_statement binary_operator call attribute identifier identifier argument_list identifier identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier identi... | Moves a date by the given number of months |
def from_(cls, gsim):
ltbranch = N('logicTreeBranch', {'branchID': 'b1'},
nodes=[N('uncertaintyModel', text=str(gsim)),
N('uncertaintyWeight', text='1.0')])
lt = N('logicTree', {'logicTreeID': 'lt1'},
nodes=[N('logicTreeBranchingLevel', {'b... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end keyword_argument... | Generate a trivial GsimLogicTree from a single GSIM instance. |
def read(self, path, encoding=None):
b = common.read(path)
if encoding is None:
encoding = self.file_encoding
return self.unicode(b, encoding) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attrib... | Read the template at the given path, and return it as a unicode string. |
def getMaskIndices(mask):
return [
list(mask).index(True), len(mask) - 1 - list(mask)[::-1].index(True)
] | module function_definition identifier parameters identifier block return_statement list call attribute call identifier argument_list identifier identifier argument_list true binary_operator binary_operator call identifier argument_list identifier integer call attribute subscript call identifier argument_list identifier... | get lower and upper index of mask |
def update_context(app, pagename, templatename, context, doctree):
if doctree is None:
return
visitor = _FindTabsDirectiveVisitor(doctree)
doctree.walk(visitor)
if not visitor.found_tabs_directive:
paths = [posixpath.join('_static', 'sphinx_tabs/' + f) for f in FILES]
if 'css_fil... | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identif... | Remove sphinx-tabs CSS and JS asset files if not used in a page |
def ftp_get(fin_src, fout):
assert fin_src[:6] == 'ftp://', fin_src
dir_full, fin_ftp = os.path.split(fin_src[6:])
pt0 = dir_full.find('/')
assert pt0 != -1, pt0
ftphost = dir_full[:pt0]
chg_dir = dir_full[pt0+1:]
print('FTP RETR {HOST} {DIR} {SRC} -> {DST}'.format(
HOST=ftphost, DIR... | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator subscript identifier slice integer string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier ... | Download a file from an ftp server |
def bound_elems(elems):
group_x0 = min(map(lambda l: l.x0, elems))
group_y0 = min(map(lambda l: l.y0, elems))
group_x1 = max(map(lambda l: l.x1, elems))
group_y1 = max(map(lambda l: l.y1, elems))
return (group_x0, group_y0, group_x1, group_y1) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list lambda lambda_parameters identifier attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list... | Finds the minimal bbox that contains all given elems |
def _parse_uri_ssh(unt):
if '@' in unt.netloc:
user, host_port = unt.netloc.split('@', 1)
else:
user, host_port = None, unt.netloc
if ':' in host_port:
host, port = host_port.split(':', 1)
else:
host, port = host_port, None
if not user:
user = None
if not ... | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_lis... | Parse a Uri from a urllib namedtuple. |
def initialize_logging(args):
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(
"%(levelname)s %(asctime)s %(name)s:%(lineno)04d - %(message)s")
log_handler.setFormatter(log_formatter)
root_logger = logging.getLogger()
root_logger.addHandler(log_handler)
root_logge... | 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 string string_start string_content string_end expression_statement... | Configure the root logger with some sensible defaults. |
def Handle(self, args, token=None):
if data_store.RelationalDBEnabled():
flow_iterator = iteritems(registry.FlowRegistry.FLOW_REGISTRY)
else:
flow_iterator = iteritems(registry.AFF4FlowRegistry.FLOW_REGISTRY)
result = []
for name, cls in sorted(flow_iterator):
if not getattr(cls, "cate... | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier else_clause b... | Renders list of descriptors for all the flows. |
def validate_metadata(self, handler):
if self.meta == 'category':
new_metadata = self.metadata
cur_metadata = handler.read_metadata(self.cname)
if (new_metadata is not None and cur_metadata is not None and
not array_equivalent(new_metadata, cur_metadata)):... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call att... | validate that kind=category does not change the categories |
def extract_emails(text):
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.findall(text):
emails.append(m[0])
return emails | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end expression_statement assignment identifier list for_... | Return a list of email addresses extracted from the string. |
def _print_code(self, code):
for key in self.variables.keys():
for arg in self.variables[key]:
code = code.replace(arg.name, 'self.'+arg.name)
return code | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block for_statement identifier subscript attribute identifier identifier identifier block expression_statement assignment identifier call attribut... | Prepare code for string writing. |
def mark_for_update(self):
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
push_key.delay(self) | module function_definition identifier parameters identifier block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identif... | Note that a change has been made so all Statuses need update |
def find_template(self, name):
deftemplate = lib.EnvFindDeftemplate(self._env, name.encode())
if deftemplate == ffi.NULL:
raise LookupError("Template '%s' not found" % name)
return Template(self._env, deftemplate) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier i... | Find the Template by its name. |
def read(self, address, size):
value = 0x0
for i in range(0, size):
value |= self._read_byte(address + i) << (i * 8)
return value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier integer for_statement identifier call identifier argument_list integer identifier block expression_statement augmented_assignment identifier binary_operator call attribute identifier identi... | Read arbitrary size content from memory. |
def format_who_when(fields):
offset = fields[3]
if offset < 0:
offset_sign = b'-'
offset = abs(offset)
else:
offset_sign = b'+'
offset_hours = offset // 3600
offset_minutes = offset // 60 - offset_hours * 60
offset_str = offset_sign + ('%02d%02d' % (offset_hours, offset_m... | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment ide... | Format a tuple of name,email,secs-since-epoch,utc-offset-secs as a string. |
def __set_config_value(self, key, value):
self.check_owner()
params = {"room": self.room_id, "config": to_json({key: value})}
resp = self.conn.make_api_call("setRoomConfig", params)
if "error" in resp:
raise RuntimeError(f"{resp['error'].get('message') or resp['error']}")
... | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_star... | Sets a value for a room config |
def makeAla(segID, N, CA, C, O, geo):
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
res = Residue... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attrib... | Creates an Alanine residue |
def merge(self, other):
new_node = self.copy()
new_node.size += other.size
new_node.instruction_addrs += other.instruction_addrs
if new_node.byte_string is None or other.byte_string is None:
new_node.byte_string = None
else:
new_node.byte_string += other.b... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment a... | Merges this node with the other, returning a new node that spans the both. |
def read(self, size=-1):
if size == 0:
return b''
elif size < 0:
from_buf = self._read_from_buffer()
self._current_pos = self._content_length
return from_buf + self._raw_reader.read()
if len(self._buffer) >= size:
return self._read_from... | module function_definition identifier parameters identifier default_parameter identifier unary_operator integer block if_statement comparison_operator identifier integer block return_statement string string_start string_end elif_clause comparison_operator identifier integer block expression_statement assignment identif... | Read up to size bytes from the object and return them. |
def _parse_xfs_info(data):
ret = {}
spr = re.compile(r'\s+')
entry = None
for line in [spr.sub(" ", l).strip().replace(", ", " ") for l in data.split("\n")]:
if not line:
continue
nfo = _xfs_info_get_kv(line)
if not line.startswith("="):
entry = nfo.pop(0)... | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier none for_statemen... | Parse output from "xfs_info" or "xfs_growfs -n". |
def _match_type(self, i):
self.col_match = self.RE_TYPE.match(self._source[i])
if self.col_match is not None:
self.section = "types"
self.el_type = CustomType
self.el_name = self.col_match.group("name")
return True
else:
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier identifier if_statement comparison_operator attribute identifier ... | Looks at line 'i' to see if the line matches a module user type def. |
def build_github_url(
repo,
branch=None,
path='requirements.txt',
token=None
):
repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/')
if not path:
path = 'requirements.txt'
if not branch:
branch = get_default_branch(repo)
url = 'https://raw.githubusercontent.com/... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier none block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list st... | Builds a URL to a file inside a Github repository. |
def _tseitin(ex, auxvarname, auxvars=None):
if isinstance(ex, Literal):
return ex, list()
else:
if auxvars is None:
auxvars = list()
lits = list()
constraints = list()
for x in ex.xs:
lit, subcons = _tseitin(x, auxvarname, auxvars)
lits... | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block return_statement expression_list identifier call identifier argument_list else_clause block if_statement comparison_operator identifier no... | Convert a factored expression to a literal, and a list of constraints. |
def update_pop(self):
candidates = []
for ind in self.population:
candidates.append(self.crossover(ind))
self._params['model_count'] += len(candidates)
self.assign_fitnesses(candidates)
for i in range(len(self.population)):
if candidates[i].fitness > self.... | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expressio... | Updates the population according to crossover and fitness criteria. |
def _init_org(self):
self.logger.info(
"Verifying and refreshing credentials for the specified org: {}.".format(
self.org_config.name
)
)
orig_config = self.org_config.config.copy()
self.org_config.refresh_oauth_token(self.project_config.keychain)
... | 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 attribute attribute identifier identifier identifier expression_statement a... | Test and refresh credentials to the org specified. |
def load_adjusted_array(self, domain, columns, dates, sids, mask):
out = {}
for col in columns:
try:
loader = self._loaders.get(col)
if loader is None:
loader = self._loaders[col.unspecialize()]
except KeyError:
... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier iden... | Load by delegating to sub-loaders. |
def simplices(self):
return [Simplex([self.points[i] for i in v]) for v in self.vertices] | module function_definition identifier parameters identifier block return_statement list_comprehension call identifier argument_list list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier identifier for_in_clause identifier attribute identifier identifier | Returns the simplices of the triangulation. |
def _get_package_path(self):
if not self.package:
return []
if not hasattr(self, 'package_path'):
m = __import__(self.package)
parts = self.package.split('.')[1:]
self.package_path = os.path.join(os.path.dirname(m.__file__), *parts)
return [self.pa... | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement list if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call i... | Gets the path of a Python package |
def even_mults(start:float, stop:float, n:int)->np.ndarray:
"Build log-stepped array from `start` to `stop` in `n` steps."
mult = stop/start
step = mult**(1/(n-1))
return np.array([start*(step**i) for i in range(n)]) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type attribute identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment ... | Build log-stepped array from `start` to `stop` in `n` steps. |
def staticdir():
root = os.path.abspath(os.path.dirname(__file__))
return os.path.join(root, "static") | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier ide... | Return the location of the static data directory. |
def visit_annassign(self, node):
target = node.target.accept(self)
annotation = node.annotation.accept(self)
if node.value is None:
return "%s: %s" % (target, annotation)
return "%s: %s = %s" % (target, annotation, node.value.accept(self)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list id... | Return an astroid.AugAssign node as string |
def handle_presentation(msg):
if msg.child_id == SYSTEM_CHILD_ID:
sensorid = msg.gateway.add_sensor(msg.node_id)
if sensorid is None:
return None
msg.gateway.sensors[msg.node_id].type = msg.sub_type
msg.gateway.sensors[msg.node_id].protocol_version = msg.payload
m... | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_o... | Process a presentation message. |
def raw_path_qs(self):
if not self.raw_query_string:
return self.raw_path
return "{}?{}".format(self.raw_path, self.raw_query_string) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement attribute identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attrib... | Encoded path of URL with query. |
def confusion_matrix(self):
confusion_matrix = self.pixel_classification_sum.astype(np.float)
confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T
return confusion_matrix * 100.0 | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute call attribute identifier identifier argument_list att... | Returns the normalised confusion matrix |
def read_mm_header(fh, byteorder, dtype, count, offsetsize):
mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder)
mmh = recarray2dict(mmh)
mmh['Dimensions'] = [
(bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip())
for d in mmh['Dimensions']]
d = mmh['GrayChannel']
... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier ca... | Read FluoView mm_header tag from file and return as dict. |
def delete_all_secrets(cls, user, client_id):
can_delete = yield cls(client_id=client_id).can_delete(user)
if not can_delete:
raise exceptions.Unauthorized('User may not delete {} secrets'
.format(client_id))
results = yield cls.view.get(key=... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier yield call attribute call identifier argument_list keyword_argument identifier identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call... | Delete all of the client's credentials |
def extract_stats(neurons, config):
stats = defaultdict(dict)
for ns, modes in config['neurite'].items():
for n in config['neurite_type']:
n = _NEURITE_MAP[n]
for mode in modes:
stat_name = _stat_name(ns, mode)
stat = eval_stats(nm.get(ns, neurons,... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list blo... | Extract stats from neurons |
def _match(self, regex):
cregex = re.compile(regex)
for line in self.content.splitlines():
match = cregex.match(line)
if match:
return match
raise Exception('No "{0}" line in {1}.cpp'.format(
regex_to_error_msg(regex),
self.name
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment ide... | Find the first line matching regex and return the match object |
def run(self):
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier if... | Increments counter and raises an exception for first two runs. |
def write_flash(self, addr, page_buffer, target_page, page_count):
pk = None
pk = self.link.receive_packet(0)
while pk is not None:
pk = self.link.receive_packet(0)
retry_counter = 5
while ((not pk or pk.header != 0xFF or
struct.unpack('<BB', pk.data[0... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier none expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer while_statement comparison_operator ide... | Initiate flashing of data in the buffer to flash. |
def create_hooks(use_tfdbg=False,
use_dbgprofile=False,
dbgprofile_kwargs=None,
use_validation_monitor=False,
validation_monitor_kwargs=None,
use_early_stopping=False,
early_stopping_kwargs=None):
train_hooks = []
... | module function_definition identifier parameters default_parameter identifier false default_parameter identifier false default_parameter identifier none default_parameter identifier false default_parameter identifier none default_parameter identifier false default_parameter identifier none block expression_statement as... | Create train and eval hooks for Experiment. |
def FilePattern(pattern, settings, **kwargs):
url = _urlparse(pattern)
if url.scheme == 'gs':
return GoogleStorageFilePattern(pattern, settings, **kwargs)
else:
assert url.scheme == 'file'
return LocalFilePattern(pattern, settings, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return... | Factory method returns LocalFilePattern or GoogleStorageFilePattern |
def create_index(self):
self.reset()
counter = 0
pre_time = time.time()
while True:
if counter % 1000 == 0:
cur_time = time.time()
print('time:', cur_time - pre_time, ' count:', counter)
pos = self.tell()
cont = self.rea... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list while_statement true block if_stateme... | Creates the index file from open record file |
def _production(self):
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other | module function_definition identifier parameters identifier block return_statement binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute ide... | Calculate total energy production. Not rounded |
def _set(self, value):
super(AttachmentsField, self)._set(value)
self._cursor = None | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier none | Override setter, allow clearing cursor |
def _load_config_file(self):
LOGGER.info('Loading configuration from %s', self._file_path)
if self._file_path.endswith('json'):
config = self._load_json_config()
else:
config = self._load_yaml_config()
for key, value in [(k, v) for k, v in config.items()]:
... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list string string_start... | Load the configuration file into memory, returning the content. |
def _requested_name(self, name, action=None, func=None):
if name is not None:
if name in self._used_names:
n = 2
while True:
pn = name + '_' + str(n)
if pn not in self._used_names:
self._used_names.add(pn... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identi... | Create a unique name for an operator or a stream. |
def _get_comments_to_export(self, last_export_id=None):
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=last_e... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end line... | Return comments which should be exported. |
def _git_dir(repo, path):
name = "%s" % (path,)
if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']:
return repo.git_dir
return repo.common_dir | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string... | Find the git dir that's appropriate for the path |
def _center_window(self, result, window):
if self.axis > result.ndim - 1:
raise ValueError("Requested axis is larger then no. of argument "
"dimensions")
offset = _offset(window, True)
if offset > 0:
if isinstance(result, (ABCSeries, ABCDataFr... | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier binary_operator attribute identifier identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content stri... | Center the result in the window. |
def _put(self, uri, data):
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("BODY=" + json.dumps(data))
response = self.session.put(uri, headers=headers,
data=json.dumps(data))
if response.status_code in [201, 204]:
return d... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call... | Simple PUT operation for a given path. |
def _toggle_term_protect(name, value):
instance_id = _get_node(name)['instanceId']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id,
'DisableApiTermination.Value': value}
result = aws.query(params,
location=get_location(),
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_en... | Enable or Disable termination protection on a node |
def classify(self, table, weighted_choice=False, transform=None):
assert table.shape[1] == self.numgrp
if weighted_choice:
if transform is not None:
probs = transform_fn(table.copy(), transform)
else:
probs = table.copy()
cmprobs = prob... | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier none block assert_statement comparison_operator subscript attribute identifier identifier integer attribute identifier identifier if_statement identifier block if_statement comparison_o... | The Classification step of the CEM algorithm |
def _validate_operator_name(operator, supported_operators):
if not isinstance(operator, six.text_type):
raise TypeError(u'Expected operator as unicode string, got: {} {}'.format(
type(operator).__name__, operator))
if operator not in supported_operators:
raise GraphQLCompilationError... | module function_definition identifier parameters identifier 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 attrib... | Ensure the named operator is valid and supported. |
def sameAddr(self, ha, ha2) -> bool:
if ha == ha2:
return True
if ha[1] != ha2[1]:
return False
return ha[0] in self.localips and ha2[0] in self.localips | module function_definition identifier parameters identifier identifier identifier type identifier block if_statement comparison_operator identifier identifier block return_statement true if_statement comparison_operator subscript identifier integer subscript identifier integer block return_statement false return_statem... | Check whether the two arguments correspond to the same address |
def union(self, other):
return Interval(min(self.low, other.low), max(self.high, other.high)) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier | Intersect current range with other. |
def tags(self):
tags = self.workbench.get_all_tags()
if not tags:
return
tag_df = pd.DataFrame(tags)
tag_df = self.vectorize(tag_df, 'tags')
print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal)
self.top_corr(tag_df) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block return_statement expression_statement assignment identifier call attribute identifier identifier... | Display tag information for all samples in database |
def extract_metrics(self, metrics_files):
extension_maps = dict(
align_metrics=(self._parse_align_metrics, "AL"),
dup_metrics=(self._parse_dup_metrics, "DUP"),
hs_metrics=(self._parse_hybrid_metrics, "HS"),
insert_metrics=(self._parse_insert_metrics, "INS"),
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier tuple attribute identifier identifier string string_start string_content string_end keyword_argument identifier tuple attribute identifier ide... | Return summary information for a lane of metrics files. |
def total_write_throughput(self):
total = self.write_throughput
for index in itervalues(self.global_indexes):
total += index.write_throughput
return total | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement augmented_assignment identifier attribute identifier identifier r... | Combined write throughput of table and global indexes |
def dedent(s):
head, _, tail = s.partition('\n')
dedented_tail = textwrap.dedent(tail)
result = "{head}\n{tail}".format(
head=head,
tail=dedented_tail)
return result | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute ident... | Removes the hanging dedent from all the first line of a string. |
def mtf_unitransformer_base():
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("num_memory_heads", 0)
hparams.add_hparam("shared_kv", False)
hparams.add_hparam("local_at... | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end true expression_statement call attribute identifier identifier argument_li... | Hyperparameters for single-stack Transformer. |
def nonwhitelisted_allowed_principals(self, whitelist=None):
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect == "Allow":
nonwhitelisted.append(stateme... | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block return_statement list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement boolean_operator call attribute... | Find non whitelisted allowed principals. |
def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
if self.logger:
self.logger.info("Reading %s", self.path)
self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)
self.reportProgress("done", 'stop') | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier true default_parameter identifier true block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string s... | Process the input file and generate the instances. |
def declare_namespace(packageName):
_imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path = sys.path
parent, _, _ = packageName.rpartition('.')
if parent:
declare_namespace(parent)
if parent not in _namespace_packages:
... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list try_statement block if_statement comparison_operator identifier identifier block return_statement expression_statement assignment identifier attribute identifier identifier expressio... | Declare that package 'packageName' is a namespace package |
def add_menu(self, name, link=None):
if self.menu_began:
if self.menu_separator_tag:
self.write(self.menu_separator_tag)
else:
self.write('<ul class="horizontal">')
self.menu_began = True
self.write('<li>')
if link:
self.wri... | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier els... | Adds a menu entry, will create it if it doesn't exist yet |
def _convertTZ(self):
tz = timezone.get_current_timezone()
dtstart = self['DTSTART']
dtend = self['DTEND']
if dtstart.zone() == "UTC":
dtstart.dt = dtstart.dt.astimezone(tz)
if dtend.zone() == "UTC":
dtend.dt = dtend.dt.astimezone(tz) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscri... | Will convert UTC datetimes to the current local timezone |
def include_raw_constructor(self, loader, node):
path = convert_path(node.value)
with open(path, 'r') as f:
config = f.read()
config = self.inject_include_info(path, config, include_type='include-raw')
self.add_file(path, config)
return config | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content str... | Called when PyYaml encounters '!include-raw' |
def strip_ip_port(ip_address):
if '.' in ip_address:
cleaned_ip = ip_address.split(':')[0]
elif ']:' in ip_address:
cleaned_ip = ip_address.rpartition(':')[0][1:-1]
else:
cleaned_ip = ip_address
return cleaned_ip | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer ... | Strips the port from an IPv4 or IPv6 address, returns a unicode object. |
def _get_cu_and_fu_status(self):
headers = HEADERS.copy()
headers['Accept'] = '*/*'
headers['X-Requested-With'] = 'XMLHttpRequest'
headers['X-CSRFToken'] = self._parent.csrftoken
args = '?controller_serial=' + self.serial \
+ '&faucet_serial=' + self.faucet.serial
... | 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 string string_start string_content string_end expression_stat... | Submit GET request to update information. |
def retract(self, e, a, v):
ta = datetime.datetime.now()
ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v))
rs = self.tx(ret)
tb = datetime.datetime.now() - ta
print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan')
return rs | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end t... | redact the value of an attribute |
def populateFromRow(self, callSetRecord):
self._biosampleId = callSetRecord.biosampleid
self.setAttributesJson(callSetRecord.attributes) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Populates this CallSet from the specified DB row. |
def parse_output(self, line):
try:
key, value = line.split(":")
self.update_value(key.strip(), value.strip())
except ValueError:
pass | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier a... | Convert output to key value pairs |
def combine_recs(rec_list, key):
final_recs = {}
for rec in rec_list:
rec_key = rec[key]
if rec_key in final_recs:
for k, v in rec.iteritems():
if k in final_recs[rec_key] and final_recs[rec_key][k] != v:
raise Exception("Mis-match for key '%s'" % ... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier identifier block for_stateme... | Use a common key to combine a list of recs |
def worker(namespace, name, branch='master'):
with repository(namespace, name, branch) as (path, latest, cache):
if cache.get(latest, None) and json.loads(cache[latest])['status'] != 'starting':
return 'Build already started'
data = {'status': 'in_progress', 'result': ''}
cache[l... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier identifier as_pattern_target tuple identifier identifier identifier ... | The simple_ci background worker process |
def possible_completions(self, e):
u
completions = self._get_completions()
self._display_completions(completions)
self.finalize() | module function_definition identifier parameters identifier identifier block expression_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribut... | u"""List the possible completions of the text before point. |
def strictly_increasing(values):
return all(x < y for x, y in zip(values, values[1:])) | module function_definition identifier parameters identifier block return_statement call identifier generator_expression comparison_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier subscript identifier slice integer | True if values are stricly increasing. |
def cli(env):
table = formatting.Table([
'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'
])
table.align['Name'] = 'l'
table.align['Package Name'] = 'r'
table.align['Package Id'] = 'l'
manager = ordering.OrderingManager(env.client)
items = manager.get_quo... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_sta... | List all active quotes on an account |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.