function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def __init__(self) -> None: # map from node name to the node object self.map: dict[T, DisjointSetTreeNode[T]] = {}
TheAlgorithms/Python
[ 154959, 39275, 154959, 147, 1468662241 ]
def find_set(self, data: T) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) elem_ref = self.map[data] if elem_ref != elem_ref.parent: elem_ref.parent = self.find_set(elem_ref.parent.data) return elem_ref.parent
TheAlgorithms/Python
[ 154959, 39275, 154959, 147, 1468662241 ]
def union(self, data1: T, data2: T) -> None: # merge 2 disjoint sets self.link(self.find_set(data1), self.find_set(data2))
TheAlgorithms/Python
[ 154959, 39275, 154959, 147, 1468662241 ]
def __init__(self) -> None: # connections: map from the node to the neighbouring nodes (with weights) self.connections: dict[T, dict[T, int]] = {}
TheAlgorithms/Python
[ 154959, 39275, 154959, 147, 1468662241 ]
def add_edge(self, node1: T, node2: T, weight: int) -> None: # add an edge with the given weight self.add_node(node1) self.add_node(node2) self.connections[node1][node2] = weight self.connections[node2][node1] = weight
TheAlgorithms/Python
[ 154959, 39275, 154959, 147, 1468662241 ]
def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_query_r...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_query_results_for_subscription( self, query_options: Optional["_models.QueryOptions"] = None, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_query_r...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_query_results_for_resource_group( self, resource_group_name: str, query_options: Optional["_models.QueryOptions"] = None, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_query_r...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_query_results_for_resource( self, resource_id: str, query_options: Optional["_models.QueryOptions"] = None, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_query_r...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def convert_pandoc_rst(source, from_format, to_format, extra_args=None): """ Overwrites `convert_pandoc <https://github.com/jupyter/nbconvert/blob/master/nbconvert/filters/pandoc.py>`_. @param source string to convert @param from_format from format @param to_format ...
sdpython/pyquickhelper
[ 21, 10, 21, 22, 1388194285 ]
def __init__(self, *args, **kwargs): """ Overwrites the extra loaders to get the right template. """ filename = os.path.join(os.path.dirname(__file__), 'rst_modified.tpl') with open(filename, 'r', encoding='utf-8') as f: content = f.read() filename = os.path.j...
sdpython/pyquickhelper
[ 21, 10, 21, 22, 1388194285 ]
def _template_file_default(self): return "rst_modified.tpl"
sdpython/pyquickhelper
[ 21, 10, 21, 22, 1388194285 ]
def _file_extension_default(self): return '.rst'
sdpython/pyquickhelper
[ 21, 10, 21, 22, 1388194285 ]
def _template_name_default(self): return 'rst'
sdpython/pyquickhelper
[ 21, 10, 21, 22, 1388194285 ]
def parse(self, response): shops = response.xpath('//div[@id="js_subnav"]//li[@class="level-1"]/a/@href') for shop in shops: yield scrapy.Request( response.urljoin(shop.extract()), callback=self.parse_shop )
iandees/all-the-places
[ 379, 151, 379, 602, 1465952958 ]
def htlc(): pass
xeroc/uptick
[ 42, 29, 42, 6, 1483541352 ]
def create(ctx, to, amount, symbol, type, hash, expiration, length, account): """ Create an HTLC contract from a hash and lock-time """ ctx.blockchain.blocking = True tx = ctx.blockchain.htlc_create( Amount(amount, symbol), to, hash_type=type, hash_hex=hash, expir...
xeroc/uptick
[ 42, 29, 42, 6, 1483541352 ]
def create_from_secret(ctx, to, amount, symbol, type, secret, expiration, length, account): """Create an HTLC contract from a secret preimage If you are the party choosing the preimage, this version of htlc_create will compute the hash for you from the supplied preimage, and crea...
xeroc/uptick
[ 42, 29, 42, 6, 1483541352 ]
def main(config_file): return {'config_file': config_file}
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def on_error(e): # pragma: no cover """Error handler RuntimeError or ValueError exceptions raised by commands will be handled by this function. """ exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'} sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e)))...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def on_unexpected_error(e): # pragma: no cover """Catch-all error handler Unexpected errors will be handled by this function. """ sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') ...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def init(name, description, bucket, timeout, memory, stages, requirements, function, runtime, config_file, **kwargs): """Generate a configuration file.""" if os.path.exists(config_file): raise RuntimeError('Please delete the old version {} if you want to ' 'reconfigur...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def _run_lambda_function(event, context, app, config): # pragma: no cover """Run the function. This is the default when no plugins (such as wsgi) define an alternative run function.""" args = event.get('args', []) kwargs = event.get('kwargs', {}) # first attempt to invoke the function passing the ...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def _build(config, rebuild_deps=False): package = datetime.utcnow().strftime("lambda_package.%Y%m%d_%H%M%S.zip") ignore = ['\\.slam\\/venv\\/.*$', '\\.pyc$'] if os.environ.get('VIRTUAL_ENV'): # make sure the currently active virtualenv is not included in the pkg venv = os.path.relpath(os.env...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def _ensure_bucket_exists(s3, bucket, region): # pragma: no cover try: s3.head_bucket(Bucket=bucket) except botocore.exceptions.ClientError: if region != 'us-east-1': s3.create_bucket(Bucket=bucket, CreateBucketConfiguration={ 'LocationConstraint': region}) e...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def _print_status(config): cfn = boto3.client('cloudformation') lmb = boto3.client('lambda') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions.ClientError: print('{} has not been deployed yet.'.format(config['name'])) else: pri...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def build(rebuild_deps, config_file): """Build lambda package.""" config = _load_config(config_file) print("Building lambda package...") package = _build(config, rebuild_deps=rebuild_deps) print("{} has been built successfully.".format(package))
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file): """Deploy the project to the development stage.""" config = _load_config(config_file) if stage is None: stage = config['devstage'] s3 = boto3.client('s3') cfn = boto3.client('cloudformation') region = _get_aws_regi...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def publish(version, stage, config_file): """Publish a version of the project to a stage.""" config = _load_config(config_file) cfn = boto3.client('cloudformation') if version is None: version = config['devstage'] elif version not in config['stage_environments'].keys() and \ not...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def invoke(stage, nowait, dry_run, config_file, args): """Invoke the lambda function.""" config = _load_config(config_file) if stage is None: stage = config['devstage'] cfn = boto3.client('cloudformation') lmb = boto3.client('lambda') try: stack = cfn.describe_stacks(StackName=...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def delete(no_logs, config_file): """Delete the project.""" config = _load_config(config_file) s3 = boto3.client('s3') cfn = boto3.client('cloudformation') logs = boto3.client('logs') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def status(config_file): """Show deployment status for the project.""" config = _load_config(config_file) _print_status(config)
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def logs(stage, period, tail, config_file): """Dump logs to the console.""" config = _load_config(config_file) if stage is None: stage = config['devstage'] cfn = boto3.client('cloudformation') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocor...
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def template(config_file): """Print the default Cloudformation deployment template.""" config = _load_config(config_file) print(get_cfn_template(config, pretty=True))
miguelgrinberg/slam
[ 71, 11, 71, 4, 1482636088 ]
def get_logging_level(level): logging_level = None if isinstance(level, (str, unicode)): level = level.upper() try: logging_level = getattr(logging, level.upper()) except AttributeError: raise AttributeError('Tried to grab logging level "%s"' '...
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def __init__(self): self._handlers = [] self._log_lines = [] #storage before any handlers appear
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def debug(self, message, **kwargs): self.log('debug', message, **kwargs)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def info(self, message, **kwargs): self.log('info', message, **kwargs)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def critical(self, message, **kwargs): self.log('critical', message, **kwargs)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def debug_exception(self, message, **kwargs): """Stores exception except using the debug level""" exception_str = self._get_exception_str() self.log('debug', '%s\n%s' % (message, exception_str))
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def log(self, level, message, new_line=True): if new_line: message = "%s\n" % message handlers = self._handlers if not handlers: self._log_lines.append((level, message)) else: for handler in handlers: handler.log(level, message)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def __init__(self, level='debug'): self._level = get_logging_level(level)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def log(self, level, message): current_level = get_logging_level(level) if current_level >= self._level: self.emit(level, message)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def close(self): pass
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def emit(self, level, message): sys.stdout.write(message)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def emit(self, level, output): color = self.level_colors.get(level, "black") colored_function = getattr(colored, color, lambda text: text) colored_output = colored_function(output) puts(colored_output)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def __init__(self, filename): self._file = open(filename, 'a')
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def close(self): self._file.close() self._file = None
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def __init__(self, outputter): self._outputter = outputter logging.Handler.__init__(self)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def write(self, output, level): print(output)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def write(self, output, level): color = self.level_colors.get(level, "black") colored_function = getattr(colored, color, lambda text: text) colored_output = colored_function(output) puts(colored_output)
ravenac95/virtstrap
[ 7, 2, 7, 3, 1330379410 ]
def __init__(self, tree, view, with_root=False): self.tree = json.loads(tree.to_json(with_data=True)) self.view = view self.with_root = with_root # For public sitemap # Public sitemap self.sitemap = self.get_public_sitemap(self.tree) # Store a flat list of every ressour...
sveetch/Sveetoy
[ 1, 1, 1, 7, 1483118147 ]
def recursive_ressources(self, children, pages=[]): """ Return a flat ressources list from given children """ for branch in children: for leaf_name, leaf_content in branch.items(): datas = leaf_content['data'] pages.append(self.view( ...
sveetch/Sveetoy
[ 1, 1, 1, 7, 1483118147 ]
def draw_axis(img, charuco_corners, charuco_ids, board): vecs = np.load("./calib.npz") # I already calibrated the camera mtx, dist, _, _ = [vecs[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')] ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard( charuco_corners, charuco_ids, board, mtx, dist) i...
makelove/OpenCV-Python-Tutorial
[ 2997, 1086, 2997, 11, 1445060268 ]
def make_grayscale(img): ret = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return ret
makelove/OpenCV-Python-Tutorial
[ 2997, 1086, 2997, 11, 1445060268 ]
def __init__(self, *args, **kwargs):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def annotate_clips(self, clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _get_clip_lists(self, clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _annotate_clips(self, clips, classifier):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _get_new_classification(self, old_classification, auto_classification):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _set_clip_score(self, clip, score):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _show_classification_errors(self, triples):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _show_classification_errors_aux(self, category, errors, num_clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def __init__(self, clip_type):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _load_model(self): path = classifier_utils.get_keras_model_file_path(self.clip_type) logging.info(f'Loading classifier model from "{path}"...') return tf.keras.models.load_model(path)
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _load_settings(self): path = classifier_utils.get_settings_file_path(self.clip_type) logging.info(f'Loading classifier settings from "{path}"...') text = path.read_text() d = yaml_utils.load(text) return Settings.create_from_dict(d)
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def classify_clips(self, clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _slice_clip_waveforms(self, clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _get_clip_samples(self, clip):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def _classify_clip(self, index, score, clips):
HaroldMills/Vesper
[ 43, 3, 43, 33, 1398351334 ]
def __init__(self): # Fix some key bindings self.bind("<Control-Key-a>", self.select_all) # We will need Ctrl-/ for the "stroke", but it cannot be unbound, so # let's prevent it from being passed to the standard handler self.bind("<Control-Key-/>", lambda event: "break") ...
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def __init__(self, master=None, **kwargs): Entry.__init__(self, master=None, **kwargs) Diacritical.__init__(self)
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def __init__(self, master=None, **kwargs): ScrolledText.__init__(self, master=None, **kwargs) Diacritical.__init__(self)
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def test(): frame = Frame() frame.pack(fill=BOTH, expand=YES) if os.name == "nt": # Set default font for all widgets; use Windows typical default frame.option_add("*font", "Tahoma 8") # The editors entry = DiacriticalEntry(frame) entry.pack(fill=BOTH, expand=YES) text = Diacr...
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def __init__(self, num_units, num_layers, lstm_impl, use_peephole, parameter_init, clip_activation, num_proj, concat=False, name='pblstm_encoder'): assert num...
hirofumi0810/tensorflow_end2end_speech_recognition
[ 311, 126, 311, 11, 1495618521 ]
def __init__(self, voice = 'Alex', rate = '300'): self.voice = voice self.rate = rate super(AppleSay, self).__init__()
frastlin/PyAudioGame
[ 5, 4, 5, 2, 1420973210 ]
def speak(self, text, interrupt = 0): if interrupt: self.silence() os.system('say -v %s -r %s "%s" &' % (self.voice, self.rate, text))
frastlin/PyAudioGame
[ 5, 4, 5, 2, 1420973210 ]
def _jupyter_server_extension_paths(): return [{"module": "jupyterlmod"}]
cmd-ntrf/jupyter-lmod
[ 26, 11, 26, 5, 1485456063 ]
def _jupyter_nbextension_paths(): return [ dict( section="tree", src="static", dest="jupyterlmod", require="jupyterlmod/main" ) ]
cmd-ntrf/jupyter-lmod
[ 26, 11, 26, 5, 1485456063 ]
def __init__(self, **kwargs): self.__dict__.update(kwargs)
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __eq__(self, other): return self.__dict__ == other.__dict__
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def client(): # The poller itself don't use it, so we don't need something functionnal return AsyncPipelineClient("https://baseurl")
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def async_pipeline_client_builder(): """Build a client that use the "send" callback as final transport layer send will receive "request" and kwargs as any transport layer """ def create_client(send_cb): class TestHttpTransport(AsyncHttpTransport): async def open(self): pass ...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def deserialization_cb(): def cb(pipeline_response): return json.loads(pipeline_response.http_response.text()) return cb
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def polling_response(): polling = AsyncLROBasePolling() headers = {} response = Response() response.headers = headers response.status_code = 200 polling._pipeline_response = PipelineResponse( None, AsyncioRequestsTransportResponse( None, response, ...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def mock_send(http_request, http_response, method, status, headers=None, body=RESPONSE_BODY): if headers is None: headers = {} response = Response() response._content_consumed = True response._content = json.dumps(body).encode('ascii') if body is not None else None re...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def mock_update(http_request, http_response, url, headers=None): response = Response() response._content_consumed = True response.request = mock.create_autospec(Request) response.request.method = 'GET' response.headers = headers or {} response.headers.update({"content-typ...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def mock_outputs(pipeline_response): response = pipeline_response.http_response try: body = json.loads(response.text()) except ValueError: raise DecodeError("Impossible to deserialize") body = {TestBasePolling.convert.sub(r'\1_\2', k).lower(): v f...
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def mock_deserialization_no_body(pipeline_response): """Use this mock when you don't expect a return (last body irrelevant) """ return None
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def no_update_allowed(url, headers=None): raise ValueError("Should not try to update")
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('vid_file') parser.add_argument('box_file') parser.add_argument('annot_file', default=None, help='Ground truth annotation file...
myfavouritekk/TPN
[ 69, 18, 69, 7, 1460708833 ]
def set_user(self, user): for field in self.filters: self.filters[field].field.label = u'<strong>{0}</strong>'.format(self.filters[field].field.label) groups = user.group_set.all() courses = Course.objects.filter(groups__in=groups) course_choices = set() year_choices...
znick/anytask
[ 31, 27, 31, 51, 1416913630 ]
def __init__(self, **kwargs): self.repo_name = kwargs['repo_name'] self.repo_path = kwargs['repo_path'] self.pipelines = kwargs['pipelines']
MetaSUB/ModuleUltra
[ 1, 1, 1, 1, 1506196367 ]
def get_pipeline_list(self): """Return a list of (pipe_name, version).""" return [(pipe['name'], pipe['version']) for pipe in self.pipelines]
MetaSUB/ModuleUltra
[ 1, 1, 1, 1, 1506196367 ]
def get_pipeline_endpts(self, pipe_name): """Return a list of endpts or None.""" return None
MetaSUB/ModuleUltra
[ 1, 1, 1, 1, 1506196367 ]
def __init__(self, repos, total_jobs=10, run_local=True, pipeline_configs={}): self.repos = repos self.total_jobs = int(total_jobs) self.run_local = run_local self.pipeline_configs = pipeline_configs
MetaSUB/ModuleUltra
[ 1, 1, 1, 1, 1506196367 ]