repository_name stringlengths 7 107 | function_path stringlengths 4 190 | function_identifier stringlengths 1 236 | language stringclasses 1
value | function stringlengths 9 647k | docstring stringlengths 5 488k | function_url stringlengths 71 285 | context stringlengths 0 2.51M | license stringclasses 5
values |
|---|---|---|---|---|---|---|---|---|
lostindarkmath/pedantic-python-decorators | pedantic/type_checking_logic/check_types.py | _get_base_generic | python | def _get_base_generic(cls: Any) -> Any:
origin = cls.__origin__ if hasattr(cls, '__origin__') else None
name = cls._name if hasattr(cls, '_name') else None
if name is not None:
return getattr(typing, name)
elif origin is not None:
return origin
return cls | >>> from typing import List, Union, Tuple, Callable, Dict, Set
>>> _get_base_generic(List)
typing.List
>>> _get_base_generic(List[float])
typing.List
>>> _get_base_generic(List[List[float]])
typing.List
>>> _get_base_generic(List[Union[int, float]])
typing... | https://github.com/lostindarkmath/pedantic-python-decorators/blob/66865a958a36440b48e790f22ea42d2beb725b16/pedantic/type_checking_logic/check_types.py#L413-L455 | import inspect
import typing
from io import BytesIO, StringIO, BufferedWriter, TextIOWrapper
from typing import Any, Dict, Iterable, ItemsView, Callable, Union, Optional, Tuple, Mapping, TypeVar, NewType
import collections
import sys
from pedantic.constants import TypeVar as TypeVar_
from pedantic.exceptions import Ped... | Apache License 2.0 |
seung-lab/chunkflow | chunkflow/chunk/base.py | Chunk.ndoffset | python | def ndoffset(self) -> tuple:
if self.ndim == 4:
return (0, *self.voxel_offset)
else:
return self.voxel_offset | make the voxel offset have the same dimension with array | https://github.com/seung-lab/chunkflow/blob/0e032cdf4f2ba104af4f7809ac11df17352384ed/chunkflow/chunk/base.py#L395-L402 | from typing import Union
import os
from numbers import Number
import h5py
import numpy as np
import nrrd
from numpy.core.numerictypes import issubdtype
from numpy.lib.mixins import NDArrayOperatorsMixin
from scipy.ndimage import gaussian_filter
import tifffile
import cc3d
from cloudvolume.lib import yellow, Bbox
from c... | Apache License 2.0 |
twisted/axiom | axiom/tags.py | Catalog.tagNames | python | def tagNames(self):
return self.store.query(_TagName, _TagName.catalog == self).getColumn("name") | Return an iterator of unicode strings - the unique tag names which have
been applied objects in this catalog. | https://github.com/twisted/axiom/blob/28191ede99287e9a87c1ff561b831f7d80aaa2fe/axiom/tags.py#L83-L88 | from epsilon.extime import Time
from axiom.item import Item
from axiom.attributes import text, reference, integer, AND, timestamp
class Tag(Item):
typeName = 'tag'
schemaVersion = 1
name = text(doc="""
The short string which is being applied as a tag to an Item.
""")
created = timestamp(doc="""
... | MIT License |
fredhutch/proxmox-tools | prox/cmdprox.py | ssh_exec | python | def ssh_exec(user, pwd, commands, host):
if not isinstance(commands, list):
print('commands parameter in ssh_exec needs to be a list')
return False
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pwd)... | execute list of commands via ssh | https://github.com/fredhutch/proxmox-tools/blob/cfd4d7333969d3ad8af80f15be56d0d5052fee4e/prox/cmdprox.py#L949-L961 | import sys, os, subprocess, re, platform, getpass, argparse, logging, hostlist
import time, warnings, functools, random, json, requests, paramiko, socket
try:
import easygui
except:
pass
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
try:
from .pyp... | Apache License 2.0 |
derfies/panda3d-editor | src/pandaEditor/ui/mainFrame.py | MainFrame.OnFileSave | python | def OnFileSave(self, evt, saveAs=False):
if self.base.doc.file_path is None or saveAs:
filePath = self._GetSavePath()
if filePath:
self.base.doc.file_path = filePath
else:
return
self.base.doc.save() | Save the document. | https://github.com/derfies/panda3d-editor/blob/a50939bd4bfa5c22d27a9ddee090717e8d95f404/src/pandaEditor/ui/mainFrame.py#L248-L262 | import os
import sys
import wx
import wx.aui
import wx.propgrid as wxpg
from pubsub import pub
import panda3d.core as pm
import p3d
from direct.showbase.PythonUtil import getBase as get_base
from wxExtra import utils as wxUtils, ActionItem
from wxExtra.logpanel import LogPanel
from wxExtra import AuiManagerConfig, Cust... | MIT License |
obi-wan3/ob13-cogs | mentionhelp/mentionhelp.py | MentionHelp._mention_help | python | async def _mention_help(self, ctx: commands.Context): | Send a message when a user mentions the bot (with no other text). | https://github.com/obi-wan3/ob13-cogs/blob/716527f8581e0345802ea2626d43324f87edf941/mentionhelp/mentionhelp.py#L79-L80 | import re
import discord
from redbot.core import commands, Config
class MentionHelp(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 14000605, force_registration=True)
default_guild = {
"toggle": True
}
default_global = {
... | MIT License |
medtagger/medtagger | backend/medtagger/repositories/label_tags.py | enable | python | def enable(label_tag_key: str) -> None:
enabling_query = LabelTag.query.filter(LabelTag.key == label_tag_key)
updated = enabling_query.update({'disabled': False}, synchronize_session='fetch')
if not updated:
raise InternalErrorException(f'Label Tag "{label_tag_key}" was not enabled due to unknown da... | Enable existing Label Tag. | https://github.com/medtagger/medtagger/blob/8b7575e55764a95d2040f3b9bcd23b6ff846ecaa/backend/medtagger/repositories/label_tags.py#L75-L80 | from typing import List
from medtagger.database import db_transaction_session
from medtagger.database.models import LabelTag
from medtagger.definitions import LabelTool
from medtagger.exceptions import InternalErrorException
from medtagger.types import TaskID
def get_all_tags(include_disabled: bool = False) -> List[Lab... | Apache License 2.0 |
linmx0130/ya_mxdet | train_faster_rcnn.py | train_dataset | python | def train_dataset():
train_dataset = VOCDataset(annotation_dir=cfg.annotation_dir,
img_dir=cfg.img_dir,
dataset_index=cfg.dataset_index,
transform=train_transformation,
resize_func=img_resize)
... | prepare a custom dataset
return: train_dataset | https://github.com/linmx0130/ya_mxdet/blob/eaa6de7faf819f3720d8dac64c57a42dec38eed7/train_faster_rcnn.py#L37-L47 | from faster_rcnn.config import cfg
from VOCDataset import VOCDataset
from faster_rcnn.faster_rcnn import FasterRCNN
import mxnet as mx
from faster_rcnn.utils import random_flip, imagenetNormalize, img_resize, random_square_crop, select_class_generator, bbox_inverse_transform, softmax_celoss_with_ignore
from faster_rcnn... | MIT License |
usc-isi-i2/rltk | rltk/record.py | remove_raw_object | python | def remove_raw_object(cls):
cls._remove_raw_object = True
return cls | Decorator for Record class.
If a Record class is decorated, raw_object will be removed once all mark properties are cached. | https://github.com/usc-isi-i2/rltk/blob/aee10ed5dd561583e60db3373ed82fe1208da1e9/rltk/record.py#L75-L81 | import re
from typing import Callable
re_record_id = re.compile(r'^[^*]{1,255}$')
re_valid_property_name = re.compile(r'^[A-Za-z_]{1}[\w]*$')
class Record(object):
_remove_raw_object = False
def __init__(self, raw_object):
self.raw_object = raw_object
@property
def id(self):
raise NotImp... | MIT License |
google-research/long-range-arena | lra_benchmarks/models/reformer/reformer.py | ReformerDualEncoder.apply | python | def apply(self,
inputs1,
inputs2,
vocab_size=None,
inputs1_positions=None,
inputs2_positions=None,
inputs1_segmentation=None,
inputs2_segmentation=None,
use_bfloat16=False,
emb_dim=512,
num_heads=8,
... | Applies Transformer model on text similarity.
A deliberate choice to distinguish this from NLI because
we may want to do different things to the model later. Dual Encoding
mode enforces that we do not do cross attention between pairs.
Args:
inputs1: input data.
inputs2: target data.
... | https://github.com/google-research/long-range-arena/blob/09c2916c3f33a07347dcc70c8839957d3c9d4062/lra_benchmarks/models/reformer/reformer.py#L204-L284 | from flax import nn
import jax.numpy as jnp
from lra_benchmarks.models.layers import common_layers
from lra_benchmarks.models.reformer import reformer_attention
class ReformerBlock(nn.Module):
def apply(self,
inputs,
qkv_dim,
mlp_dim,
num_heads,
dtype=jnp.fl... | Apache License 2.0 |
beartype/beartype | beartype/_decor/_code/_pep/pepcode.py | _unmemoize_pep_code | python | def _unmemoize_pep_code(
data: BeartypeData,
func_wrapper_code: str,
pith_repr: str,
hint_forwardrefs_class_basename: tuple,
) -> str:
assert data.__class__ is BeartypeData, f'{repr(data)} not @beartype data.'
assert isinstance(func_wrapper_code, str), (
f'{repr(func_wrapper_code)} not s... | Convert the passed memoized code snippet type-checking any parameter or
return of the decorated callable into a memoized code snippet type-checking
a specific parameter or return of that callable.
Specifically, this function (in order):
#. Globally replaces all references to the
:data:`PEP_CODE... | https://github.com/beartype/beartype/blob/9da0bbebe408d281d5bfb6cc203dc6969e241aa4/beartype/_decor/_code/_pep/pepcode.py#L237-L331 | from beartype.roar import BeartypeDecorHintPepException
from beartype._decor._cache.cachetype import (
bear_typistry,
register_typistry_forwardref,
)
from beartype._decor._code.codesnip import ARG_NAME_TYPISTRY
from beartype._decor._code._pep._pephint import pep_code_check_hint
from beartype._decor._code._pep._... | MIT License |
visualcomputinginstitute/3d-semantic-segmentation | tools/lazy_decorator.py | lazy_property | python | def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return getattr(self, attribute)
return decorator | caches the output of the property and just returns the value for next calls
:param function: property to be cached
:return: cached output of property | https://github.com/visualcomputinginstitute/3d-semantic-segmentation/blob/1dfc010b370a346902ad29460c9ad969c1892a97/tools/lazy_decorator.py#L10-L25 | import functools | MIT License |
nuagenetworks/vspk-python | vspk/v5_0/nuvirtualip.py | NUVirtualIP.associated_floating_ip_id | python | def associated_floating_ip_id(self):
return self._associated_floating_ip_id | Get associated_floating_ip_id value.
Notes:
Id of Floating IP address associated to this virtual ip
This attribute is named `associatedFloatingIPID` in VSD API. | https://github.com/nuagenetworks/vspk-python/blob/375cce10ae144ad6017104e57fcd3630898cc2a6/vspk/v5_0/nuvirtualip.py#L253-L263 | from .fetchers import NUMetadatasFetcher
from .fetchers import NUGlobalMetadatasFetcher
from .fetchers import NUEventLogsFetcher
from bambou import NURESTObject
class NUVirtualIP(NURESTObject):
__rest_name__ = "virtualip"
__resource_name__ = "virtualips"
CONST_IP_TYPE_IPV6 = "IPV6"
CONST_IP_TYPE_IPV4 = ... | BSD 3-Clause New or Revised License |
v7labs/darwin-py | darwin/dataset/remote_dataset.py | RemoteDataset.push | python | def push(
self,
files_to_upload: Optional[List[Union[PathLike, LocalFile]]],
*,
blocking: bool = True,
multi_threaded: bool = True,
fps: int = 0,
as_frames: bool = False,
files_to_exclude: Optional[List[PathLike]] = None,
path: Optional[str] = None... | Uploads a local dataset (images ONLY) in the datasets directory.
Parameters
----------
files_to_upload : Optional[List[Union[PathLike, LocalFile]]]
List of files to upload. Those can be folders.
blocking : bool
If False, the dataset is not uploaded and a generato... | https://github.com/v7labs/darwin-py/blob/694253ec520ec32d791eb4a2d0b8acc9ad686b33/darwin/dataset/remote_dataset.py#L88-L168 | import json
import shutil
import tempfile
import zipfile
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Union
from urllib import parse
from darwin.dataset.download_manager import download_all_images_from_annotations
from darwin.dat... | MIT License |
prajdabre/yanmtt | transformers/src/transformers/models/t5/modeling_tf_t5.py | TFT5Attention.compute_bias | python | def compute_bias(self, query_length, key_length):
context_position = tf.range(query_length)[:, None]
memory_position = tf.range(key_length)[None, :]
relative_position = memory_position - context_position
relative_position_bucket = self._relative_position_bucket(
relative_po... | Compute binned relative position bias | https://github.com/prajdabre/yanmtt/blob/4d329c3bcb81ca432d5947bb4673897086ee7f32/transformers/src/transformers/models/t5/modeling_tf_t5.py#L226-L240 | import copy
import itertools
import math
import warnings
from typing import Tuple
import tensorflow as tf
from ...activations_tf import get_tf_activation
from ...file_utils import (
DUMMY_INPUTS,
DUMMY_MASK,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
fr... | MIT License |
asteroid-team/asteroid | asteroid/dsp/overlap_add.py | LambdaOverlapAdd.ola_forward | python | def ola_forward(self, x):
assert x.ndim == 3
batch, channels, n_frames = x.size()
unfolded = torch.nn.functional.unfold(
x.unsqueeze(-1),
kernel_size=(self.window_size, 1),
padding=(self.window_size, 0),
stride=(self.hop_size, 1),
)
... | Heart of the class: segment signal, apply func, combine with OLA. | https://github.com/asteroid-team/asteroid/blob/64e10e9de840ada77719ff4fa280be42a19aa51c/asteroid/dsp/overlap_add.py#L84-L131 | import torch
from torch import nn
from ..losses.pit_wrapper import PITReorder
class LambdaOverlapAdd(torch.nn.Module):
def __init__(
self,
nnet,
n_src,
window_size,
hop_size=None,
window="hanning",
reorder_chunks=True,
enable_grad=False,
):
... | MIT License |
conchylicultor/musicgenerator | deepmusic/modulemanager.py | ModuleManager.save | python | def save(self, config_group):
config_group[self.name] = ' '.join([self.module_name] + self.module_parameters) | Save the current module parameters
Args:
config_group (dict): dictionary where to write the configuration | https://github.com/conchylicultor/musicgenerator/blob/adea76dccaba923b7d3807082ec6f5b512d16bb9/deepmusic/modulemanager.py#L111-L117 | from collections import OrderedDict
class ModuleManager:
def __init__(self, name):
self.name = name
self.modules = OrderedDict()
self.module_instance = None
self.module_name = ''
self.module_parameters = []
def register(self, module):
assert not module.get... | Apache License 2.0 |
markblundeberg/openswap | lib/util.py | bh2u | python | def bh2u(x):
return hfu(x).decode('ascii') | str with hex representation of a bytes-like object
>>> x = bytes((1, 2, 10))
>>> bh2u(x)
'01020A'
:param x: bytes
:rtype: str | https://github.com/markblundeberg/openswap/blob/7de04aa80dab79bebe4b64483011dad70a48694c/lib/util.py#L356-L367 | import binascii
import os, sys, re, json
from collections import defaultdict
from datetime import datetime
import decimal
from decimal import Decimal
import traceback
import threading
import hmac
import stat
from .i18n import _
import queue
def inv_dict(d):
return {v: k for k, v in d.items()}
base_units = {'BCH':8,... | MIT License |
spilchen/yahoo_fantasy_api | yahoo_fantasy_api/league.py | League.edit_date | python | def edit_date(self):
if self.edit_date_cache is None:
json = self.yhandler.get_settings_raw(self.league_id)
t = objectpath.Tree(json)
edit_key = t.execute('$..edit_key[0]')
self.edit_date_cache = datetime.datetime.strptime(edit_key, '%Y-%m-%d').date... | Return the next day that you can edit the lineups.
:return: edit date
:rtype: :class: datetime.date | https://github.com/spilchen/yahoo_fantasy_api/blob/867444eecffe46541c9c099f4ffc06ab5c178bd2/yahoo_fantasy_api/league.py#L579-L591 | import yahoo_fantasy_api as yfa
from yahoo_fantasy_api import yhandler
import objectpath
import datetime
import re
class League:
def __init__(self, sc, league_id):
self.sc = sc
self.league_id = league_id
self.yhandler = yhandler.YHandler(sc)
self.current_week_cache = None
sel... | MIT License |
iristyle/chocolateypackages | EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/pyflakes/checker.py | Checker._runDeferred | python | def _runDeferred(self, deferred):
for handler, scope in deferred:
self.scopeStack = scope
handler() | Run the callables in C{deferred} using their associated scope stack. | https://github.com/iristyle/chocolateypackages/blob/8c9833710577de6db6e8b1db5d9196e19e19d117/EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/pyflakes/checker.py#L229-L235 | import __builtin__
import os.path
import _ast
from pyflakes import messages
try:
import ast
iter_child_nodes = ast.iter_child_nodes
except (ImportError, AttributeError):
def iter_child_nodes(node, astcls=_ast.AST):
for name in node._fields:
field = getattr(node, name, None)
i... | MIT License |
artyompal/tpu_models | models/official/detection/evaluation/coco_utils.py | generate_annotation_file | python | def generate_annotation_file(groundtruth_generator,
annotation_file):
groundtruths = {}
tf.logging.info('Loading groundtruth annotations from dataset to memory...')
for groundtruth in groundtruth_generator():
for k, v in six.iteritems(groundtruth):
if k not in groundtruths:
... | Generates COCO-style annotation JSON file given a groundtruth generator. | https://github.com/artyompal/tpu_models/blob/639306f30e085bb1cdb5b1118a4c96a2dbe14e3e/models/official/detection/evaluation/coco_utils.py#L345-L361 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import json
import numpy as np
from PIL import Image
from pycocotools import coco
from pycocotools import mask as mask_utils
import six
import tensorflow as tf
from dataloader import tf_example_decod... | Apache License 2.0 |
e-loue/pyke | pyke/target_pkg.py | target_pkg.reset | python | def reset(self, check_sources = True):
if debug: print >> sys.stderr, "target_pkg.reset"
self.dirty = False
self.check_sources = check_sources
self.source_packages = {}
self.compiled_targets = set()
self.rb_names = set() | This should be called once by engine.__init__ prior to calling
add_source_package. | https://github.com/e-loue/pyke/blob/cfe95d8aaa06de123264f9b7f5bea20eb5924ecd/pyke/target_pkg.py#L180-L192 | from __future__ import with_statement
import os, os.path
import time
import sys
import re
import pyke
debug = False
Name_test = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
class target_pkg(object):
def __init__(self, module_name, filename = None,
pyke_version = pyke.version,
... | MIT License |
zomux/deepy | deepy/trainers/base.py | NeuralTrainer.load_params | python | def load_params(self, path, exclude_free_params=False):
self.network.load_params(path, exclude_free_params=exclude_free_params)
self.best_params = self.copy_params()
if self.network.train_logger.progress() > 0 or self.network.train_logger.epoch() > 0:
self.skip(self.network.train_log... | Load parameters for the training.
This method can load free parameters and resume the training progress. | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/trainers/base.py#L144-L153 | import sys
import time
import numpy as np
import theano
from ..conf import TrainerConfig
from ..core import env, runtime
from ..utils import Timer
from ..dataset import Dataset
from controllers import TrainingController
from abc import ABCMeta, abstractmethod
from logging import getLogger
logging = getLogger("trainer")... | MIT License |
neuropycon/graphpype | graphpype/labeled_mask.py | compute_ROI_nii_from_ROI_coords_files | python | def compute_ROI_nii_from_ROI_coords_files(
ref_img_file, MNI_coords_file, labels_file, neighbourhood=1):
ref_image = nib.load(ref_img_file)
ref_image_data = ref_image.get_data()
ref_image_data_shape = ref_image_data.shape
ref_image_data_sform = ref_image.get_sform()
ROI_MNI_coords_list = np.... | Export single file VOI binary nii image | https://github.com/neuropycon/graphpype/blob/409a370e7d293c3fcff0d733bf7af50850dfa9e4/graphpype/labeled_mask.py#L256-L309 | import nipype.interfaces.spm as spm
from nipype.utils.filemanip import split_filename as split_f
from graphpype.utils import check_np_dimension
import itertools as iter
import numpy as np
import nibabel as nib
import glob
import os
from scipy import ndimage as ndimg
from scipy.spatial.distance import cdist
def _coord_t... | BSD 3-Clause New or Revised License |
sanic-org/sanic | sanic/server/socket.py | remove_unix_socket | python | def remove_unix_socket(path: Optional[str]) -> None:
if not path:
return
try:
if stat.S_ISSOCK(os.stat(path, follow_symlinks=False).st_mode):
with socket.socket(socket.AF_UNIX) as testsock:
try:
testsock.connect(path)
except Connect... | Remove dead unix socket during server exit. | https://github.com/sanic-org/sanic/blob/3262878ebd41aa2230ef15d4475bbcf223b2356b/sanic/server/socket.py#L74-L87 | from __future__ import annotations
import os
import secrets
import socket
import stat
from ipaddress import ip_address
from typing import Optional
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
try:
ip = ip_address(host)
host = str(ip)
sock = socket.socket(
... | MIT License |
YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
Dataset Summary
Scotch is a dataset of about 19 million functions collected from open-source repositiories from GitHub with permissive licenses. Each function has its corresponding code context and about 4 million functions have corresponding docstrings.
Languages
The dataset includes functions written in programming languages Python, Java, Javascript, and Go.
Statistics
Split
The functions with docstrings is splitted into train, valid, and test set of 3200626, 400077, 400080 functions respectively.
Features
Each function consists of following features:
- repository_name: Name of the repository the function belongs to.
- function_path: Path of the function within the repository.
- function_identifier: Function name/identifier.
- language: Programming language the function is written in.
- function: Function string.
- docstring: Function docstring.
- function_url: URL to the function code.
- context: Code context.
- license: License info of the repository (includes only repositories with permissive licenses).
Data Collection
The dataset is collected from GitHub repositories of respective languages with 5 or more stars. Such repositories are listed using SEART. Functions are parsed using a lightweight parser build on top of function parser from CodeSearchNet dataset and repositories were collected with help of github-downloader from EleutherAI.
Data Processing
All the code without permissive licenses are removed and deduplication is performed on the remaining set of functions. Afterwards, all the functions with single line of code, whose docstring contains non-English characters are removed. Files with multiple same functions are excluded. This results in about 19M functions. To obtain a dataset of NL-Code pairs, functions with no docstrings or doctrings less than 3 tokens separated by white-space are excluded. Following CodeSearchNet, functions with 'test' keyword in their name are excluded.
License
This dataset is under MIT License. However, the repositories the functions are collected from may have several permissive licenses. Those licenses include MIT License, Apache License 2.0, BSD 3-Clause “New” or “Revised” License, BSD 2-Clause “Simplified” License, and ISC License.
- Downloads last month
- 344