code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def months_ago(date, nb_months=1):
nb_years = nb_months // 12
nb_months = nb_months % 12
month_diff = date.month - nb_months
if month_diff > 0:
new_month = month_diff
else:
new_month = 12 + month_diff
nb_years += 1
return date.replace(day=1, month=new_month, year=date.yea... | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator at... | Return the given `date` with `nb_months` substracted from it. |
def _fill_argparser(self, parser):
for key, val in self._options.items():
add_argument(parser, key, val) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier | Fill an `argparser.ArgumentParser` with the options from this chain |
def callHook(self, hookname, *args, **kwargs):
'Call all functions registered with `addHook` for the given hookname.'
r = []
for f in self.hooks[hookname]:
try:
r.append(f(*args, **kwargs))
except Exception as e:
exceptionCaught(e)
... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list for_statement identifier subscript attribute identifier identi... | Call all functions registered with `addHook` for the given hookname. |
def get(self):
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
self.mutex.release()
return None
tas... | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list integer block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list expression_statemen... | Get a task from queue when bucket available |
def recursively_resume_states(self):
super(ContainerState, self).recursively_resume_states()
for state in self.states.values():
state.recursively_resume_states() | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute id... | Resume the state and all of it child states. |
def toListInt(value):
if TypeConverters._can_convert_to_list(value):
value = TypeConverters.toList(value)
if all(map(lambda v: TypeConverters._is_integer(v), value)):
return [int(v) for v in value]
raise TypeError("Could not convert %s to list of ints" % value) | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list call identifier argument_... | Convert a value to list of ints, if possible. |
def delete_name(name):
session = create_session()
try:
user = session.query(User).filter_by(name=name).first()
session.delete(user)
session.commit()
except SQLAlchemyError, e:
session.rollback()
raise bottle.HTTPError(500, "Database Error", e)
finally:
ses... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list try_statement block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list k... | This function don't use the plugin. |
def contour_mask(self, contour):
new_data = np.zeros(self.data.shape)
num_boundary = contour.boundary_pixels.shape[0]
boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2])
boundary_px_ij_swapped[:, 0, 0] = contour.boundary_pixels[:, 1]
boundary_px_ij_swapped[:, 0, 1] = contour.... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier subscript attribute attribute identifier identifier i... | Generates a binary image with only the given contour filled in. |
def verify_email(self, action_token, signed_data):
try:
action = "verify-email"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
raise mocha_exc.AppError("Verification Invalid!")
... | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier if_statement boolean_operato... | Verify email account, in which a link was sent to |
def stop(self, sig=signal.SIGINT):
for cpid in self.sandboxes:
logger.warn('Stopping %i...' % cpid)
try:
os.kill(cpid, sig)
except OSError:
logger.exception('Error stopping %s...' % cpid)
for cpid in list(self.sandboxes):
tr... | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_... | Stop all the workers, and then wait for them |
def generate_ngrams(args, parser):
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
if args.catalogue:
catalogue = utils.get_catalogue(args)
else:
catalogue = None
store.add_ngrams(corpus, args.min_size, args.max_size, catalogue) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier... | Adds n-grams data to the data store. |
def load(config_file):
with open(config_file, "r") as f:
def env_get():
return dict(os.environ)
tmpl = Template(f.read())
return Config(yaml.load(tmpl.render(**env_get()))) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block function_definition identifier parameters block return_statement call identifier arg... | Processes and loads config file. |
def crop_to_sheet(self,sheet_coord_system):
"Crop the slice to the SheetCoordinateSystem's bounds."
maxrow,maxcol = sheet_coord_system.shape
self[0] = max(0,self[0])
self[1] = min(maxrow,self[1])
self[2] = max(0,self[2])
self[3] = min(maxcol,self[3]) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment subscript identifier integer call identifier ... | Crop the slice to the SheetCoordinateSystem's bounds. |
def removeIndividual(self, individual):
q = models.Individual.delete().where(
models.Individual.id == individual.getId())
q.execute() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list comparison_operator attribute attribute identifier identifier identifier call attribute ... | Removes the specified individual from this repository. |
def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
for database_column, (section, key) in mapping.items():
if section in bel_resource and key in bel_resource[section]:
values[database_column] = bel_resource[section][key] | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type generic_type identifier type_para... | Update the value dictionary with a BEL resource dictionary. |
def allow_user(user):
def processor(action, argument):
db.session.add(
ActionUsers.allow(action, argument=argument, user_id=user.id)
)
return processor | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier i... | Allow a user identified by an email address. |
def output_vlan(gandi, vlan, datacenters, output_keys, justify=10):
output_generic(gandi, vlan, output_keys, justify)
if 'dc' in output_keys:
for dc in datacenters:
if dc['id'] == vlan.get('datacenter_id',
vlan.get('datacenter', {}).get('id')):
... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier integer block expression_statement call identifier argument_list identifier identifier identifier identifier if_statement comparison_operator string string_start string_content string_end identifier... | Helper to output a vlan information. |
def submit_url(self, url, params={}, _extra_params={}):
self._check_user_parameters(params)
params = copy.copy(params)
params['url'] = url
return self._submit(params, _extra_params=_extra_params) | module function_definition identifier parameters identifier identifier default_parameter identifier dictionary default_parameter identifier dictionary block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier ... | Submit a website for analysis. |
def data_context(fn, mode="r"):
with open(data_context_name(fn), mode) as f:
return f.read() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list call identifier argument_list identifier identifier as_pattern_target identifier block return_stateme... | Return content fo the `fn` from the `template_data` directory. |
def customer(self):
url = self._get_link('customer')
if url:
resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)
return Customer(resp) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute attribute attribute identi... | Return the customer for this subscription. |
def gather_metrics(self, runs):
for run_dirs in runs.values():
with open(JSON_METRICS_FILE, 'w') as ostr:
ostr.write('[\n')
for i in range(len(run_dirs)):
with open(osp.join(run_dirs[i], YAML_REPORT_FILE)) as istr:
data = ya... | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifi... | Write a JSON file with the result of every runs |
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted):
self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr)
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1])) | module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end subscript attribute identifier identifier integer subscript a... | Handle an AgentJobStarted message. Send the data back to the client |
def meth_acl(args):
r = fapi.get_repository_method_acl(args.namespace, args.method,
args.snapshot_id)
fapi._check_response_code(r, 200)
acls = sorted(r.json(), key=lambda k: k['user'])
return map(lambda acl: '{0}\t{1}'.format(acl['user'], acl['role']),... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argume... | Retrieve access control list for given version of a repository method |
def _compute_fval(X, A, R, P, Z, lmbdaA, lmbdaR, lmbdaZ, normX):
f = lmbdaA * norm(A) ** 2
for i in range(len(X)):
ARAt = dot(A, dot(R[i], A.T))
f += (norm(X[i] - ARAt) ** 2) / normX[i] + lmbdaR * norm(R[i]) ** 2
return f | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier binary_operator call identifier argument_list identifier integer for_statement identifier call i... | Compute fit for full slices |
def browse_outdir(self):
self.dirsel.popup(
'Select directory', self.w.outdir.set_text, initialdir=self.outdir)
self.set_outdir() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute ide... | Browse for output directory. |
def to_datetime(t):
if t is None:
return None
year, mon, day, h, m, s = t
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
pass
mday = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if mon < 1:
mon = 1
if mon > 12:
mon = 12
if ... | module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement none expression_statement assignment pattern_list identifier identifier identifier identifier identifier identifier identifier try_statement block return_statement call identifier ar... | Convert 6-part time tuple into datetime object. |
def total(self):
total = 0
for item in self.items.all():
total += item.total
return total | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement augmented_assignment identifier attribute identifier identifier return_statemen... | Total cost of the order |
def from_kwargs(cls, **kwargs):
config = cls()
for slot in cls.__slots__:
if slot.startswith('_'):
slot = slot[1:]
setattr(config, slot, kwargs.pop(slot, cls.get_default(slot)))
if kwargs:
raise ValueError("Unrecognized option(s): {}".format(kw... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_star... | Initialise configuration from kwargs. |
def delete(self):
res = self.session.delete(self.href)
self.emit('deleted', self)
return res | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content ... | Delete resource from the API server |
def super_mro(self):
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
"type, not {mro_pointer}.",
super_=self,
)
if isinstance(self.type, sc... | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string... | Get the MRO which will be used to lookup attributes in this super. |
def insert(self, space_no, *args):
d = self.replyQueue.get()
packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier iden... | insert tuple, if primary key exists server will return error |
def server_link(rel, server_id=None, self_rel=False):
servers_href = '/v1/servers'
link = _SERVER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute subscript identifier identifier identi... | Helper for getting a Server link document, given a rel. |
def connect_to_cloud_cdn(region=None):
global default_region
if region in ['DFW', 'IAD', 'ORD', 'SYD', 'HKG']:
return _create_client(ep_name="cdn", region="DFW")
elif region in ['LON']:
return _create_client(ep_name="cdn", region="LON")
else:
if default_region in ['DFW', 'IAD', '... | module function_definition identifier parameters default_parameter identifier none block global_statement identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_st... | Creates a client for working with cloud loadbalancers. |
def GetClosestPoint(x, a, b):
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
p = x.Minus(
a_cross_b.Times(
x.DotProd(a_cross_b) / a_cross_b.Norm2()))
if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b):
return p.Normalize(... | module function_definition identifier parameters identifier identifier identifier block assert_statement parenthesized_expression call attribute identifier identifier argument_list assert_statement parenthesized_expression call attribute identifier identifier argument_list assert_statement parenthesized_expression call... | Returns the point on the great circle segment ab closest to x. |
def layer_tagger_mapping(self):
return {
PARAGRAPHS: self.tokenize_paragraphs,
SENTENCES: self.tokenize_sentences,
WORDS: self.tokenize_words,
ANALYSIS: self.tag_analysis,
TIMEXES: self.tag_timexes,
NAMED_ENTITIES: self.tag_named_entities,
... | module function_definition identifier parameters identifier block return_statement dictionary pair identifier attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifi... | Dictionary that maps layer names to taggers that can create that layer. |
def btc_is_p2wpkh_address( address ):
wver, whash = segwit_addr_decode(address)
if whash is None:
return False
if len(whash) != 20:
return False
return True | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement false if_statement comparison_operator call identifier argument_list ident... | Is the given address a p2wpkh address? |
def tag(self, tagname, message=None, force=True):
return git_tag(self.repo_dir, tagname, message=message, force=force) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier true block return_statement call identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Create an annotated tag. |
def convert_output_to_v4(self, controller_input):
player_input = SimpleControllerState()
player_input.throttle = controller_input[0]
player_input.steer = controller_input[1]
player_input.pitch = controller_input[2]
player_input.yaw = controller_input[3]
player_input.roll ... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier subscript identifier integer expression_statement assignment attribute identifier identifier subscript ide... | Converts a v3 output to a v4 controller state |
def send(self, message):
log.debug("sending '{0}' message".format(message.type))
send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU)
try:
data = str(message)
except nfc.llcp.EncodeError as e:
log.error("message encoding failed: {0}".format(e))
else:
... | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attri... | Send a handover request message to the remote server. |
def _match_minimum_date_time(self, match_key, date_time_value, match=True):
if match:
gtelt = '$gte'
else:
gtelt = '$lt'
if match_key in self._query_terms:
self._query_terms[match_key][gtelt] = date_time_value
else:
self._query_terms[match_... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block if_statement identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_star... | Matches a minimum date time value |
def simhash(self, content):
if content is None:
self.hash = -1
return
if isinstance(content, str):
features = self.tokenizer_func(content, self.keyword_weight_pari)
self.hash = self.build_from_features(features)
elif isinstance(content, collections... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier unary_operator integer return_statement if_statement call identifier argument_list identifier identifier block expression_st... | Select policies for simhash on the different types of content. |
def _common_prefix(names):
if not names:
return ''
prefix = names[0]
for name in names:
i = 0
while i < len(prefix) and i < len(name) and prefix[i] == name[i]:
i += 1
prefix = prefix[:i]
return prefix | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement string string_start string_end expression_statement assignment identifier subscript identifier integer for_statement identifier identifier block expression_statement assignment identifier intege... | Get the common prefix for all names |
def elements(self):
offset = self.EXTRA_DIGITS
if offset:
return (self._id[:offset], self.company_prefix, self._reference,
self.check_digit)
else:
return (self.company_prefix, self._reference, self.check_digit) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement identifier block return_statement tuple subscript attribute identifier identifier slice identifier attribute identifier identifier attribute identifier identifier att... | Return the identifier's elements as tuple. |
def add_contact(self):
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') | module function_definition identifier parameters identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end keyword_argument identif... | Create a contact with using the email on the list. |
async def _wrap_ws(self, handler, *args, **kwargs):
try:
method = self.request_method()
data = await handler(self, *args, **kwargs)
status = self.responses.get(method, OK)
response = {
'type': 'response',
'key': getattr(self.request... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier await call identifie... | wraps a handler by receiving a websocket request and returning a websocket response |
def api_send_mail(request, key=None, hproPk=None):
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
sender = request.POST.get('sender', settings.MAIL_SENDER)
dests = request.POST.getlist('dests')
subject = request.POST['subject']
message = request.POST['message']
... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement not_operator call identifier argument_list identifier identifier identifier block return_statement identifier expression_statement assignment identifier call attribute attri... | Send a email. Posts parameters are used |
def explain_weights_sklearn(estimator, vec=None, top=_TOP,
target_names=None,
targets=None,
feature_names=None, coef_scale=None,
feature_re=None, feature_filter=None):
return explain_weights_sklearn_not_s... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_paramete... | Return an explanation of an estimator |
def _init_server_authentication(self, ssl_verify: OpenSslVerifyEnum, ssl_verify_locations: Optional[str]) -> None:
self._ssl_ctx.set_verify(ssl_verify.value)
if ssl_verify_locations:
with open(ssl_verify_locations):
pass
self._ssl_ctx.load_verify_locations(ssl_ver... | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type none block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier ... | Setup the certificate validation logic for authenticating the server. |
def match_to_dict(self, match, gids):
values = {}
for gid in gids:
try:
values[gid] = self.map_value(match.group(gid), gid)
except IndexError:
pass
return values | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block try_statement block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list c... | Map values from match into a dictionary. |
def handle_modifier_down(self, modifier):
_logger.debug("%s pressed", modifier)
if modifier in (Key.CAPSLOCK, Key.NUMLOCK):
if self.modifiers[modifier]:
self.modifiers[modifier] = False
else:
self.modifiers[modifier] = True
else:
... | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier tuple attribute identifier identifier attribute identifier identifier ... | Updates the state of the given modifier key to 'pressed' |
def update(self, other):
Cluster.update(self, other)
self.rules.extend(other.rules) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Extend the current cluster with data from another cluster |
def text_extract(path, password=None):
pdf = Info(path, password).pdf
return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())] | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier attribute call identifier argument_list identifier identifier identifier return_statement list_comprehension call attribute call attribute identifier identifier argument_list id... | Extract text from a PDF file |
def paintEvent(self, event):
if self.isVisible() and self.position != self.Position.FLOATING:
self._background_brush = QBrush(QColor(
self.editor.sideareas_color))
self._foreground_pen = QPen(QColor(
self.palette().windowText().color()))
painte... | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment attribute identifie... | Fills the panel background using QPalette. |
def _twig_to_uniqueid(bundle, twig, **kwargs):
res = bundle.filter(twig=twig, force_ps=True, check_visible=False, check_default=False, **kwargs)
if len(res) == 1:
return res.to_list()[0].uniqueid
else:
raise ValueError("did not return a single unique match to a parameter for '{}'".format(twi... | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier false keyword... | kwargs are passed on to filter |
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info):
log_level = log_levels[log_level]
conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path)
try:
conn.connect(force_discovery=force_discovery)
if print_info:
... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start... | Run the main function. |
def run_friedman_smooth(x, y, span):
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier ... | Run the FORTRAN smoother. |
def job_exists(self, prov):
with self.lock:
self.cur.execute('select * from "jobs" where "prov" = ?;', (prov,))
rec = self.cur.fetchone()
return rec is not None | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end tuple identifier expression_s... | Check if a job exists in the database. |
def _resizeCurrentColumnToContents(self, new_index, old_index):
if new_index.column() not in self._autosized_cols:
self._resizeVisibleColumnsToContents()
self.dataTable.scrollTo(new_index) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute at... | Resize the current column to its contents. |
def reopen(args):
if not args.isadmin:
return "Nope, not gonna do it."
msg = args.msg.split()
if not msg:
return "Syntax: !poll reopen <pollnum>"
if not msg[0].isdigit():
return "Not a valid positve integer."
pid = int(msg[0])
poll = get_open_poll(args.session, pid)
i... | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement... | reopens a closed poll. |
def _file_path(self, src_path, dest, regex):
m = re.search(regex, src_path)
if dest.endswith('/') or dest == '':
dest += '{filename}'
names = m.groupdict()
if not names and m.groups():
names = {'filename': m.groups()[-1]}
for name, value in names.items():
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement boolean_operator call attribute identifier identifier argument_list string string_start stri... | check src_path complies with regex and generate new filename |
def encode(data, mime_type='', charset='utf-8', base64=True):
if isinstance(data, six.text_type):
data = data.encode(charset)
else:
charset = None
if base64:
data = utils.text(b64encode(data))
else:
data = utils.text(quote(data))
result = ['data:', ]
if mime_type:... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_content string_end default_parameter identifier true block if_statement call identifier argument_list identifier attribute identifier identifier... | Encode data to DataURL |
def unknown_command(self, args):
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mode_mapping:
self.master.set_mode(mode_mapping[mode])
return True
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list if_statement com... | handle mode switch by mode name as command |
def apseudo(Ss, ipar, sigma):
Is = random.randint(0, len(Ss) - 1, size=len(Ss))
if not ipar:
BSs = Ss[Is]
else:
A, B = design(6)
K, BSs = [], []
for k in range(len(Ss)):
K.append(np.dot(A, Ss[k][0:6]))
Pars = np.random.normal(K, sigma)
for k in ran... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer binary_operator call identifier argument_list identifier integer keyword_argument identifier call identifier argument_list identif... | draw a bootstrap sample of Ss |
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
self.log_count += 1
log_valid = (
valid_loader is not None
and self.valid_every_X
and not (self.log_count % self.valid_every_X)
)
metrics_dict = {}
if self.config["lo... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier parenthesized_expression boolean_operator boolean_operator comparison_operator identi... | Add standard and custom metrics to metrics_dict |
def create_command(self, name, operation, **kwargs):
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.split())
client_factory = kwargs.get('client_factory', None)
def _command_handl... | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern 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_con... | Constructs the command object that can then be added to the command table |
def service(self, name: str = None):
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return lambda x: x
def wrapper(service):
self.register_service... | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier none block if_statement attribute identifier identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement call identifier argument_list concatenated_string string s... | Decorator to mark something as a service. |
def new_revision(self, *fields):
if not self._id:
assert g.get('draft'), \
'Only draft documents can be assigned new revisions'
else:
with self.draft_context():
assert self.count(Q._id == self._id) == 1, \
'Only draft do... | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator attribute identifier identifier block assert_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end ... | Save a new revision of the document |
def construct(self, uri, *args, **kw):
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", uri))
return self.resolved[uri]
... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifi... | Wrapper to debug things |
def files_in_path(path):
aggregated_files = []
for dir_, _, files in os.walk(path):
for file in files:
relative_dir = os.path.relpath(dir_, path)
if ".git" not in relative_dir:
relative_file = os.path.join(relative_dir, file)
aggregated_files.appen... | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block for_statement identifier identifier block expression_statement assignment iden... | Return a list of all files in a path but exclude git folders. |
def get(self, block=True, timeout=None):
value = self._queue.get(block, timeout)
if self._queue.empty():
self.clear()
return value | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier ... | Removes and returns an item from the queue. |
def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
data = list_records_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier integer default_parameter identifier integer default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block exp... | List all BuildRecords for a given Project |
def colorbar(height, length, colormap):
cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
cbar = (cbar * (colormap.values.max() - colormap.values.min())
+ colormap.values.min())
return colormap.colorize(cbar) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator call attribute identifier identifier argument_list identifier float parenthesized_expression binary_operat... | Return the channels of a colorbar. |
def reply_bytes(self, request):
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_id = random.randint(0, 1000000)
response_to = request.request_id... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier id... | Take a `Request` and return an OP_MSG message as bytes. |
def _from_dict(cls, _dict):
args = {}
if 'models' in _dict:
args['models'] = [
SpeechModel._from_dict(x) for x in (_dict.get('models'))
]
else:
raise ValueError(
'Required property \'models\' not present in SpeechModels JSON')
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content strin... | Initialize a SpeechModels object from a json dictionary. |
def astype(self, type_name):
if type_name == 'nddata':
return self.as_nddata()
if type_name == 'hdu':
return self.as_hdu()
raise ValueError("Unrecognized conversion type '%s'" % (type_name)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content ... | Convert AstroImage object to some other kind of object. |
def select(self, table, cols, execute=True, select_type='SELECT', return_type=list):
select_type = select_type.upper()
assert select_type in SELECT_QUERY_TYPES
statement = '{0} {1} FROM {2}'.format(select_type, join_cols(cols), wrap(table))
if not execute:
return statement
... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier string string_start string_content string_end default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier arg... | Query every row and only certain columns from a table. |
def decode(hashcode, delta=False):
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 90.0/(1 << lat_length)
longitude_delta = 180.0/(1 << lon_length)
latitude = _int_to_float_hex(lat, lat_length) * 90.0 + latitude_delta
longit... | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list identifier if_statement call identifier argument_list identifier string string_start string_content ... | decode a hashcode and get center coordinate, and distance between center and outer border |
def apply_interceptors(work_db, enabled_interceptors):
names = (name for name in interceptor_names() if name in enabled_interceptors)
for name in names:
interceptor = get_interceptor(name)
interceptor(work_db) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier generator_expression identifier for_in_clause identifier call identifier argument_list if_clause comparison_operator identifier identifier for_statement identifier identifier block expression_statemen... | Apply each registered interceptor to the WorkDB. |
def send(self, *args):
for frame in args:
self.sock.sendall(self.apply_send_hooks(frame, False).pack()) | module function_definition identifier parameters identifier list_splat_pattern identifier block for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier false identi... | Send a number of frames. |
def from_etree(
el, node=None, node_cls=None,
tagsub=functools.partial(re.sub, r'\{.+?\}', ''),
Node=Node):
node_cls = node_cls or Node
if node is None:
node = node_cls()
tag = tagsub(el.tag)
attrib = dict((tagsub(k), v) for (k, v) in el.attrib.items())
node.update(attrib, tag=ta... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_end def... | Convert the element tree to a tater tree. |
def update(self, **kwargs):
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
elif 'monitor' in self.__dict__:
value = self._format_monitor_parameter(self.__dict__['monitor'])
self.__dict__['monitor... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string ... | Custom update method to implement monitor parameter formatting. |
def secretfile_args(parser):
parser.add_argument('--secrets',
dest='secrets',
help='Path where secrets are stored',
default=os.path.join(os.getcwd(), ".secrets"))
parser.add_argument('--policies',
dest='policies',
... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content... | Add Secretfile management command line arguments to parser |
def bind(renderer, to):
@wraps(to)
def view(request, **kwargs):
try:
returned = to(request, **kwargs)
except Exception as error:
view_error = getattr(renderer, "view_error", None)
if view_error is None:
raise
return view_error(reque... | module function_definition identifier parameters identifier identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call identifi... | Bind a renderer to the given callable by constructing a new rendering view. |
def Contradiction(expr1: Expression, expr2: Expression) -> Expression:
expr = Disjunction(Conjunction(expr1, Negation(expr2)),
Conjunction(Negation(expr1), expr2))
return ast.fix_missing_locations(expr) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier call ide... | Return expression which is the contradiction of `expr1` and `expr2`. |
def to_rdkit_molecule(data):
mol = RWMol()
conf = Conformer()
mapping = {}
is_3d = False
for n, a in data.atoms():
ra = Atom(a.number)
ra.SetAtomMapNum(n)
if a.charge:
ra.SetFormalCharge(a.charge)
if a.isotope != a.common_isotope:
ra.SetIsotope... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary expression_statement assignment identifier false for_s... | MoleculeContainer to RDKit molecule object converter |
def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs):
warnings.warn(message, category, stacklevel=s... | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier identifier typed_default_parameter identifier type identifier integer type generic_type identifier type_parameter type list identifier type identifier block function_definition ... | Return a decorator which adds a warning to functions. |
def do_api_calls_update_cache(self):
zones = self.parse_env_zones()
data = self.group_instances(zones)
self.cache.write_to_cache(data)
self.inventory = data | 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 identifier expression_statement call attribute attribute identifie... | Do API calls and save data in cache. |
def _calc_distortion(self):
m = self._X.shape[0]
self.distortion = 1/m * sum(
linalg.norm(self._X[i, :] - self.centroids[self.clusters[i]])**2 for i in range(m)
)
return self.distortion | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer expression_statement assignment attribute identifier identifier binary_operator binary_operator integer identifier call identifier generator... | Calculates the distortion value of the current clusters |
def acquire_node(self, node):
try:
return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
return False | module function_definition identifier parameters identifier identifier block try_statement block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier attribute identifier identifie... | acquire a single redis node |
def _cast_number(value):
"Convert numbers as string to an int or float"
m = FLOAT_REGEX.search(value)
if m is not None:
return float(value)
return int(value) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement call ident... | Convert numbers as string to an int or float |
def stream(self, request, counter=0):
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | module function_definition identifier parameters identifier identifier default_parameter identifier integer block if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement ... | Returns an iterable over strings. |
def _build_line(colwidths, colaligns, linefmt):
"Return a string which represents a horizontal line."
if not linefmt:
return None
if hasattr(linefmt, "__call__"):
return linefmt(colwidths, colaligns)
else:
begin, fill, sep, end = linefmt
cells = [fill*w for w in colwidth... | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator identifier block return_statement none if_statement call identifier argument_list identifier string string_start string_content string_end ... | Return a string which represents a horizontal line. |
def crawler(site, uri=None):
config = load_site_config(site)
model = _get_model('crawl', config, uri)
visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets(
site, config
)
if not visited_set.has(model.hash):
visited_set.add(model.hash)
visited_uri_set.add(model... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier identi... | Crawl URI using site config. |
def iterations(self, parameter):
return numpy.arange(0, self.last_iteration(parameter), self.thinned_by) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list identifier attribute identifier identifier | Returns the iteration each sample occurred at. |
def external_answer(self, *sequences):
if not getattr(self, 'external', False):
return
if hasattr(self, 'test_func') and self.test_func is not self._ident:
return
libs = libraries.get_libs(self.__class__.__name__)
for lib in libs:
if not lib.check_cond... | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end false block return_statement if_statement boolean_operator call identifier argument_list identifier string stri... | Try to get answer from known external libraries. |
def scene_command(self, command):
self.logger.info("scene_command: Group %s Command %s", self.group_id, command)
command_url = self.hub.hub_url + '/0?' + command + self.group_id + "=I=0"
return self.hub.post_direct_command(command_url) | 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 attribute identifier identifier identifier expression_statement assignment identifier binary_operator bi... | Wrapper to send posted scene command and get response |
def r_date_num(obj, multiple=False):
if isinstance(obj, (list, tuple)):
it = iter
else:
it = LinesIterator
if multiple:
datasets = {}
for line in it(obj):
label = line[2]
if label not in datasets:
datasets[label] = Dataset([Dataset.DATE... | module function_definition identifier parameters identifier default_parameter identifier false block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier if_st... | Read date-value table. |
def resize(self, height, width, **kwargs):
self.client.exec_resize(self.exec_id, height=height, width=width) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier iden... | resize pty of an execed process |
def removeSubEditor(self, subEditor):
if subEditor is self.focusProxy():
self.setFocusProxy(None)
subEditor.removeEventFilter(self)
self._subEditors.remove(subEditor)
self.hBoxLayout.removeWidget(subEditor) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list none expression_statement call attribute identifier identifier argumen... | Removes the subEditor from the layout and removes the event filter. |
async def open(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str] = "-",
extra_cmd: Optional[str] = None,
stdout_pipe: bool = True,
stderr_pipe: bool = False,
) -> bool:
stdout = subprocess.PIPE if stdout_pipe else subprocess.DEV... | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier typed_default_parameter identifier type generic_type identifier type_parameter type id... | Start a ffmpeg instance and pipe output. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.