code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def reset(self): self.report("sending reset") try: self.p.stdin.write(bytes("T\n","utf-8")) self.p.stdin.flush() except IOError: self.report("could not send reset command")
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list ca...
Tell the external analyzer to reset itself
def _get_files_to_lint(self, external_directories): all_f = [] for external_dir in external_directories: all_f.extend(_all_files_matching_ext(external_dir, "py")) packages = self.distribution.packages or list() for package in packages: all_f.extend(_all_files_matc...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content strin...
Get files to lint.
def sample_string(self, individual=-1): base = str(self) extra = self.get_sample_info(individual=individual) extra = [':'.join([str(j) for j in i]) for i in zip(*extra.values())] return '\t'.join([base, '\t'.join(extra)])
module function_definition identifier parameters identifier default_parameter identifier unary_operator integer block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identif...
Returns the VCF entry as it appears in the vcf file
def list_vrf(self): try: vrfs = VRF.list() except NipapError, e: return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__}) return json.dumps(vrfs, cls=NipapJSONEncoder)
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier identifier block return_statement call attribute identifier identifier argument_list dictionary pair string string_...
List VRFs and return JSON encoded result.
def unique_everseen(iterable, filterfalse_=itertools.filterfalse): seen = set() seen_add = seen.add for element in filterfalse_(seen.__contains__, iterable): seen_add(element) yield element
module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute identifier identifier for_statement identifier call identifier argu...
Unique elements, preserving order.
def change_dir(): try: d = os.environ['HADOOPY_CHDIR'] sys.stderr.write('HADOOPY: Trying to chdir to [%s]\n' % d) except KeyError: pass else: try: os.chdir(d) except OSError: sys.stderr.write('HADOOPY: Failed to chdir to [%s]\n' % d)
module function_definition identifier parameters block try_statement block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator strin...
Change the local directory if the HADOOPY_CHDIR environmental variable is provided
def move_where_clause_to_column(self, column='condition', key=None): if self.conditions: expr = " AND ".join(self.conditions) params = self.params self.params = [] self.conditions = [] else: expr = '1' params = [] self.add_c...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content s...
Move whole WHERE clause to a column named `column`.
def nest(thing): tfutil = util.get_module('tensorflow.python.util') if tfutil: return tfutil.nest.flatten(thing) else: return [thing]
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 return_statement call attribute attribute identifier identifier identifier argument_...
Use tensorflows nest function if available, otherwise just wrap object in an array
def type(self) -> str: model = self.name if 'single' in model: return 'single' elif 'multi' in model: return 'multi' else: raise RuntimeError("Bad pipette model name: {}".format(model))
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement string string_start string_content string_end elif...
One of `'single'` or `'multi'`.
def variables(template): vars = set() for varlist in TEMPLATE.findall(template): if varlist[0] in OPERATOR: varlist = varlist[1:] varspecs = varlist.split(',') for var in varspecs: var = var.split(':')[0] if var.endswith('*'): var = var...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator subscript identifier integer identifier block expressio...
Returns the set of keywords in a uri template
def close(self): if self.closed: return for func,arglist in self.callbacks: apply(func, arglist) self.closed = True
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier expression_statement assig...
Invoke all the callbacks, and close off the SOAP message.
def do_stacktrace(self) -> None: frame = sys._current_frames()[self._event_loop_thread_id] traceback.print_stack(frame, file=self._sout)
module function_definition identifier parameters identifier type none block expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifi...
Print a stack trace from the event loop thread
def validate(self): super().validate() message_dsm = 'Matrix at [%s:%s] is not an instance of '\ 'DesignStructureMatrix or MultipleDomainMatrix.' message_ddm = 'Matrix at [%s:%s] is not an instance of '\ 'DomainMappingMatrix or MultipleDomainMatrix.' ...
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier argument_list expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expressi...
Base validation + each cell is instance of DSM or MDM.
def _getEventsByWeek(self, request, year, month): home = request.site.root_page return getAllEventsByWeek(request, year, month, home=home)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier keyword_argument identifier identifier
Return the events in this site for the given month grouped by week.
def update_channels(self): self.interlock_channel = -1 self.override_channel = -1 self.zero_I_channel = -1 self.no_vtol_channel = -1 self.rsc_out_channel = 9 self.fwd_thr_channel = 10 for ch in range(1,16): option = self.get_mav_param("RC%u_OPTION" % c...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier unary_operator i...
update which channels provide input
def read_plain_int96(file_obj, count): items = struct.unpack(b"<" + b"qi" * count, file_obj.read(12 * count)) return [q << 32 | i for (q, i) in zip(items[0::2], items[1::2])]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end binary_operator string string_start string_content string_end identifier call attribute...
Read `count` 96-bit ints using the plain encoding.
def __generate_location(self): screen_width = world.get_backbuffer_size().X self.movement_speed = random.randrange(10, 25) self.coords = R.Vector2(screen_width + self.image.get_width(), random.randrange(0, 100))
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer integer expressi...
Reset the location of the cloud once it has left the viewable area of the screen.
def add_new_data_port(self): try: new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model]) if new_data_port_ids: self.select_entry(new_data_port_ids[self.model.state]) except ValueError: pass
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier list attribute identifier identifier if_statement identifier block expression_state...
Add a new port with default values and select it
def _show_mpl_backend_errors(self): if not self.external_kernel: self.shellwidget.silent_execute( "get_ipython().kernel._show_mpl_backend_errors()") self.shellwidget.sig_prompt_ready.disconnect( self._show_mpl_backend_errors)
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute attri...
Show possible errors when setting the selected Matplotlib backend.
def mask_image_data(data): if data.bands.size in (2, 4): if not np.issubdtype(data.dtype, np.integer): raise ValueError("Only integer datatypes can be used as a mask.") mask = data.data[-1, :, :] == np.iinfo(data.dtype).min data = data.astype(np.float64) masked_data = da....
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier tuple integer integer block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier...
Mask image data if alpha channel is present.
def start_ray_processes(self): logger.info( "Process STDOUT and STDERR is being redirected to {}.".format( self._logs_dir)) self.start_plasma_store() self.start_raylet() if PY3: self.start_reporter() if self._ray_params.include_log_monitor:...
module function_definition identifier parameters 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 call attribute identifier identifier argume...
Start all of the processes on the node.
def check_complete(self): logger.debug('Running check_complete for task {0}'.format(self.name)) if self.remote_not_complete() or self.local_not_complete(): self._start_check_timer() return return_code = self.completed_task() if self.terminate_sent: sel...
module function_definition identifier parameters 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 if_statement boolean_operator call attribute identifier identifi...
Runs completion flow for this task if it's finished.
def random_init_map(interface, state, label, inp): import random out = interface.output(0) centers = {} for row in inp: row = row.strip().split(state["delimiter"]) if len(row) > 1: x = [(0 if row[i] in state["missing_vals"] else float(row[i])) for i in state["X_indices"]] ...
module function_definition identifier parameters identifier identifier identifier identifier block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier dictionary for_statement identifier ...
Assign datapoint `e` randomly to one of the `k` clusters.
def _get_method(self, request): if self._is_doc_request(request): return self.get_documentation else: return super(DocumentedResource, self)._get_method(request)
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement attribute identifier identifier else_clause block return_statement call attribute call identifier argument_list identifier identifier identifier ...
Override to check if this is a documentation request.
def mpub(self, topic, *messages): with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_response()
module function_definition identifier parameters identifier identifier list_splat_pattern identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identif...
Publish messages to a topic
def __process_gprest_response(self, r=None, restType='GET'): if r is None: logging.info('No response for REST '+restType+' request') return None httpStatus = r.status_code logging.info('HTTP status code: %s', httpStatus) if httpStatus == requests.codes.ok or...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list binary_operator bi...
Returns the processed response for rest calls
def export_data(filename_or_fobj, data, mode="w"): if filename_or_fobj is None: return data _, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode) source = Source.from_file(filename_or_fobj, mode=mode, plugin_name=None) source.fobj.write(data) source.fobj.flush() return source.fobj
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment pattern_list identifier identifier call identifier ar...
Return the object ready to be exported or only data if filename_or_fobj is not passed.
def run(self): self.OnStartup() try: while True: message = self._in_queue.get() if message is None: break try: self.HandleMessage(message) except Exception as e: logging.warning("%s", e) self.SendReply( rdf_flows.GrrStat...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list try_statement block while_statement true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement compari...
Main thread for processing messages.
def print_menuconfig(kconf): print("\n======== {} ========\n".format(kconf.mainmenu_text)) print_menuconfig_nodes(kconf.top_node.list, 0) print("")
module function_definition identifier parameters identifier block expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier expression_statement call identifier argument_list at...
Prints all menu entries for the configuration.
def extractFromHTML(html, blur=5): try: html = unicode(html, errors='ignore') except TypeError: pass assert isinstance(html, unicode) _file = StringIO() f = formatter.AbstractFormatter(formatter.DumbWriter(_file)) p = TextExtractor() p.pathBlur = blur p.feed(html) p.c...
module function_definition identifier parameters identifier default_parameter identifier integer block try_statement block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end except_clause identifier block pass_sta...
Extracts text from HTML content.
def resolve(self, key): registration = self._registrations.get(key) if registration is None: raise KeyError("Unknown key: '{0}'".format(key)) return registration.resolve(self, key)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list call attribute s...
Resolves the requested key to an object instance, raising a KeyError if the key is missing
def ajax_count_plus(self, slug): output = { 'status': 1 if MWiki.view_count_plus(slug) else 0, } return json.dump(output, self)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end conditional_expression integer call attribute identifier identifier argument_list identifier integer return_statement call attribute ident...
post count plus one via ajax.
def enable_napp(cls, mgr): try: if not mgr.is_enabled(): LOG.info(' Enabling...') mgr.enable() LOG.info(' Enabled.') except (FileNotFoundError, PermissionError) as exception: LOG.error(' %s', exception)
module function_definition identifier parameters identifier identifier block try_statement block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement c...
Install one NApp using NAppManager object.
def _metaconfigure(self, argv=None): metaconfig = self._get_metaconfig_class() if not metaconfig: return if self.__class__ is metaconfig: return override = { 'conflict_handler': 'resolve', 'add_help': False, 'prog': self._parser...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement if_statement comparison_operator attribute identifier identifier i...
Initialize metaconfig for provisioning self.
def filenames(self) -> Tuple[str, ...]: return tuple(sorted(set(itertools.chain( *(_.keys() for _ in self.folders.values())))))
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type ellipsis block return_statement call identifier argument_list call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list list_splat generator_e...
A |tuple| of names of all handled |NetCDFFile| objects.
def AddClientLabels(self, client_id, owner, labels): if client_id not in self.metadatas: raise db.UnknownClientError(client_id) labelset = self.labels.setdefault(client_id, {}).setdefault(owner, set()) for l in labels: labelset.add(utils.SmartUnicode(l))
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute cal...
Attaches a user label to a client.
def full(self, external=False): return self.fs.url(self.filename, external=external) if self.filename else None
module function_definition identifier parameters identifier default_parameter identifier false block return_statement conditional_expression call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier attribute identifier identifier none
Get the full image URL in respect with ``max_size``
def header(*msg, level='h1', separator=" ", print_out=print): out_string = separator.join(str(x) for x in msg) if level == 'h0': box_len = 80 print_out('+' + '-' * (box_len + 2)) print_out("| %s" % out_string) print_out('+' + '-' * (box_len + 2)) elif level == 'h1': p...
module function_definition identifier parameters list_splat_pattern identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier identifier block expression_statement assignment identifier ca...
Print header block in text mode
def _get_log_format(self, request): user = getattr(request, 'user', None) if not user: return if not request.user.is_authenticated: return method = request.method.upper() if not (method in self.target_methods): return request_url = urlp...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement not_operator identifier block return_statement if_statement not_operator attribute attribute id...
Return operation log format.
def which_api_version(self, api_call): if api_call.endswith('.php'): return 1 elif api_call.startswith('api/2.0/'): return 2 elif '/am/' in api_call: return 'am' elif '/was/' in api_call: return 'was' return False
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement integer elif_clause call attribute identifier identifier argument_list string string_start string_content stri...
Return QualysGuard API version for api_call specified.
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority=None, fail_silently=False, auth_user=None, auth_password=None, headers={}): from django.utils.encoding import force_text from django.core.mail import EmailMultiAlternatives from mail...
module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier dictionary block import_from_statement dotted_name...
Function to queue HTML e-mails
def create_directories(self, create_project_dir=True): return task.create_directories(self.datadir, self.sitedir, self.target if create_project_dir else None)
module function_definition identifier parameters identifier default_parameter identifier true block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier conditional_expression attribute identifier identifier identifier none
Call once for new projects to create the initial project directories.
def reward_battery(self): if not 'battery' in self.mode: return mode = self.mode['battery'] if mode and mode and self.__test_cond(mode): self.logger.debug('Battery out') self.player.stats['reward'] += mode['reward'] self.player.game_over = self.pla...
module function_definition identifier parameters identifier block if_statement not_operator comparison_operator string string_start string_content string_end attribute identifier identifier block return_statement expression_statement assignment identifier subscript attribute identifier identifier string string_start st...
Add a battery level reward
def _bddnode(root, lo, hi): if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: node = _NODES[key] = BDDNode(*key) return node
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier tuple identifier identifier identifier try_statement blo...
Return a unique BDD node.
def equals(self, rest_object): if self._is_dirty: return False if rest_object is None: return False if not isinstance(rest_object, NURESTObject): raise TypeError('The object is not a NURESTObject %s' % rest_object) if self.rest_name != rest_object.rest...
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement false if_statement comparison_operator identifier none block return_statement false if_statement not_operator call identifier argument_list identifier identifier block raise_s...
Compare with another object
def add_to(self, parent, name=None, index=None): parent.add_child(self, name=name, index=index) return self
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_stateme...
Add element to a parent.
def DeleteSubjects(self, subjects, sync=False): for subject in subjects: self.DeleteSubject(subject, sync=sync)
module function_definition identifier parameters identifier identifier default_parameter identifier false block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier
Delete multiple subjects at once.
def evaluate(grid): "Return the value for the player to move, assuming perfect play." if is_won(grid): return -1 succs = successors(grid) return -min(map(evaluate, succs)) if succs else 0
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier block return_statement unary_operator integer expression_statement assignment identifier call identifier argument_list identifier ret...
Return the value for the player to move, assuming perfect play.
def _inverse_i(self, y, i): lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if 1 < 3: if not lb <= y <= ub: raise ValueError('argument of inverse must be within the given bounds') ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier ...
return inverse of y in component i
def __parse_fc_data(fc_data): fc = [] for day in fc_data: fcdata = { CONDITION: __cond_from_desc( __get_str( day, __WEATHERDESCRIPTION) ), TEMPERATURE: __get_float(day, __MAXTEMPERATURE), MIN_TEMP: __...
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier dictionary pair identifier call identifier argument_list call identifier argument_list identifier identifier pair identif...
Parse the forecast data from the json section.
def stream_skypipe_output(endpoint, name=None): name = name or '' socket = ctx.socket(zmq.DEALER) socket.connect(endpoint) try: socket.send_multipart(sp_msg(SP_CMD_LISTEN, name)) while True: msg = socket.recv_multipart() try: data = parse_skypipe_d...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier ide...
Generator for reading skypipe data
def client(self, name=None): name = name or self.default if not name: return NullClient(self, None, None) params = self.backends_hash[name] ccls = self.backends_schemas.get(params.scheme, TCPClient) return (yield from ccls(self, params.hostname, params.port).connect()...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier if_statement not_operator identifier block return_statement call identifier argument_list identifier none none expres...
Initialize a backend's client with given name or default.
def _check_for_boolean_pair_reduction(self, kwargs): if 'reduction_forcing_pairs' in self._meta_data: for key1, key2 in self._meta_data['reduction_forcing_pairs']: kwargs = self._reduce_boolean_pair(kwargs, key1, key2) return kwargs
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block for_statement pattern_list identifier identifier subscript attribute identifier identifier string string_start string_content ...
Check if boolean pairs should be reduced in this resource.
def _findPoint(self, name, force_read=True): for point in self.points: if point.properties.name == name: if force_read: point.value return point raise ValueError("{} doesn't exist in controller".format(name))
module function_definition identifier parameters identifier identifier default_parameter identifier true block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier identifier block if_statement identifier block expression_st...
Used by getter and setter functions
def stack_sparse_frame(frame): lengths = [s.sp_index.npoints for _, s in frame.items()] nobs = sum(lengths) minor_codes = np.repeat(np.arange(len(frame.columns)), lengths) inds_to_concat = [] vals_to_concat = [] for _, series in frame.items(): if not np.isnan(series.fill_value): ...
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension attribute attribute identifier identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identif...
Only makes sense when fill_value is NaN
def find_water_flow(self, world, water_path): for x in range(world.width - 1): for y in range(world.height - 1): path = self.find_quick_path([x, y], world) if path: tx, ty = path flow_dir = [tx - x, ty - y] k...
module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list binary_operator attribute identifier identifier integer block for_statement identifier call identifier argument_list binary_operator attribute identifier identifier integer bloc...
Find the flow direction for each cell in heightmap
def stat_smt_query(func: Callable): stat_store = SolverStatistics() def function_wrapper(*args, **kwargs): if not stat_store.enabled: return func(*args, **kwargs) stat_store.query_count += 1 begin = time() result = func(*args, **kwargs) end = time() st...
module function_definition identifier parameters typed_parameter identifier type identifier block expression_statement assignment identifier call identifier argument_list function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator attribute...
Measures statistics for annotated smt query check function
def _handle_error(self, response): auth_msg = "The query could not be completed. Invalid auth token." status_code = response.status_code if 400 <= status_code < 500: if status_code == 400: raise auth_error(auth_msg) else: raise auth_...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator integer identifier integer block if_statement ...
Handles all responses which return an error status code
def load_site_config(name): return _load_config_json( os.path.join( CONFIG_PATH, CONFIG_SITES_PATH, name + CONFIG_EXT ) )
module function_definition identifier parameters identifier block return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier binary_operator identifier identifier
Load and return site configuration as a dict.
def protocols(self): if self._protocols is None: uri = "/loadbalancers/protocols" resp, body = self.method_get(uri) self._protocols = [proto["name"] for proto in body["protocols"]] return self._protocols
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identif...
Returns a list of available load balancing protocols.
def ind_zero_freq(self): ind = np.searchsorted(self.frequencies, 0) if ind >= len(self.frequencies): raise ValueError("No positive frequencies found") return ind
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier integer if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block raise_st...
Index of the first point for which the freqencies are equal or greater than zero.
def getIndexes(cls) : "returns a list of the indexes of a class" con = RabaConnection(cls._raba_namespace) idxs = [] for idx in con.getIndexes(rabaOnly = True) : if idx[2] == cls.__name__ : idxs.append(idx) else : for k in cls.columns : if RabaFields.isRabaListField(getattr(cls, k)) and idx[2...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list for_statement identifier call attr...
returns a list of the indexes of a class
def list_styles(style_name): style = get_style_by_name(style_name) keys = list(style)[0][1] Styles = namedtuple("Style", keys) existing_styles = {} for ttype, ndef in style: s = Styles(**ndef) if s in existing_styles: existing_styles[s].append(ttype) else: ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier subscript subscript call identifier argument_list identifier integer integer expression_statement assignment identifier call id...
Just list all different styles entries
def load(self, data, many=None, partial=None): result = super(ResumptionTokenSchema, self).load( data, many=many, partial=partial ) result.data.update( result.data.get('resumptionToken', {}).get('kwargs', {}) ) return result
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier keyword_argument identifier i...
Deserialize a data structure to an object.
def validate(self, value): if not self.blank and value == '': self.error_message = 'Can not be empty. Please provide a value.' return False self._choice = value return True
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier comparison_operator identifier string string_start string_end block expression_statement assignment attribute identifier identifier string string_start string_content s...
The most basic validation
def _from_dict(cls, _dict): args = {} if 'global' in _dict: args['global_'] = MessageContextGlobal._from_dict( _dict.get('global')) if 'skills' in _dict: args['skills'] = MessageContextSkills._from_dict( _dict.get('skills')) return ...
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 MessageContext object from a json dictionary.
def setImportDataInterface(self, values): exims = self.getImportDataInterfacesList() new_values = [value for value in values if value in exims] if len(new_values) < len(values): logger.warn("Some Interfaces weren't added...") self.Schema().getField('ImportDataInterface').set(...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier...
Return the current list of import data interfaces
def handle_var(value, context): if isinstance(value, FilterExpression) or isinstance(value, Variable): return value.resolve(context) stringval = QUOTED_STRING.search(value) if stringval: return stringval.group("noquotes") try: return Variable(value).resolve(context) except Va...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier expression_statement ass...
Handle template tag variable
def depth(self): if self.indentation is None: yield else: previous = self.previous_indent self.previous_indent = self.indent self.indent += self.indentation yield self.indent = self.previous_indent self.previous_indent =...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement yield else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier ident...
Increase the level of indentation by one.
def pprint_label(self): "The pretty-printed label string for the Dimension" unit = ('' if self.unit is None else type(self.unit)(self.unit_format).format(unit=self.unit)) return bytes_to_unicode(self.label) + bytes_to_unicode(unit)
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier parenthesized_expression conditional_expression string string_start string_end comparison_operator attribute identifier identifier none call att...
The pretty-printed label string for the Dimension
def list(self, request): query = get_query_params(request).get("search", "") results = [] base = self.model.get_base_class() doctypes = indexable_registry.families[base] for doctype, klass in doctypes.items(): name = klass._meta.verbose_name.title() if que...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier...
Search the doctypes for this model.
def unstash(self): if not self.stashed: LOGGER.error('no stash') else: LOGGER.info('popping stash') self.repo.git.stash('pop') self.stashed = False
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identif...
Pops the last stash if EPAB made a stash before
def green(cls): "Make the text foreground color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREEN cls._set_text_attributes(wAttributes)
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 expression_statement augmented_assignment identifier unary_operator attribute identifier iden...
Make the text foreground color green.
def process_view(self, request, view_func, view_args, view_kwargs): profiler = getattr(request, 'profiler', None) if profiler: original_get = request.GET request.GET = original_get.copy() request.GET.pop('profile', None) request.GET.pop('show_queries', Non...
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement identifier block expression_statement assignment identifier at...
Run the profiler on _view_func_.
def cli(env, volume_id, sortby, columns): file_manager = SoftLayer.FileStorageManager(env.client) snapshots = file_manager.get_file_volume_snapshot_list( volume_id, mask=columns.mask() ) table = formatting.Table(columns.columns) table.sortby = sortby for snapshot in snapshots: ...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list i...
List file storage snapshots.
def gpg_command(args, env=None): if env is None: env = os.environ cmd = get_gnupg_binary(neopg_binary=env.get('NEOPG_BINARY')) return [cmd] + args
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument ...
Prepare common GPG command line arguments.
def touch_if_touching(self): if self._touching_parent(): self.get_parent().touch() if self.get_parent().touches(self._relation_name): self.touch()
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list if_statement call attribute call attribute identifier identifier argumen...
Touch if the parent model is being touched.
def _make_policies(self): self.policies = [AutoScalePolicy(self.manager, dct, self) for dct in self.scalingPolicies]
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list_comprehension call identifier argument_list attribute identifier identifier identifier identifier for_in_clause identifier attribute identifier identifier
Convert the 'scalingPolicies' dictionary into AutoScalePolicy objects.
def get(self, name: str, default: Any = None) -> Any: return super().get(name, [default])[0]
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none type identifier block return_statement subscript call attribute call identifier argument_list identifier argument_list identifier list identifier integer
Return the first value, either the default or actual
def worker(workers): logging.info( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead.") if workers: celery_app.conf.update(CELERYD_CONCURRENCY=workers) elif config.get('SUPERSET_CELERY_WORKERS'): celery_app.conf.update( ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement call attribute attr...
Starts a Superset worker for async SQL query execution.
def _call(self, x, out=None): if out is None: out = self.range.zero() else: out.set_zero() out[self.index] = x return out
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement ...
Extend ``x`` from the subspace.
def filter(cls, filters, iterable): if isinstance(filters, Filter): filters = [filters] for filter in filters: iterable = filter.generator(iterable) return iterable
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute id...
Returns the elements in `iterable` that pass given `filters`
def collect_gaps(blast, use_subject=False): key = lambda x: x.sstart if use_subject else x.qstart blast.sort(key=key) for a, b in zip(blast, blast[1:]): if use_subject: if a.sstop < b.sstart: yield b.sstart - a.sstop else: if a.qstop < b.qstart: ...
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier lambda lambda_parameters identifier conditional_expression attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identi...
Collect the gaps between adjacent HSPs in the BLAST file.
def _manhattan_distance(vec_a, vec_b): if len(vec_a) != len(vec_b): raise ValueError('len(vec_a) must equal len(vec_b)') return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifi...
Return manhattan distance between two lists of numbers.
def post_build_time_coverage(self): from ambry.util.datestimes import expand_to_years years = set() if self.metadata.about.time: for year in expand_to_years(self.metadata.about.time): years.add(year) if self.identity.btime: for year in expand_to_ye...
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list if_statement attribute attribute attribute identifier identifier identifier identifier bloc...
Collect all of the time coverage for the bundle.
def update_license(license_id, **kwargs): updated_license = pnc_api.licenses.get_specific(id=license_id).content for key, value in iteritems(kwargs): if value: setattr(updated_license, key, value) response = utils.checked_api_call( pnc_api.licenses, 'update', id=i...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier for_statement pattern_list identifier ident...
Replace the License with given ID with a new License
def mkdir(self, foldername): 'Create a new subfolder and return the new JFSFolder' url = posixpath.join(self.path, foldername) params = {'mkDir':'true'} r = self.jfs.post(url, params) self.sync() return r
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identif...
Create a new subfolder and return the new JFSFolder
def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_mat...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier integer keyword_argument identifier identifier expression_state...
Create a batch for SG training objective with subwords.
def nested_dict_to_list(path, dic, exclusion=None): result = [] exclusion = ['__self'] if exclusion is None else exclusion for key, value in dic.items(): if not any([exclude in key for exclude in exclusion]): if isinstance(value, dict): aux = path + key + "/" ...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier list expression_statement assignment identifier conditional_expression list string string_start string_content string_end comparison_operator identifier none identifi...
Transform nested dict to list
def done(self, result): self._geometry = self.geometry() QtWidgets.QDialog.done(self, result)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier
save the geometry before dialog is close to restore it later
def file_list(self, load): if 'env' in load: load.pop('env') ret = set() if 'saltenv' not in load: return [] if not isinstance(load['saltenv'], six.string_types): load['saltenv'] = six.text_type(load['saltenv']) for fsb in self.backends(load.po...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignme...
Return a list of files from the dominant environment
def insert_blob(filename, hosts=None, table=None): conn = connect(hosts) container = conn.get_blob_container(table) with open(filename, 'rb') as f: digest = container.put(f) return '{server}/_blobs/{table}/{digest}'.format( server=conn.client.active_servers[0], table=table, ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifi...
Upload a file into a blob table
def prt_tsv(prt, data_nts, **kws): prt_tsv_hdr(prt, data_nts, **kws) return prt_tsv_dat(prt, data_nts, **kws)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement call identifier argument_list identifier identifier dictionary_splat identifier return_statement call identifier argument_list identifier identifier dictionary_splat identifier
Print tab-separated table headers and data
def batch_norm(inputs, training, data_format): outputs = tf.layers.batch_normalization( inputs=inputs, axis=1 if data_format == 'channels_first' else 3, momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True, scale=True, training=training, fused=True) resnet_log_helper.log_batch_norm...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier conditional_expression integer comparison_operator...
Performs a batch normalization using a standard set of parameters.
def _validate_wavelengths(self, wave): if wave is None: if self.waveset is None: raise exceptions.SynphotError( 'self.waveset is undefined; ' 'Provide wavelengths for sampling.') wavelengths = self.waveset else: ...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier none block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start strin...
Validate wavelengths for sampling.
def isopen(self) -> bool: if self._file is None: return False return bool(self._file.id)
module function_definition identifier parameters identifier type identifier block if_statement comparison_operator attribute identifier identifier none block return_statement false return_statement call identifier argument_list attribute attribute identifier identifier identifier
State of backing file.
def resolve(self, key, keylist): raise AmbiguousKeyError("Ambiguous key "+ repr(key) + ", could be any of " + str(sorted(keylist)))
module function_definition identifier parameters identifier identifier identifier block raise_statement call identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call ...
Hook to resolve ambiguities in selected keys
def split_string(x: str, n: int) -> List[str]: return [x[i:i+n] for i in range(0, len(x), n)]
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block return_statement list_comprehension subscript identifier slice identifier binary_operator identifier identifier for_in_...
Split string into chunks of length n
def handleNotification(self, req): name = req["method"] params = req["params"] try: obj = getMethodByName(self.service, name) rslt = obj(*params) except: pass
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end try_statement block exp...
handles a notification request by calling the appropriete method the service exposes
def toListString(value): if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)): return [TypeConverters.toString(v) for v in value] raise TypeError("Could not conve...
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 strings, if possible.