_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q36700
main
train
def main(): """This is the CLI driver for ia-wrapper.""" args = docopt(__doc__, version=__version__, options_first=True) # Validate args. s = Schema({ six.text_type: bool, '--config-file': Or(None, str), '<args>': list, '<command>': Or(str, lambda _: 'help'), }) ...
python
{ "resource": "" }
q36701
suppress_keyboard_interrupt_message
train
def suppress_keyboard_interrupt_message(): """Register a new excepthook to suppress KeyboardInterrupt exception messages, and exit with status code 130. """ old_excepthook = sys.excepthook def new_hook(type, value, traceback): if type != KeyboardInterrupt: old_excepthook(type, ...
python
{ "resource": "" }
q36702
recursive_file_count
train
def recursive_file_count(files, item=None, checksum=False): """Given a filepath or list of filepaths, return the total number of files.""" if not isinstance(files, (list, set)): files = [files] total_files = 0 if checksum is True: md5s = [f.get('md5') for f in item.files] else: ...
python
{ "resource": "" }
q36703
reraise_modify
train
def reraise_modify(caught_exc, append_msg, prepend=False): """Append message to exception while preserving attributes. Preserves exception class, and exception traceback. Note: This function needs to be called inside an except because `sys.exc_info()` requires the exception context. A...
python
{ "resource": "" }
q36704
configure
train
def configure(username=None, password=None, config_file=None): """Configure internetarchive with your Archive.org credentials. :type username: str :param username: The email address associated with your Archive.org account. :type password: str :param password: Your Archive.org password. Usage...
python
{ "resource": "" }
q36705
get_user_info
train
def get_user_info(access_key, secret_key): """Returns details about an Archive.org user given an IA-S3 key pair. :type access_key: str :param access_key: IA-S3 access_key to use when making the given request. :type secret_key: str :param secret_key: IA-S3 secret_key to use when making the given re...
python
{ "resource": "" }
q36706
CatalogTask.task_log
train
def task_log(self): """Get task log. :rtype: str :returns: The task log as a string. """ if self.task_id is None: raise ValueError('task_id is None') return self.get_task_log(self.task_id, self.session, self.request_kwargs)
python
{ "resource": "" }
q36707
CatalogTask.get_task_log
train
def get_task_log(task_id, session, request_kwargs=None): """Static method for getting a task log, given a task_id. This method exists so a task log can be retrieved without retrieving the items task history first. :type task_id: str or int :param task_id: The task id for the ta...
python
{ "resource": "" }
q36708
ArchiveSession._get_user_agent_string
train
def _get_user_agent_string(self): """Generate a User-Agent string to be sent with every request.""" uname = platform.uname() try: lang = locale.getlocale()[0][:2] except: lang = '' py_version = '{0}.{1}.{2}'.format(*sys.version_info) return 'intern...
python
{ "resource": "" }
q36709
ArchiveSession.rebuild_auth
train
def rebuild_auth(self, prepared_request, response): """Never rebuild auth for archive.org URLs. """ u = urlparse(prepared_request.url) if u.netloc.endswith('archive.org'): return super(ArchiveSession, self).rebuild_auth(prepared_request, response)
python
{ "resource": "" }
q36710
FormForForm.email_to
train
def email_to(self): """ Return the value entered for the first field of type EmailField. """ for field in self.form_fields: if field.is_a(fields.EMAIL): return self.cleaned_data[field.slug] return None
python
{ "resource": "" }
q36711
unique_slug
train
def unique_slug(manager, slug_field, slug): """ Ensure slug is unique for the given manager, appending a digit if it isn't. """ max_length = manager.model._meta.get_field(slug_field).max_length slug = slug[:max_length] i = 0 while True: if i > 0: if i > 1: ...
python
{ "resource": "" }
q36712
import_attr
train
def import_attr(path): """ Given a a Python dotted path to a variable in a module, imports the module and returns the variable in it. """ module_path, attr_name = path.rsplit(".", 1) return getattr(import_module(module_path), attr_name)
python
{ "resource": "" }
q36713
form_sent
train
def form_sent(request, slug, template="forms/form_sent.html"): """ Show the response message. """ published = Form.objects.published(for_user=request.user) context = {"form": get_object_or_404(published, slug=slug)} return render_to_response(template, context, RequestContext(request))
python
{ "resource": "" }
q36714
FormAdmin.get_queryset
train
def get_queryset(self, request): """ Annotate the queryset with the entries count for use in the admin list view. """ qs = super(FormAdmin, self).get_queryset(request) return qs.annotate(total_entries=Count("entries"))
python
{ "resource": "" }
q36715
FormAdmin.file_view
train
def file_view(self, request, field_entry_id): """ Output the file for the requested field entry. """ model = self.fieldentry_model field_entry = get_object_or_404(model, id=field_entry_id) path = join(fs.location, field_entry.value) response = HttpResponse(content...
python
{ "resource": "" }
q36716
RequestHandler.get_live_scores
train
def get_live_scores(self, use_12_hour_format): """Gets the live scores""" req = requests.get(RequestHandler.LIVE_URL) if req.status_code == requests.codes.ok: scores_data = [] scores = req.json() if len(scores["games"]) == 0: click.secho("No li...
python
{ "resource": "" }
q36717
RequestHandler.get_team_scores
train
def get_team_scores(self, team, time, show_upcoming, use_12_hour_format): """Queries the API and gets the particular team scores""" team_id = self.team_names.get(team, None) time_frame = 'n' if show_upcoming else 'p' if team_id: try: req = self._get('teams/{te...
python
{ "resource": "" }
q36718
RequestHandler.get_standings
train
def get_standings(self, league): """Queries the API and gets the standings for a particular league""" league_id = self.league_ids[league] try: req = self._get('competitions/{id}/standings'.format( id=league_id)) self.writer.standings(req.json(), le...
python
{ "resource": "" }
q36719
RequestHandler.get_league_scores
train
def get_league_scores(self, league, time, show_upcoming, use_12_hour_format): """ Queries the API and fetches the scores for fixtures based upon the league and time parameter """ time_frame = 'n' if show_upcoming else 'p' if league: try: leagu...
python
{ "resource": "" }
q36720
RequestHandler.get_team_players
train
def get_team_players(self, team): """ Queries the API and fetches the players for a particular team """ team_id = self.team_names.get(team, None) try: req = self._get('teams/{}/'.format(team_id)) team_players = req.json()['squad'] if no...
python
{ "resource": "" }
q36721
load_json
train
def load_json(file): """Load JSON file at app start""" here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, file)) as jfile: data = json.load(jfile) return data
python
{ "resource": "" }
q36722
get_input_key
train
def get_input_key(): """Input API key and validate""" click.secho("No API key found!", fg="yellow", bold=True) click.secho("Please visit {} and get an API token.".format(RequestHandler.BASE_URL), fg="yellow", bold=True) while True: confkey = click.prompt(click.sty...
python
{ "resource": "" }
q36723
load_config_key
train
def load_config_key(): """Load API key from config file, write if needed""" global api_token try: api_token = os.environ['SOCCER_CLI_API_TOKEN'] except KeyError: home = os.path.expanduser("~") config = os.path.join(home, ".soccer-cli.ini") if not os.path.exists(config): ...
python
{ "resource": "" }
q36724
map_team_id
train
def map_team_id(code): """Take in team ID, read JSON file to map ID to name""" for team in TEAM_DATA: if team["code"] == code: click.secho(team["name"], fg="green") break else: click.secho("No team found for this code", fg="red", bold=True)
python
{ "resource": "" }
q36725
list_team_codes
train
def list_team_codes(): """List team names in alphabetical order of team ID, per league.""" # Sort teams by league, then alphabetical by code cleanlist = sorted(TEAM_DATA, key=lambda k: (k["league"]["name"], k["code"])) # Get league names leaguenames = sorted(list(set([team["league"]["name"] for team...
python
{ "resource": "" }
q36726
main
train
def main(league, time, standings, team, live, use12hour, players, output_format, output_file, upcoming, lookup, listcodes, apikey): """ A CLI for live and past football scores from various football leagues. League codes: \b - WC: World Cup - EC: European Championship - CL: Champio...
python
{ "resource": "" }
q36727
Stdout.live_scores
train
def live_scores(self, live_scores): """Prints the live scores in a pretty format""" scores = sorted(live_scores, key=lambda x: x["league"]) for league, games in groupby(scores, key=lambda x: x["league"]): self.league_header(league) for game in games: self....
python
{ "resource": "" }
q36728
Stdout.team_scores
train
def team_scores(self, team_scores, time, show_datetime, use_12_hour_format): """Prints the teams scores in a pretty format""" for score in team_scores["matches"]: if score["status"] == "FINISHED": click.secho("%s\t" % score["utcDate"].split('T')[0], ...
python
{ "resource": "" }
q36729
Stdout.team_players
train
def team_players(self, team): """Prints the team players in a pretty format""" players = sorted(team, key=lambda d: d['shirtNumber']) click.secho("%-4s %-25s %-20s %-20s %-15s" % ("N.", "NAME", "POSITION", "NATIONALITY", "BIRTHDAY"), bold=True, ...
python
{ "resource": "" }
q36730
Stdout.standings
train
def standings(self, league_table, league): """ Prints the league standings in a pretty way """ click.secho("%-6s %-30s %-10s %-10s %-10s" % ("POS", "CLUB", "PLAYED", "GOAL DIFF", "POINTS")) for team in league_table["standings"][0]["table"]: if team["goal...
python
{ "resource": "" }
q36731
Stdout.league_scores
train
def league_scores(self, total_data, time, show_datetime, use_12_hour_format): """Prints the data in a pretty format""" for match in total_data['matches']: self.scores(self.parse_result(match), add_new_line=not show_datetime) if show_datetime: ...
python
{ "resource": "" }
q36732
Stdout.league_header
train
def league_header(self, league): """Prints the league header""" league_name = " {0} ".format(league) click.secho("{:=^62}".format(league_name), fg=self.colors.MISC) click.echo()
python
{ "resource": "" }
q36733
Stdout.scores
train
def scores(self, result, add_new_line=True): """Prints out the scores in a pretty format""" if result.goalsHomeTeam > result.goalsAwayTeam: homeColor, awayColor = (self.colors.WIN, self.colors.LOSE) elif result.goalsHomeTeam < result.goalsAwayTeam: homeColor, awayColor = ...
python
{ "resource": "" }
q36734
Stdout.parse_result
train
def parse_result(self, data): """Parses the results and returns a Result namedtuple""" def valid_score(score): return "" if score is None else score return self.Result( data["homeTeam"]["name"], valid_score(data["score"]["fullTime"]["homeTeam"]), ...
python
{ "resource": "" }
q36735
Stdout.utc_to_local
train
def utc_to_local(time_str, use_12_hour_format, show_datetime=False): """Converts the API UTC time string to the local user time.""" if not (time_str.endswith(" UTC") or time_str.endswith("Z")): return time_str today_utc = datetime.datetime.utcnow() utc_local_diff = today_utc...
python
{ "resource": "" }
q36736
Csv.live_scores
train
def live_scores(self, live_scores): """Store output of live scores to a CSV file""" headers = ['League', 'Home Team Name', 'Home Team Goals', 'Away Team Goals', 'Away Team Name'] result = [headers] result.extend([game['league'], game['homeTeamName'], ...
python
{ "resource": "" }
q36737
Csv.team_scores
train
def team_scores(self, team_scores, time): """Store output of team scores to a CSV file""" headers = ['Date', 'Home Team Name', 'Home Team Goals', 'Away Team Goals', 'Away Team Name'] result = [headers] result.extend([score["utcDate"].split('T')[0], ...
python
{ "resource": "" }
q36738
Csv.team_players
train
def team_players(self, team): """Store output of team players to a CSV file""" headers = ['Jersey Number', 'Name', 'Position', 'Nationality', 'Date of Birth'] result = [headers] result.extend([player['shirtNumber'], player['name'], ...
python
{ "resource": "" }
q36739
Csv.standings
train
def standings(self, league_table, league): """Store output of league standings to a CSV file""" headers = ['Position', 'Team Name', 'Games Played', 'Goal For', 'Goals Against', 'Goal Difference', 'Points'] result = [headers] result.extend([team['position'], ...
python
{ "resource": "" }
q36740
Csv.league_scores
train
def league_scores(self, total_data, time, show_upcoming, use_12_hour_format): """Store output of fixtures based on league and time to a CSV file""" headers = ['League', 'Home Team Name', 'Home Team Goals', 'Away Team Goals', 'Away Team Name'] result = [headers] league ...
python
{ "resource": "" }
q36741
Json.team_scores
train
def team_scores(self, team_scores, time): """Store output of team scores to a JSON file""" data = [] for score in team_scores['matches']: if score['status'] == 'FINISHED': item = {'date': score["utcDate"].split('T')[0], 'homeTeamName': score['h...
python
{ "resource": "" }
q36742
Json.standings
train
def standings(self, league_table, league): """Store output of league standings to a JSON file""" data = [] for team in league_table['standings'][0]['table']: item = {'position': team['position'], 'teamName': team['team'], 'playedGames': team['p...
python
{ "resource": "" }
q36743
Json.team_players
train
def team_players(self, team): """Store output of team players to a JSON file""" keys = 'shirtNumber name position nationality dateOfBirth'.split() data = [{key: player[key] for key in keys} for player in team] self.generate_output({'players': data})
python
{ "resource": "" }
q36744
Json.league_scores
train
def league_scores(self, total_data, time): """Store output of fixtures based on league and time to a JSON file""" data = [] for league, score in self.supported_leagues(total_data): item = {'league': league, 'homeTeamName': score['homeTeamName'], 'goalsHomeTeam': s...
python
{ "resource": "" }
q36745
example_camera
train
def example_camera(): """ Example with `morphological_chan_vese` with using the default initialization of the level-set. """ logging.info('Running: example_camera (MorphACWE)...') # Load the image. img = imread(PATH_IMG_CAMERA)/255.0 # Callback for visual plotting callback = v...
python
{ "resource": "" }
q36746
operator_si
train
def operator_si(u): """operator_si operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
python
{ "resource": "" }
q36747
operator_is
train
def operator_is(u): """operator_is operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
python
{ "resource": "" }
q36748
gborders
train
def gborders(img, alpha=1.0, sigma=1.0): """Stopping criterion for image borders.""" # The norm of the gradient. gradnorm = gaussian_gradient_magnitude(img, sigma, mode='constant') return 1.0/np.sqrt(1.0 + alpha*gradnorm)
python
{ "resource": "" }
q36749
MorphACWE.step
train
def step(self): """Perform a single step of the morphological Chan-Vese evolution.""" # Assign attributes to local variables for convenience. u = self._u if u is None: raise ValueError("the levelset function is not set " "(use set_levelse...
python
{ "resource": "" }
q36750
MorphGAC._update_mask
train
def _update_mask(self): """Pre-compute masks for speed.""" self._threshold_mask = self._data > self._theta self._threshold_mask_v = self._data > self._theta/np.abs(self._v)
python
{ "resource": "" }
q36751
MorphGAC.step
train
def step(self): """Perform a single step of the morphological snake evolution.""" # Assign attributes to local variables for convenience. u = self._u gI = self._data dgI = self._ddata theta = self._theta v = self._v if u is None: raise...
python
{ "resource": "" }
q36752
sup_inf
train
def sup_inf(u): """SI operator.""" if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") erosions = [] for P_i in P: erosions.append(ndi.binary_ero...
python
{ "resource": "" }
q36753
inf_sup
train
def inf_sup(u): """IS operator.""" if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") dilations = [] for P_i in P: dilations.append(ndi.binary_d...
python
{ "resource": "" }
q36754
_check_input
train
def _check_input(image, init_level_set): """Check that shapes of `image` and `init_level_set` match.""" if not image.ndim in [2, 3]: raise ValueError("`image` must be a 2 or 3-dimensional array.") if len(image.shape) != len(init_level_set.shape): raise ValueError("The dimensions of the init...
python
{ "resource": "" }
q36755
_init_level_set
train
def _init_level_set(init_level_set, image_shape): """Auxiliary function for initializing level sets with a string. If `init_level_set` is not a string, it is returned as is. """ if isinstance(init_level_set, str): if init_level_set == 'checkerboard': res = checkerboard_level_set(ima...
python
{ "resource": "" }
q36756
circle_level_set
train
def circle_level_set(image_shape, center=None, radius=None): """Create a circle level set with binary values. Parameters ---------- image_shape : tuple of positive integers Shape of the image center : tuple of positive integers, optional Coordinates of the center of the circle given...
python
{ "resource": "" }
q36757
checkerboard_level_set
train
def checkerboard_level_set(image_shape, square_size=5): """Create a checkerboard level set with binary values. Parameters ---------- image_shape : tuple of positive integers Shape of the image. square_size : int, optional Size of the squares of the checkerboard. It defaults to 5. ...
python
{ "resource": "" }
q36758
inverse_gaussian_gradient
train
def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0): """Inverse of gradient magnitude. Compute the magnitude of the gradients in the image and then inverts the result in the range [0, 1]. Flat areas are assigned values close to 1, while areas close to borders are assigned values close to 0. ...
python
{ "resource": "" }
q36759
Command.get_handler
train
def get_handler(self, *args, **options): """ Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler. """ handler = super(Command, self).get_handler(*args, **options) inse...
python
{ "resource": "" }
q36760
Account.privateKeyToAccount
train
def privateKeyToAccount(self, private_key): ''' Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing a...
python
{ "resource": "" }
q36761
Account.recoverTransaction
train
def recoverTransaction(self, serialized_transaction): ''' Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & ch...
python
{ "resource": "" }
q36762
Account.signHash
train
def signHash(self, message_hash, private_key): ''' Sign the hash provided. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. If you would like com...
python
{ "resource": "" }
q36763
get_dependencies
train
def get_dependencies(primary_type, types): """ Perform DFS to get all the dependencies of the primary_type """ deps = set() struct_names_yet_to_be_expanded = [primary_type] while len(struct_names_yet_to_be_expanded) > 0: struct_name = struct_names_yet_to_be_expanded.pop() deps....
python
{ "resource": "" }
q36764
is_valid_abi_type
train
def is_valid_abi_type(type_name): """ This function is used to make sure that the ``type_name`` is a valid ABI Type. Please note that this is a temporary function and should be replaced by the corresponding ABI function, once the following issue has been resolved. https://github.com/ethereum/eth-ab...
python
{ "resource": "" }
q36765
get_depths_and_dimensions
train
def get_depths_and_dimensions(data, depth): """ Yields 2-length tuples of depth and dimension of each element at that depth """ if not isinstance(data, (list, tuple)): # Not checking for Iterable instance, because even Dictionaries and strings # are considered as iterables, but that's no...
python
{ "resource": "" }
q36766
hash_of_signed_transaction
train
def hash_of_signed_transaction(txn_obj): ''' Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware tr...
python
{ "resource": "" }
q36767
extract_chain_id
train
def extract_chain_id(raw_v): ''' Extracts chain ID, according to EIP-155 @return (chain_id, v) ''' above_id_offset = raw_v - CHAIN_ID_OFFSET if above_id_offset < 0: if raw_v in {0, 1}: return (None, raw_v + V_OFFSET) elif raw_v in {27, 28}: return (None, r...
python
{ "resource": "" }
q36768
get_occurrence
train
def get_occurrence(event_id, occurrence_id=None, year=None, month=None, day=None, hour=None, minute=None, second=None, tzinfo=None): """ Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the...
python
{ "resource": "" }
q36769
CalendarManager.get_calendars_for_object
train
def get_calendars_for_object(self, obj, distinction=''): """ This function allows you to get calendars for a specific object If distinction is set it will filter out any relation that doesnt have that distinction. """ ct = ContentType.objects.get_for_model(obj) i...
python
{ "resource": "" }
q36770
CalendarRelationManager.create_relation
train
def create_relation(self, calendar, content_object, distinction='', inheritable=True): """ Creates a relation between calendar and content_object. See CalendarRelation for help on distinction and inheritable """ return CalendarRelation.objects.create( calendar=calenda...
python
{ "resource": "" }
q36771
EventListManager.occurrences_after
train
def occurrences_after(self, after=None): """ It is often useful to know what the next occurrence is given a list of events. This function produces a generator that yields the the most recent occurrence after the date ``after`` from any of the events in ``self.events`` ""...
python
{ "resource": "" }
q36772
EventRelationManager.get_events_for_object
train
def get_events_for_object(self, content_object, distinction='', inherit=True): ''' returns a queryset full of events, that relate to the object through, the distinction If inherit is false it will not consider the calendars that the events belong to. If inherit is true it will i...
python
{ "resource": "" }
q36773
EventRelationManager.create_relation
train
def create_relation(self, event, content_object, distinction=''): """ Creates a relation between event and content_object. See EventRelation for help on distinction. """ return EventRelation.objects.create( event=event, distinction=distinction, ...
python
{ "resource": "" }
q36774
init_db
train
def init_db(): """ Populate a small db with some example entries. """ db.drop_all() db.create_all() # Create sample Post title = "de Finibus Bonorum et Malorum - Part I" text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \ incididunt ...
python
{ "resource": "" }
q36775
_CKEditor.load
train
def load(custom_url=None, pkg_type=None, serve_local=None, version='4.9.2'): """Load CKEditor resource from CDN or local. :param custom_url: The custom resource url to use, build your CKEditor on `CKEditor builder <https://ckeditor.com/cke4/builder>`_. :param pkg_type: The type of C...
python
{ "resource": "" }
q36776
PyWiFi.interfaces
train
def interfaces(self): """Collect the available wlan interfaces.""" self._ifaces = [] wifi_ctrl = wifiutil.WifiUtil() for interface in wifi_ctrl.interfaces(): iface = Interface(interface) self._ifaces.append(iface) self._logger.info("Get interface: %s...
python
{ "resource": "" }
q36777
WifiUtil.network_profile_name_list
train
def network_profile_name_list(self, obj): """Get AP profile names.""" profile_list = pointer(WLAN_PROFILE_INFO_LIST()) self._wlan_get_profile_list(self._handle, byref(obj['guid']), byref(profile_list)) profiles = ca...
python
{ "resource": "" }
q36778
WifiUtil.remove_network_profile
train
def remove_network_profile(self, obj, params): """Remove the specified AP profile.""" self._logger.debug("delete profile: %s", params.ssid) str_buf = create_unicode_buffer(params.ssid) ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf) self._logger.debug("delete...
python
{ "resource": "" }
q36779
WifiUtil.remove_all_network_profiles
train
def remove_all_network_profiles(self, obj): """Remove all the AP profiles.""" profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: self._logger.debug("delete profile: %s", profile_name) str_buf = create_unicode_buffer(profile_na...
python
{ "resource": "" }
q36780
WifiUtil.remove_network_profile
train
def remove_network_profile(self, obj, params): """Remove the specified AP profiles""" network_id = -1 profiles = self.network_profiles(obj) for profile in profiles: if profile == params: network_id = profile.id if network_id != -1: self....
python
{ "resource": "" }
q36781
Interface.scan
train
def scan(self): """Trigger the wifi interface to scan.""" self._logger.info("iface '%s' scans", self.name()) self._wifi_ctrl.scan(self._raw_obj)
python
{ "resource": "" }
q36782
Interface.scan_results
train
def scan_results(self): """Return the scan result.""" bsses = self._wifi_ctrl.scan_results(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for bss in bsses: self._logger.info("Find bss:") self._logger.info("\tbssid: %s", bss.bssid)...
python
{ "resource": "" }
q36783
Interface.network_profiles
train
def network_profiles(self): """Get all the AP profiles.""" profiles = self._wifi_ctrl.network_profiles(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for profile in profiles: self._logger.info("Get profile:") self._logger.info("\tssid: %s...
python
{ "resource": "" }
q36784
Interface.disconnect
train
def disconnect(self): """Disconnect from the specified AP.""" self._logger.info("iface '%s' disconnects", self.name()) self._wifi_ctrl.disconnect(self._raw_obj)
python
{ "resource": "" }
q36785
Source.label
train
def label(self): """Convert a module name to a formatted node label. This is a default policy - please override. """ if len(self.name) > 14 and '.' in self.name: return '\\.\\n'.join(self.name.split('.')) # pragma: nocover return self.name
python
{ "resource": "" }
q36786
DepGraph.proximity_metric
train
def proximity_metric(self, a, b): """Return the weight of the dependency from a to b. Higher weights usually have shorter straighter edges. Return 1 if it has normal weight. A value of 4 is usually good for ensuring that a related pair of modules are drawn next to each other. ...
python
{ "resource": "" }
q36787
DepGraph.dissimilarity_metric
train
def dissimilarity_metric(self, a, b): """Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. Returns an int bet...
python
{ "resource": "" }
q36788
DepGraph.connect_generations
train
def connect_generations(self): """Traverse depth-first adding imported_by. """ # for src in list(self.sources.values()): for src in self.sources.values(): for _child in src.imports: if _child in self.sources: child = self.sources[_child] ...
python
{ "resource": "" }
q36789
DepGraph.remove_excluded
train
def remove_excluded(self): """Remove all sources marked as excluded. """ # import yaml # print yaml.dump({k:v.__json__() for k,v in self.sources.items()}, default_flow_style=False) sources = list(self.sources.values()) for src in sources: if src.excluded: ...
python
{ "resource": "" }
q36790
to_bytes
train
def to_bytes(s): # pragma: nocover """Convert an item into bytes. """ if isinstance(s, bytes): return s if isinstance(s, str) or is_unicode(s): return s.encode("utf-8") try: return unicode(s).encode("utf-8") except NameError: return str(s).encode("utf-8")
python
{ "resource": "" }
q36791
cmd2args
train
def cmd2args(cmd): """Prepare a command line for execution by Popen. """ if isinstance(cmd, str): return cmd if win32 else shlex.split(cmd) return cmd
python
{ "resource": "" }
q36792
pipe
train
def pipe(cmd, txt): """Pipe `txt` into the command `cmd` and return the output. """ return Popen( cmd2args(cmd), stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=win32 ).communicate(txt)[0]
python
{ "resource": "" }
q36793
dot
train
def dot(src, **kw): """Execute the dot command to create an svg output. """ cmd = "dot -T%s" % kw.pop('T', 'svg') for k, v in list(kw.items()): if v is True: cmd += " -%s" % k else: cmd += " -%s%s" % (k, v) return pipe(cmd, to_bytes(src))
python
{ "resource": "" }
q36794
call_graphviz_dot
train
def call_graphviz_dot(src, fmt): """Call dot command, and provide helpful error message if we cannot find it. """ try: svg = dot(src, T=fmt) except OSError as e: # pragma: nocover if e.errno == 2: cli.error(""" cannot find 'dot' pydeps c...
python
{ "resource": "" }
q36795
display_svg
train
def display_svg(kw, fname): # pragma: nocover """Try to display the svg file on this platform. """ if kw['display'] is None: cli.verbose("Displaying:", fname) if sys.platform == 'win32': os.startfile(fname) else: opener = "open" if sys.platform == "darwin" el...
python
{ "resource": "" }
q36796
pystdlib
train
def pystdlib(): """Return a set of all module-names in the Python standard library. """ curver = '.'.join(str(x) for x in sys.version_info[:2]) return (set(stdlib_list.stdlib_list(curver)) | { '_LWPCookieJar', '_MozillaCookieJar', '_abcoll', 'email._parseaddr', 'email.base64mime', ...
python
{ "resource": "" }
q36797
ModuleFinder.report
train
def report(self): # pragma: nocover """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ print() print(" %-25s %s" % ("Name", "File")) print(" %-25s %s" % ("----", "----")) # Pr...
python
{ "resource": "" }
q36798
name2rgb
train
def name2rgb(hue): """Originally used to calculate color based on module name. """ r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7) return tuple(int(x * 256) for x in [r, g, b])
python
{ "resource": "" }
q36799
foreground
train
def foreground(background, *options): """Find the best foreground color from `options` based on `background` color. """ def absdiff(a, b): return brightnessdiff(a, b) # return 3 * brightnessdiff(a, b) + colordiff(a, b) diffs = [(absdiff(background, color), color) for color in opti...
python
{ "resource": "" }