query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
extension of model file to save to this should depends on what format model is saved under | def _get_model_file_extension(self):
pass | [
"def _get_model_filename(self) -> str:\n model_filename = f'{self.model_dir}/{self.description}.{self._get_model_file_extension()}'\n return model_filename",
"def _save_model(self, out_file):\n pass",
"def _get_model_save_path(self):\n return '{0}/{1}.ckpt'.format(self._get_save_dir(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save the model to out_file | def _save_model(self, out_file):
pass | [
"def save(self,file):\n assert \".pymodel\" in file\n with open(file,\"w\") as stream:\n pickle.dump(self,stream)",
"def __saveModel(self, filename):\n if filename != None and filename != \"\":\n joblib.dump(self.model, filename)",
"def save_model(self):\n f1 = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates sklearn like classification report dictionary | def _calculate_classification_report(self) -> dict:
pass | [
"def classification_report(self,X,y):\n y_pred = self.predict(X)\n clfr = classification_report(y, y_pred)\n\treturn clfr",
"def createNBClassifier(data):\n\n # for each feature, need to calculate probability of True/False\n\n # get the 2 classes\n classes = set([])\n for d in data:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets sizes for training and test sets | def _get_sizes(self) -> int:
pass | [
"def test_size(self):\n return self.__test_batches * len(self.__sources)",
"def _train_batch_sizes(self):\n for device in device_lib.list_local_devices():\n # TODO(b/141475121): We need some way to check which batch sizes would\n # work using a public API.\n if tf.DeviceSpec.from_string(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return substrings of length n in both a and b | def substrings(a, b, n):
# TODO
la = len(a)
lb = len(b)
sub_a = []
sub_b = []
sub = []
for i in range(la-n+1):
sub_a.append(a[i:i+n])
for j in range(lb-n+1):
sub_b.append(b[j:j+n])
for k in sub_a:
if k in sub_b:
sub.append(k)
sub = set(sub... | [
"def substrings(a, b, n):\n\n result_a = [a[i:i+n] for i in range(len(a))]\n result_b = [b[i:i+n] for i in range(len(b))]\n\n return compare_lists(result_a, result_b)",
"def getSubstrings(a, n):\n\n # Get substrings from string\n substrings = set()\n for i in range(0, len(a) - n + 1):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain a function signature, for Python 2. This analyzes the function argument specification and constructs the argument order, required set of arguments, and optional set of arguments. | def _getsig(func):
# Get the argument specification
argspec = inspect.getargspec(func)
order = argspec.args[:]
# Figure out how many are optional
if argspec.defaults:
defcnt = -len(argspec.defaults)
required = set(order[:defcn... | [
"def trampoline_signature(fn):\n\n # TODO: operator overloads\n names = []\n\n if fn[\"const\"]:\n names.append(\"K\")\n refqual = fn[\"ref_qualifiers\"]\n if refqual:\n if refqual == \"&\":\n names.append(\"R\")\n if refqual == \"&&\":\n names.append(\"O\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize an ``InjectorCleanup`` instance. | def __init__(self, injector):
self.injector = injector
self.keep = None | [
"def initialize(cls, io_loop=None):\r\n if cls._initialized:\r\n return\r\n if io_loop is None:\r\n io_loop = ioloop.IOLoop.current()\r\n cls._old_sigchld = signal.signal(\r\n signal.SIGCHLD,\r\n lambda sig, frame: io_loop.add_callback_from_signal(cls... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit the context manager. This deletes all keys added to the injector since the context manager was entered. The exception, if any, is not handled. | def __exit__(self, exc_type, exc_value, exc_tb):
# Must not be None
assert self.keep is not None
# Delete the added keys
for key in self.injector._keys - self.keep:
del self.injector[key]
# Reset keep
self.keep = None
return None | [
"def __exit__(self, exc_type, exc_val, exc_tb):\n # Try to clean up what we can before exiting.\n for rg in self.redundancy_groups:\n while rg:\n try:\n self.pop_and_cleanup_route_reflector(rg)\n except KeyboardInterrupt:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the value of an item. This also discards any deferred callable that has been set for the key. | def __delitem__(self, key):
# Handle the KeyError case first
if key not in self._keys:
raise KeyError(key)
# Pop it off
self._available.pop(key, None)
self._deferred.pop(key, None)
self._keys.discard(key) | [
"def remove_item(self, key, value):\n ...",
"def delete(self, key, item): # noqa\n return self.execute_command(CF_DEL, key, item)",
"def _delitem(\n self,\n key: K,\n ) -> None:\n if test_mode:\n assert (\n self._lock.locked()\n ), \"Th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a deferred callable for a key. This may be used when a value for a key should only be generated if the function being called actually wants the value, usually because generating the value is somewhat expensive. | def set_deferred(self, key, func):
self._deferred[key] = func | [
"def set_lazy(self, key, value_callable):\n if key in self._dic:\n del self._dic[key]\n self._lazyload[key] = value_callable",
"def setter(self, fn):\n self.cb_set = fn",
"def makeKeyGetter( k ):\n def myFunc( v ):\n return k( v[1] )\n print('making key getter for k=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function decorator that allows dependency injection to be tailored. In most cases, it is not necessary to use this decorator; it may be used when a function takes all keyword argumentsi.e., a ``kwargs`` or similar argument is presentbut the developer wishes to restrict the set of injectible arguments. | def inject(required=None, optional=None):
# The actual decorator; just calls from_func() with appropriate
# arguments
def decorator(func):
WantSignature.from_func(func, required=required, optional=optional)
return func
return decorator | [
"def inject_config(function):\n\n @wraps(function)\n def wrapper(*args, **kwargs):\n sig = signature(function)\n\n # for each parameter that wasn't passed as args\n for parameter_name in list(sig.parameters)[len(args):]:\n # and wasn't passed in kwargs\n if kwargs.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function decorator for wrapping decorators. This works just like ``six.wraps()`` (which in turn works just like ``functools.wraps()``), but additionally manages dependency injection metadata, allowing decorators to request data independent of the function they wrap. | def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES, provides=None,
required=_unset, optional=_unset):
# The actual decorator
def decorator(func):
# Generate the signature first
sig = WantSignature.from_func(
func, wrapped... | [
"def decorator_with_args(decorator_to_enhance):\n\n # We use the same trick we did to pass arguments\n def decorator_maker(*args, **kwargs):\n\n # We create on the fly a decorator that accepts only a function\n # but keeps the passed arguments from the maker.\n def decorator_wrapper(func)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call a wrapped function with appropriate dependency injection. This is for use by decorators that wrap a function that will be called via dependency injection, and ensures that the function is called only with the desired keyword arguments. | def call_wrapped(func, args, kwargs):
# Get the function's injection signature
sig = WantSignature.from_func(func)
# Call the function
return sig(args, kwargs) | [
"def inject(required=None, optional=None):\n\n # The actual decorator; just calls from_func() with appropriate\n # arguments\n def decorator(func):\n WantSignature.from_func(func, required=required, optional=optional)\n return func\n\n return decorator",
"def with_argspec(f):\n @wraps... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if a function wants a particular keyword argument. | def wants(func, keyword):
# Get the function's injection signature
sig = WantSignature.from_func(func)
# See if it wants the argument
return keyword in sig | [
"def test_KeywordParameterIsIncluded(self):\n def function_with_kw(**kw):\n return\n #---\n self.local_register.RPCFunction(function_with_kw)\n\n kwargs_var_name = self.server_stub.definitions[self.module]['function_with_kw']['args']['kwargs_var']\n assert kwargs_var_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the request_type of this RequestForMe. | def request_type(self):
return self._request_type | [
"def get_request_type(self, ):\n return self._request_type",
"def get_type(self) -> str:\n return self.request_type",
"def get_request_type(type):\n uo_type = None\n if isinstance(type, (types.IntType, types.LongType)):\n uo_type = int(type)\n elif isinstance(type, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the request_type of this RequestForMe. | def request_type(self, request_type):
self._request_type = request_type | [
"def get_request_type(self, ):\n return self._request_type",
"def set_type(self, type):\n return _raw_util.raw_message_set_type(self, type)",
"def input_type(self, input_type):\n\n self._input_type = input_type",
"def set_task_type(self, task_type):\n self._task_type = task_type",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary containing minimum version for each python package. | def min_python_module_version():
## read from file: prog2default.csv
python_modules = file_list("python_requirements")
package_min_versions = HCGB_main.file2dictionary(python_modules, ",")
return(package_min_versions) | [
"def return_min_version_python_package(package):\r\n\tversion_package = min_python_module_version()\r\n\treturn (version_package[package])",
"def get_package_versions() -> Dict[str, str]:\n import pkg_resources\n\n package_dict = pkg_resources.working_set.by_key # type: ignore\n package_version_dict = {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves minimum version requirement for the given package. | def return_min_version_python_package(package):
version_package = min_python_module_version()
return (version_package[package]) | [
"def get_minimum_version(requirement):\n if not requirement.specs:\n warnings.warn(f\"No version specifier for {requirement.name} in \"\n \"install_requires. Using lowest available version on PyPi.\",\n stacklevel=2)\n content = urllib.request.urlopen(f'https:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a book to the shelf if there is room. | def AddBook(self, book):
thickness = book.GetThickness()
if self.__available_capacity >= thickness:
self.__books[book.GetTitle()] = book
self._ReduceCapacity(thickness)
else:
raise RuntimeError("Add failed: No space available on shelf.") | [
"def add_book(self, book: Book):\n self.books.append(book)",
"def add_book(name):\n if check_book_in_library(name):\n msg = f\"{name} is already in the Library\"\n else:\n add_book_to_library(name)\n msg = f\"{name} added to the Library\"\n click.echo(msg)",
"def create_book... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a book from the shelf if it resides on the shelf. | def RemoveBook(self, title):
stored_title = book.Book.TransformTitle(title)
if stored_title in self.__books:
stored_book = self.__books[stored_title]
thickness = stored_book.GetThickness()
del self.__books[stored_title]
self._IncreaseCapacity(thickness)
... | [
"def remove_book(self, book: Book):\n self.books.remove(book)",
"def remove_book(self):\n \n try:\n self.clr_scr()\n serial_no=input(\"Enter serial number of book:\\t\\t\") #enter serial_no of book you want to delete.\n Library.library.pop(serial_no,\"No suc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of books on the shelf. | def GetBookCount(self):
return len(self.__books) | [
"def number_of_bookings(bookings_registry=DEFAULT_BOOKING_REGISTRY):\n return _db.number_of_items(Booking, bookings_registry)",
"def getNumberOfRecipes():\n\n with sessionInstance() as session:\n return session.query(models.Recipe).count()",
"def getNumEntries(self) -> \"int\":\n return _coi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the initial capacity of the shelf. | def GetInitialCapacity(self):
return self.__length | [
"def initial_size(self):\n ret = self._get_attr(\"initialSize\")\n return ret",
"def capacity(cls):\n return WellPlate96.size() // PreyStoragePlate.capacity()",
"def min_capacity(self) -> jsii.Number:\n return self._values.get(\"min_capacity\")",
"def capacity(self):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reduces shelf capacity (after a book is added). | def _ReduceCapacity(self, thickness):
self.__available_capacity -= thickness | [
"def AddBook(self, book):\n thickness = book.GetThickness()\n if self.__available_capacity >= thickness:\n self.__books[book.GetTitle()] = book\n self._ReduceCapacity(thickness)\n else:\n raise RuntimeError(\"Add failed: No space available on shelf.\")",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that applies a simple onereactant oneproduct reaction SMILES to a list of input RDKit molecules, returning the products as a list of RDKit molecules. | def simple_rxn(mol_list, rxn, debug=False):
prod_list = []
for mol in mol_list:
if debug:
logging.info('Input: '+ MolToSmiles(mol))
products = rxn.RunReactants((Chem.AddHs(mol),))
if debug:
logging.info('Products: {}'.format(products))
if products != ():
... | [
"def pair_rxnts(mol1_list, mol2_list, rxn, debug=False): \n prod_list = []\n for mol1 in mol1_list:\n for mol2 in mol2_list:\n\n products = rxn.RunReactants((Chem.AddHs(mol1),Chem.AddHs(mol2)))\n if debug:\n logging.info(products)\n if products != ():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that applies a tworeactant oneproduct reaction SMILES to two lists of input RDKit molecules, returning the products as a list of RDKit molecules. | def pair_rxnts(mol1_list, mol2_list, rxn, debug=False):
prod_list = []
for mol1 in mol1_list:
for mol2 in mol2_list:
products = rxn.RunReactants((Chem.AddHs(mol1),Chem.AddHs(mol2)))
if debug:
logging.info(products)
if products != ():
... | [
"def _join_product(*iterables):\n end_product = []\n for iterable in iterables:\n if len(iterable) > 1:\n end_product.extend(iterable)\n else:\n end_product.append(iterable[0])\n return tuple(end_product)",
"def simple_rxn(mol_list, rxn, deb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replaces the external networks by xwards and equivalent impedance | def _replace_external_area_by_xwards(net_external, bus_lookups, xward_parameter_no_power,
impedance_parameter, ext_buses_with_xward,
show_computing_time, calc_volt_angles=True,
runpp_fct=_runpp_except_voltage... | [
"def annplastic(adaptation):\n # layers network\n inLayer = LinearLayer(100)\n hiddenLayer = LinearLayer(adaptation)\n outLayer = LinearLayer(10)\n # mount layers\n n.addInputModule(inLayer)\n n.addModule(hiddenLayer)\n n.addOutputModule(outLayer)\n # stabilise type confections\n in_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the coder to the text. Returns the encoded text. | def applyCoder(text, coder):
newtext=""
for i in range(len(text)):
if text[i].isalpha():
newtext+=coder[text[i]]
else:
newtext+=text[i]
return newtext | [
"def apply_coder(text, coder):\n ### TODO.\n codedText = ''\n for char in text:\n if char in coder:\n codedText += coder[char]\n else:\n codedText += char\n return codedText",
"def encode_text(self, text):\n encoded_text = \"\"\n for char in text:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if basis is insertion encodable by rightmost. | def is_insertion_encodable_rightmost(basis: Iterable[Perm]) -> bool:
curr = 0
for perm in basis:
curr = curr | InsertionEncodablePerms._insertion_encodable_properties(perm)
if curr == InsertionEncodablePerms._ALL_PROPERTIES:
return True
return False | [
"def is_insertion_encodable(basis: Iterable[Perm]) -> bool:\n return InsertionEncodablePerms.is_insertion_encodable_rightmost(\n basis\n ) or InsertionEncodablePerms.is_insertion_encodable_maximum(basis)",
"def is_insertion_encodable_maximum(basis: Iterable[Perm]) -> bool:\n curr =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if basis is insertion encodable by maximum. | def is_insertion_encodable_maximum(basis: Iterable[Perm]) -> bool:
curr = 0
for perm in basis:
curr = curr | InsertionEncodablePerms._insertion_encodable_properties(
perm.rotate()
)
if curr == InsertionEncodablePerms._ALL_PROPERTIES:
re... | [
"def is_insertion_encodable(basis: Iterable[Perm]) -> bool:\n return InsertionEncodablePerms.is_insertion_encodable_rightmost(\n basis\n ) or InsertionEncodablePerms.is_insertion_encodable_maximum(basis)",
"def is_insertion_encodable_rightmost(basis: Iterable[Perm]) -> bool:\n curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if basis is insertion encodable. | def is_insertion_encodable(basis: Iterable[Perm]) -> bool:
return InsertionEncodablePerms.is_insertion_encodable_rightmost(
basis
) or InsertionEncodablePerms.is_insertion_encodable_maximum(basis) | [
"def is_inserted(self):\n return self.code < -200",
"def is_insertion(ival):\n is_ins = ival.fields[18].endswith('insertion')\n return is_ins",
"def is_insertion_encodable_rightmost(basis: Iterable[Perm]) -> bool:\n curr = 0\n for perm in basis:\n curr = curr | InsertionEnc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a Google Cloud Storage service object. | def GcsApi(self) -> 'googleapiclient.discovery.Resource':
return common.CreateService(
'storage', self.CLOUD_STORAGE_API_VERSION) | [
"def _GetService() -> object_storage_service.ObjectStorageService: # pytype: disable=not-instantiable\n # TODO(pclay): consider using FLAGS.storage to allow cross cloud testing?\n cloud = FLAGS.cloud\n providers.LoadProvider(cloud)\n service = object_storage_service.GetObjectStorageClass(cloud)()\n # This met... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get API operation object metadata for Google Cloud Storage object. | def GetObjectMetadata(self,
gcs_path: str,
user_project: Optional[str] = None) -> Dict[str, Any]:
if not gcs_path.startswith('gs://'):
gcs_path = 'gs://' + gcs_path
bucket, object_path = SplitStoragePath(gcs_path)
gcs_objects = self.GcsApi().objects() # ... | [
"def GetObjectMetadata(self,\n bucket_name,\n object_name,\n generation=None,\n provider=None,\n fields_scope=None):\n raise NotImplementedError('GetObjectMetadata must be overloaded')",
"def blob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ACLs for a Google Cloud Storage bucket. This includes both ACL entries and IAM policies. | def GetBucketACLs(self,
bucket: str,
user_project: Optional[str] = None) -> Dict[str, List[str]]:
ret = collections.defaultdict(list)
if bucket.startswith('gs://'):
# Can change to removeprefix() in 3.9
bucket = bucket[5:]
gcs_bac = self.GcsApi().bucketAcc... | [
"def get_bucket_acl(client, bucket_name):\n req = client.bucketAccessControls().list(\n bucket=bucket_name,\n )\n resp = req.execute()\n return resp",
"def get_bucket_defacl(client, bucket_name):\n req = client.defaultObjectAccessControls().list(\n bucket=bucket_name,\n )\n resp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List buckets in a Google Cloud project. | def ListBuckets(self) -> List[Dict[str, Any]]:
gcs_buckets = self.GcsApi().buckets() # pylint: disable=no-member
request = gcs_buckets.list(project=self.project_id)
objects = request.execute() # type: Dict[str, Any]
return objects.get('items', []) | [
"def list():\n return [b.name for b in s3.buckets.all()]",
"def getBuckets(cos):\r\n\r\n res = []\r\n print(\"* Retrieving list of buckets\")\r\n\r\n try:\r\n buckets = cos.list_buckets()\r\n \r\n for b in buckets['Buckets']:\r\n res.append(b['Name'])\r\n\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List objects (with metadata) in a Google Cloud Storage bucket. | def ListBucketObjects(self, bucket: str) -> List[Dict[str, Any]]:
if bucket.startswith('gs://'):
# Can change to removeprefix() in 3.9
bucket = bucket[5:]
gcs_objects = self.GcsApi().objects() # pylint: disable=no-member
request = gcs_objects.list(bucket=bucket)
objects = request.execute() ... | [
"def bucket_listing(bucket):\n response = s3.list_objects(Bucket=bucket)\n\n file_listing = []\n for file_data in response[\"Contents\"]:\n data = {\"filename\": file_data[\"Key\"], \"size\": file_data[\"Size\"]}\n file_listing.append(data)\n\n print(\"File listing: {}\".format(file_listin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes an object in a Google Cloud Storage bucket. | def DeleteObject(self, gcs_path: str) -> None:
if not gcs_path.startswith('gs://'):
gcs_path = 'gs://' + gcs_path
bucket, object_path = SplitStoragePath(gcs_path)
gcs_objects = self.GcsApi().objects() # pylint: disable=no-member
request = gcs_objects.delete(bucket=bucket, object=object_path)
... | [
"def bucket_delete():\r\n if not confirm(\"Are you sure you want to delete the bucket %r?\" % BUCKET_NAME):\r\n abort('Aborting at user request.')\r\n conn = connect_s3()\r\n conn.delete_bucket(BUCKET_NAME)\r\n print 'Bucket %r deleted.' % BUCKET_NAME",
"def delete_object(bucket, key):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches information for a provided station name from SomaFM | def somafm_info(bot, trigger):
user_input = trigger.group(2)
if not user_input:
return bot.reply("I need a station to lookup!")
stations = _fetch(bot, API_CHANNELS_URL)
user_input = user_input.strip().lower()
station = []
for channel in stations['channels']:
if "*" in user_input:... | [
"def station_by_name(self, name):\n\n try:\n station = [_ for _ in self.stations[\"features\"] if name == _[\"properties\"][\"name\"]]\n log.debug(\"searching for station {} found {}\".format(name, station))\n return station[0]\n except:\n log.debug(\"Except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes all params from api and extends cls with it. api class can be removed afterwards | def extend(cls, api):
if cls.EXTEND:
for name, func in api.__dict__.iteritems():
if name.startswith("_"): continue
setattr(cls, name, MethodType(func, None, cls))
return cls.EXTEND | [
"def __init__(self):\n ApiHandler.__init__(self)",
"def __call__(self, cls):\n self.check(cls)\n if not hasattr(cls, '_fused_base'):\n cls._fused_base = []\n cls._fused_base.append(self._base)\n return base(implementer(interface(self._base))(cls))",
"def dynamic_cla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if the user is authorized for specific method | def isAuthorized(self, func, user):
if user.isAdmin():
return True
elif func in perm_map and user.hasPermission(perm_map[func]):
return True
else:
return False | [
"def check_authorization(self):\n pass",
"def authorize(self):\n return True",
"def authorize(self, resource, **kwargs):\n method = request.method.lower()\n\n if hasattr(self, method):\n func = getattr(self, method)\n else:\n func = self.default\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performa click at the coordinates of top_left to the website opened by the driver | def clickScreen(driver, top_left):
try:
#myElem = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CLASS_NAME, 'game')))
game_element = driver.find_element_by_class_name("game")
myElem = game_element
action = webdriver.common.action_chains.ActionChains(driver)
... | [
"def click_here(png_image, window_region):\n loc = pyautogui.locateOnScreen(\n png_image, grayscale=True, region=(window_region))\n if loc:\n loc_cent = pyautogui.center(loc)\n pyautogui.click(loc_cent)\n else:\n pyautogui.alert(text=\"Could not locate action to perform.\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Binary Image which is thresholded by thr rbg pixel vales given in rbg_threshold i.e. If pixel is > thres assign 1 and if pixel is < thres assing 0 | def colorThreshold(img, rbg_threshold = (60,60,60)):
temp = np.zeros(img.shape)
rflags_h = img[:,:]>rbg_threshold[0]
temp[:,:][rflags_h] = 1
return temp | [
"def brightness_binary(self) -> np.ndarray:\n thresholds = self.thresholds\n lab = cv2.cvtColor(self.image, cv2.COLOR_BGR2Lab)\n b_channel = lab[:, :, 2]\n b_binary = np.zeros_like(b_channel)\n b_binary[\n (b_channel >= thresholds.brightness[0]) &\n (b_channe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs the optimal clicks for the given amt | def setAmountV2(driver, amt, amount_dict, board_coord):
key_lst =optimizeAmtClick(amt);
for k in key_lst:
clickScreen(driver,amount_dict['amt_region'])
clickScreen(driver,amount_dict[k])
clickScreen(driver,board_coord) | [
"def approachTarget(self, amount):\n if amount == 0:\n # If amount is zero, do nothing.\n return\n \n if self.t.sub(self.p).mag()*(1 - amount) > 2.0*self.tolerance:\n # If 'self.approachTarget()' will not take the view within twice the\n # tolerance d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dictionary of Courdinates of different board locations | def getAllBoardCoord(driver):
board_list = ['hi', 'mid', 'lo']
board_dict = {}
for b in board_list:
tmp = getTemplate(b)
game_image = getGameImage(driver, 'layer2')
board_coord = detectTemplate(game_image, tmp, False, -1)
board_dict[b] = board_coord
return board_dict | [
"def ps_moves_per_loc():\n _dict = {}\n for i in range(8):\n for j in range(8):\n _dict[str((i, j))] = {}\n set_2nd_layer_keys_moves(_dict)\n return _dict",
"def world_cups():\n return [(\"Germany\", 2006, \"Italy\"), (\"South-Africa\", 2010, \"Spain\"), (\"Brazil\", 2014, \"Germa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a random datetime between `start` and `end` | def random_date(start, end):
random_time = start + timedelta(
seconds=randint(0, int((end - start).total_seconds())),
)
hour = numpy.random.choice(hours, p=probabilities)
return random_time.replace(hour=hour) | [
"def random_datetime(start=START_DATE, end=END_DATE):\n delta = end - start\n int_delta = (delta.days * 24 * 60 * 60) + delta.seconds\n random_second = random.randrange(int_delta)\n return start + timedelta(seconds=random_second)",
"def random_datetimes(start, end, ntimes):\n delta = end - start\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an image of the frequency spectrum of the system as a function of ng. | def frequency_spectrum(self, ngs, freqs, initial_states=[0],
kappa=0.1, branch='none'):
spectrum = np.zeros((len(ngs), len(freqs)))
for (n, ng) in enumerate(ngs):
self.ng = ng
evals, evecs = self.energies(branch, return_evecs=True)
g = self.... | [
"def spectrum(self):\n c_ratio = self._count_rates['flux_ratio']\n return c_ratio + np.random.randn(len(c_ratio)) * self.sigma",
"def get_freqs(Fs, n):\n\n return np.linspace(0, Fs / 2, int(n / 2 + 1))",
"def output_frequency(y):\n global _prev_frequency\n y = np.copy(interpolate(y, setti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. | def post_comment(request, next=None, using=None):
# Fill out some initial data fields from an authenticated user, if present
data = request.POST.copy()
if request.user.is_authenticated:
if not data.get('name', ''):
data["name"] = request.user.get_full_name() or request.user.get_username(... | [
"def post_comment():\n\n path = request.args.get('path', '')\n comment_id = request.args.get('comment_id')\n data = request.get_json()\n\n post = (db_session.query(Post)\n .filter(Post.path == path)\n .first())\n\n if not post:\n raise Exception('Unabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
data = f_read_raw_mat(filename, col, data_format='float', end='l') Read the binary data from filename Return data, which is a (N, col) array input | def f_read_raw_mat(filename, col, data_format='f4', end='l'):
f = open(filename,'rb')
if end=='l':
data_format = '<'+data_format
elif end=='b':
data_format = '>'+data_format
else:
data_format = '='+data_format
datatype = np.dtype((data_format,(col,)))
data = np.fromfile(f... | [
"def _read_binary_matrix(filename):\n with tf.gfile.GFile(filename, \"rb\") as f:\n s = f.read()\n magic = int(np.frombuffer(s, \"int32\", 1))\n ndim = int(np.frombuffer(s, \"int32\", 1, 4))\n eff_dim = max(3, ndim)\n raw_dims = np.frombuffer(s, \"int32\", eff_dim, 8)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
len = f_read_raw_mat_length(filename, data_format='f4') Read length of data, i.e., number of elements in the data file. If data is in shape (N, M), then len = N M input | def f_read_raw_mat_length(filename, data_format='f4'):
f = open(filename,'rb')
tmp = f.seek(0, 2)
bytes_num = f.tell()
f.close()
if data_format == 'f4':
return int(bytes_num / 4)
else:
return bytes_num | [
"def f_read_htk_length(filename, data_format='f4', end='l'):\n if end=='l':\n data_format = '<'+data_format\n data_formatInt4 = '<i4'\n data_formatInt2 = '<i2'\n elif end=='b':\n data_format = '>'+data_format\n data_formatInt4 = '>i4'\n data_formatInt2 = '>i2'\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
data = read_htk(filename, data_format='f4', end='l') Read HTK File and return the data as numpy.array input | def f_read_htk(filename, data_format='f4', end='l'):
if end=='l':
data_format = '<'+data_format
data_formatInt4 = '<i4'
data_formatInt2 = '<i2'
elif end=='b':
data_format = '>'+data_format
data_formatInt4 = '>i4'
data_formatInt2 = '>i2'
else:
data_form... | [
"def f_read_htk_length(filename, data_format='f4', end='l'):\n if end=='l':\n data_format = '<'+data_format\n data_formatInt4 = '<i4'\n data_formatInt2 = '<i2'\n elif end=='b':\n data_format = '>'+data_format\n data_formatInt4 = '>i4'\n data_formatInt2 = '>i2'\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
length = read_htk(filename, data_format='f4', end='l') Read HTK File and return the number of data elements in the file Read HTK File and return the data as numpy.array input | def f_read_htk_length(filename, data_format='f4', end='l'):
if end=='l':
data_format = '<'+data_format
data_formatInt4 = '<i4'
data_formatInt2 = '<i2'
elif end=='b':
data_format = '>'+data_format
data_formatInt4 = '>i4'
data_formatInt2 = '>i2'
else:
da... | [
"def f_read_htk(filename, data_format='f4', end='l'):\n if end=='l':\n data_format = '<'+data_format\n data_formatInt4 = '<i4'\n data_formatInt2 = '<i2'\n elif end=='b':\n data_format = '>'+data_format\n data_formatInt4 = '>i4'\n data_formatInt2 = '>i2'\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
flag = write_raw_mat(data, filename, data_format='f4', end='l') Write data to file on the file system as binary data input | def f_write_raw_mat(data, filename, data_format='f4', end='l'):
if not isinstance(data, np.ndarray):
print("Error write_raw_mat: input should be np.array")
return False
f = open(filename,'wb')
if len(data_format)>0:
if end=='l':
data_format = '<'+data_format
elif ... | [
"def f_append_raw_mat(data, filename, data_format='f4', end='l'):\n if not isinstance(data, np.ndarray):\n print(\"Error write_raw_mat: input shoul be np.array\")\n return False\n f = open(filename,'ab')\n if len(data_format)>0:\n if end=='l':\n data_format = '<'+data_format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
flag = write_raw_mat(data, filename, data_format='f4', end='l') Append data to an existing file on the file system as binary data input | def f_append_raw_mat(data, filename, data_format='f4', end='l'):
if not isinstance(data, np.ndarray):
print("Error write_raw_mat: input shoul be np.array")
return False
f = open(filename,'ab')
if len(data_format)>0:
if end=='l':
data_format = '<'+data_format
elif ... | [
"def f_write_raw_mat(data, filename, data_format='f4', end='l'):\n if not isinstance(data, np.ndarray):\n print(\"Error write_raw_mat: input should be np.array\")\n return False\n f = open(filename,'wb')\n if len(data_format)>0:\n if end=='l':\n data_format = '<'+data_format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
write_htk(data,targetfile, sampPeriod=50000,sampKind=9,data_format='f4',end='l') Write data as HTKcompatible format input | def f_write_htk(data, targetfile,
sampPeriod=50000, sampKind=9, data_format='f4', end='l'):
if data.ndim==1:
nSamples, vDim = data.shape[0], 1
else:
nSamples, vDim = data.shape
if data_format=='f4':
sampSize = vDim * 4;
else:
sampSize = vDim * 8;
... | [
"def f_read_htk(filename, data_format='f4', end='l'):\n if end=='l':\n data_format = '<'+data_format\n data_formatInt4 = '<i4'\n data_formatInt2 = '<i2'\n elif end=='b':\n data_format = '>'+data_format\n data_formatInt4 = '>i4'\n data_formatInt2 = '>i2'\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dic = read_dic(file_path) Read a json file from file_path and return a dictionary input | def read_dic(file_path):
try:
data = json.load( open(file_path) )
except IOError:
print("Cannot find %s" % (file_path))
sys.exit(1)
except json.decoder.JSONDecodeError:
print("Cannot parse %s" % (file_path))
sys.exit(1)
return data | [
"def get_json_dict(filepath):\n with open(filepath, encoding=\"utf8\") as infile:\n return json.load(infile)",
"def read_json_file(file_path: str) -> Dict:\n with open(file_path, 'r') as file:\n data = file.read()\n return json.loads(data)",
"def get_json_dict(json_file_name: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
write_dic(dic, file_path) Write a dictionary to file input | def write_dic(dic, file_path):
try:
json.dump(dic, open(file_path, 'w'))
except IOError:
print("Cannot write to %s " % (file_path))
sys.exit(1) | [
"def save_dictionary(worddict, wordcount, loc):\n with open(loc, 'w') as f:\n pkl.dump(worddict, f)\n pkl.dump(wordcount, f)",
"def WriteDict( d, filename, *fields ):\r\n\tif len( fields ): d = dict( ( k, v ) for k, v in d.items() if k in fields )\r\n\tfile = open( MakeWayFor( filename ), 'wt' )\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
data = pickle_load(file_path) Load data from a pickle dump file | def pickle_load(file_path):
with open(file_path, 'rb') as file_ptr:
data = pickle.load(file_ptr)
return data | [
"def load_pickle_file(file_name):\n data_values = None # Define here to establish scope\n log.info(\"LOAD PICKLE: Open the pickle file\")\n with open(file_name, 'rb') as pickle_file:\n data_values = pickle.load(pickle_file)\n\n log.info(\"LOAD PICKLE: Print the loaded pickle ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raise EC2ResponseError the first n times that the method is called. | def _fail_for_n_calls(self, n, status=400):
self.num_calls += 1
if self.num_calls <= n:
e = EC2ResponseError(status, None)
e.error_code = 'InvalidInstanceID.NotFound'
raise e | [
"def test_five_failures(self):\n function = aws_service.retry_boto(\n self._fail_for_n_calls,\n r'InvalidInstanceID\\.NotFound',\n initial_sleep_seconds=0.0\n )\n function(5)",
"def test_503(self):\n function = aws_service.retry_boto(\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we handle failing 5 times and succeeding the 6th time. | def test_five_failures(self):
function = aws_service.retry_boto(
self._fail_for_n_calls,
r'InvalidInstanceID\.NotFound',
initial_sleep_seconds=0.0
)
function(5) | [
"def test(self, failure_rate, iteration_n):\n pass",
"def test_runUntilFailure(self):\n stream = StringIO()\n case = erroneous.EventuallyFailingTestCase(\"test_it\")\n runner = self.getRunner(stream=stream)\n d = runner.runAsync(case, untilFailure=True)\n result = self.su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we retry when AWS returns a 503 status. | def test_503(self):
function = aws_service.retry_boto(
self._fail_for_n_calls, initial_sleep_seconds=0.0)
function(5, status=503) | [
"def test_retry_request_behavior(mocker):\n failed_query = make_mock_failing_query(503)\n mocker.patch.object(LHorizon, \"query\", failed_query)\n futile_lhorizon = [LHorizon()]\n start = time.time()\n try:\n query_all_lhorizons(futile_lhorizon, delay_retry=0.1, max_retries=2)\n except Time... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we retry on ssl.SSLError. This is a case that was seen in the field. | def test_ssl_error(self):
def raise_ssl_error():
self.num_calls += 1
if self.num_calls <= 5:
raise ssl.SSLError('Test')
aws_service.retry_boto(raise_ssl_error, initial_sleep_seconds=0.0)() | [
"def test_http_ssl_error(mock_base_http_request, client):\n # Configure\n mock_base_http_request.side_effect = DemistoException('SSLError')\n # Execute\n with pytest.raises(SSLError) as e:\n client.http_request('GET', MOCK_TEST_URL_SUFFIX)\n\n # Assert\n assert (\n str(e.value)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test waiting for an instance to terminate. | def test_wait_for_instance_terminated(self):
aws_svc, encryptor_image, guest_image = build_aws_service()
instance = aws_svc.run_instance(guest_image.id)
aws_svc.terminate_instance(instance.id)
result = encrypt_ami.wait_for_instance(
aws_svc, instance.id, state='terminated', t... | [
"def test_wait_for_instance_unexpectedly_terminated(self):\n aws_svc, encryptor_image, guest_image = build_aws_service()\n instance = aws_svc.run_instance(guest_image.id)\n aws_svc.terminate_instance(instance.id)\n try:\n encrypt_ami.wait_for_instance(\n aws_svc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we raise an exception when an instance goes into an error state while we're waiting for it. | def test_instance_error_state(self):
aws_svc, encryptor_image, guest_image = build_aws_service()
instance = aws_svc.run_instance(guest_image.id)
instance._state.name = 'error'
try:
encrypt_ami.wait_for_instance(aws_svc, instance.id, timeout=100)
except encrypt_ami.Ins... | [
"def testImmediateException(self):\n def _OnException(type, value, tb):\n self.stop()\n\n with util.ExceptionBarrier(_OnException):\n raise Exception('an error')\n self.wait()",
"def test_block_on_lease_error(self, fake_sleep):\n fake_lease = MagicMock()\n fake_lease.state = virtu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we handle the edge case when an instance is terminated on startup. | def test_wait_for_instance_unexpectedly_terminated(self):
aws_svc, encryptor_image, guest_image = build_aws_service()
instance = aws_svc.run_instance(guest_image.id)
aws_svc.terminate_instance(instance.id)
try:
encrypt_ami.wait_for_instance(
aws_svc, instance.... | [
"def test_wait_for_instance_terminated(self):\n aws_svc, encryptor_image, guest_image = build_aws_service()\n instance = aws_svc.run_instance(guest_image.id)\n aws_svc.terminate_instance(instance.id)\n result = encrypt_ami.wait_for_instance(\n aws_svc, instance.id, state='term... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns filename for tile with given coordinates | def tilefilename(
self,
x,
y,
z,
):
tileIndex = x + y * self.tierSizeInTiles[z][0] \
+ self.tileCountUpToTier[z]
return os.path.join('TileGroup%.0f' % math.floor(tileIndex
/ 256), '%s-%s-%s.%s' % (z, x, y,
... | [
"def get_tile_x_path(tile_dir: str, tile: str) -> str:\n return os.path.join(tile_dir, tile + TILE_X_EXT)",
"def get_tile_name_xy(x: int, y: int) -> str:\n return \"srtm_{0:02d}_{1:02d}\".format(x, y)",
"def get_tile_name(self, latitude: float, longitude: float) -> str:\n x, y = self.get_tile_x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing). | def generate_metadata(self):
if not os.path.exists(self.output):
os.makedirs(self.output)
if self.options.profile == 'mercator':
(south, west) = self.mercator.MetersToLatLon(self.ominx,
self.ominy)
(north, east) = self.mercator.MetersToLatLon(se... | [
"def mbtiles_metadata(self):\n self.metadata = dict(self.mbtiles.execute('select name, value from metadata;').fetchall())\n (metadata, mime_type) = self.jsonp(self.metadata)\n self.send_file(self.tileset + '.json', metadata, mime_type)\n self.send_file(self.tileset + '/metadata.json', metadata, mime_typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generation of the base tiles (the lowest in the pyramid) directly from the input raster | def generate_base_tiles(self):
print 'Generating Base Tiles:'
if self.options.verbose:
# mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY
# px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz)
# print "Pixel coordinates:", px, py, (mx, my)
... | [
"def divideIntoTiles(inputRaster,dim):\r\n tiles=[]\r\n xmin=0\r\n xmax=dim\r\n ymin=0\r\n ymax=dim\r\n #iterate down the Y values\r\n for i in range(0,inputRaster.shape[0]//dim):\r\n #iterate across the X values\r\n for j in range(0,inputRaster.shape[1]//dim):\r\n coor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generation of the overview tiles (higher in the pyramid) based on existing tiles | def generate_overview_tiles(self):
print 'Generating Overview Tiles:'
tilebands = self.dataBandsCount + 1
# Usage of existing tiles: from 4 underlying tiles generate one as overview.
tcount = 0
for tz in range(self.tmaxz - 1, self.tminz - 1, -1):
(tminx, tminy, tm... | [
"def _render_tiles(self, tiles, wslice, hslice):\n\n for row in tiles:\n for atile in row:\n basex = wslice*atile.x\n basey = hslice*atile.y\n if atile.visited is True:\n self.gamemap.create_rectangle(basex, basey, basex+wslice, basey... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the extent is returned in the native resolution of dataset ds. | def geo_query(
self,
ds,
ulx,
uly,
lrx,
lry,
querysize=0,
):
geotran = ds.GetGeoTransform()
rx = int((ulx - geotran[0]) / geotran[1] + 0.001)
ry = int((uly - geotran[3]) / geotran[5] + 0.001)
rxsize = int((lrx - ulx) / geot... | [
"def _get_extent(inp):\n d = inp.dimensions\n return [0, d[0]-1, 0, d[1]-1, 0, d[2]-1]",
"def read_gdal_coordinates(dataset, mode='centers', z=True):\n coordinates_pixel = pixel_coordinates(dataset.RasterXSize,\n dataset.RasterYSize, mode)\n geotransform = data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scales down query dataset to the tile dataset | def scale_query_to_tile(
self,
dsquery,
dstile,
tilefilename='',
):
querysize = dsquery.RasterXSize
tilesize = dstile.RasterXSize
tilebands = dstile.RasterCount
if self.options.resampling == 'average':
# Function: gdal.RegenerateOver... | [
"def _rescale(self, scale_factor: int) -> xr.DataArray:\n nlat_new = self.nlat / scale_factor\n nlon_new = self.nlon / scale_factor\n assert nlat_new % 1.0 == 0.0, 'The dataset\\'s dimension \\'lat\\' has size {}, '\\\n 'must be fully dividable by the argument \\'scale_factor\\' ({})... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. | def generate_googlemaps(self):
args = {}
args['title'] = self.options.title
args['googlemapskey'] = self.options.googlekey
(args['south'], args['west'], args['north'], args['east']) = \
self.swne
args['minzoom'] = self.tminz
args['maxzoom'] = self.tmaxz
... | [
"def generate_openlayers(self):\n\n args = {}\n args['title'] = self.options.title\n args['bingkey'] = self.options.bingkey\n (args['south'], args['west'], args['north'], args['east']) = \\\n self.swne\n args['minzoom'] = self.tminz\n args['maxzoom'] = self.tmaxz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Template for openlayers.html implementing overlay of available Spherical Mercator layers. | def generate_openlayers(self):
args = {}
args['title'] = self.options.title
args['bingkey'] = self.options.bingkey
(args['south'], args['west'], args['north'], args['east']) = \
self.swne
args['minzoom'] = self.tminz
args['maxzoom'] = self.tmaxz
args[... | [
"def map_service_catalogue():\n if deployment_settings.get_security_map() and not shn_has_role(\"MapAdmin\"):\n unauthorised()\n\n subtitle = T(\"List Layers\")\n # Start building the Return with the common items\n output = dict(subtitle=subtitle)\n\n # Hack: We control all perms from this 1 t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up an import project for a study and imports it. | def setup_import_project(
root_path: pathlib.Path, study: StudyInputLayout,
gpf_instance: GPFInstance,
project_config_update: Optional[dict[str, Any]] = None,
project_config_overwrite: Optional[dict[str, Any]] = None
) -> ImportProject:
project_config = setup_import_project_config(
root_path... | [
"def import_project(self,project_dir):\n # Check that target directory exists\n project_dir = os.path.abspath(project_dir)\n # Check that project doesn't already exist\n project_name = os.path.basename(project_dir)\n project_metadata = self.load_project_metadata()\n if proj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import a VCF study and return the import project. | def vcf_import(
root_path: pathlib.Path,
study_id: str,
ped_path: pathlib.Path, vcf_paths: list[pathlib.Path],
gpf_instance: GPFInstance,
project_config_update: Optional[dict[str, Any]] = None,
project_config_overwrite: Optional[dict[str, Any]] = None
) -> ImportProject:
study = StudyInputLa... | [
"def cnv_import(\n root_path: pathlib.Path,\n study_id: str,\n ped_path: pathlib.Path, cnv_paths: list[pathlib.Path],\n gpf_instance: GPFInstance,\n project_config_update: Optional[dict[str, Any]] = None,\n project_config_overwrite: Optional[dict[str, Any]] = None\n) -> ImportProject:\n study =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import a de Novo study and return the import project. | def denovo_import(
root_path: pathlib.Path,
study_id: str,
ped_path: pathlib.Path, denovo_paths: list[pathlib.Path],
gpf_instance: GPFInstance,
project_config_update: Optional[dict[str, Any]] = None,
project_config_overwrite: Optional[dict[str, Any]] = None
) -> ImportProject:
study = StudyI... | [
"def cnv_import(\n root_path: pathlib.Path,\n study_id: str,\n ped_path: pathlib.Path, cnv_paths: list[pathlib.Path],\n gpf_instance: GPFInstance,\n project_config_update: Optional[dict[str, Any]] = None,\n project_config_overwrite: Optional[dict[str, Any]] = None\n) -> ImportProject:\n study =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import a de Novo study and return the import project. | def cnv_import(
root_path: pathlib.Path,
study_id: str,
ped_path: pathlib.Path, cnv_paths: list[pathlib.Path],
gpf_instance: GPFInstance,
project_config_update: Optional[dict[str, Any]] = None,
project_config_overwrite: Optional[dict[str, Any]] = None
) -> ImportProject:
study = StudyInputLa... | [
"def denovo_import(\n root_path: pathlib.Path,\n study_id: str,\n ped_path: pathlib.Path, denovo_paths: list[pathlib.Path],\n gpf_instance: GPFInstance,\n project_config_update: Optional[dict[str, Any]] = None,\n project_config_overwrite: Optional[dict[str, Any]] = None\n) -> ImportProject:\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and register a dataset dataset_id with studies. | def setup_dataset(
dataset_id: str,
gpf_instance: GPFInstance,
*studies: GenotypeData,
dataset_config_udate: str = "") -> GenotypeData:
# pylint: disable=import-outside-toplevel
from box import Box
from dae.studies.study import GenotypeDataGroup
dataset_config = {
... | [
"def _create_dataset(self, dataset_id: str) -> None:\n\n self.assert_gcp_dependencies()\n dataset = bigquery.Dataset(f\"{self.project_id}.{dataset_id}\")\n dataset.location = self.data_location\n self.bigquery_client.create_dataset(dataset, exists_ok=True)\n logging.info(f\"Create... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert base32 encoded secret string to bytes | def secret_to_bytes(secret):
return base64.b32decode(secret) | [
"def secret_data_encode_bytes(data: bytes) -> bytes:\n return base64.b64encode(data)",
"def encode_to_b16(inp: str) -> bytes:\n encoded = inp.encode(\"utf-8\") # encoded the input (we need a bytes like object)\n b16encoded = base64.b16encode(encoded) # b16encoded the encoded string\n return b16encod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list l2 and a list of indices l1, yield all tuples (x, y) s.t. x is an index in l1 and y is l2[x]. | def special_product(l1, l2):
for i in l1:
for j in range(0, len(l2[i])):
yield (i, j) | [
"def indexpositions(list1,int1):\n list2=[]\n for i in range(len(list1)):\n if int1==list1[i]:\n list2.append(i)\n return list2",
"def cartesian( v1, v2 ):\n return tuple([(x,y) for x in v1 for y in v2])",
"def _get_pair_list(queries, docs, labels, _make_indexed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the x position of the p'th word as if given an infinite environment. | def env_pos_x_virtual(self, p):
return self.TEXT_MARGIN[0] + self.TEXT_SPACING[0] * p | [
"def xcoord(pt):\n return pt.x",
"def get_pos_x(self):\n return self._position[0]",
"def current_x(self):\n return self._current_position[0]",
"def get_x(self):\r\n return self.get_3d_position()[\"position\"].x",
"def get_x(self):\n\n return math.floor(self.position.x)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the ordered list of amino acid. This convention is based on the BLOSUM matrix in biopython and assumed for the binned distribution presenting amino acid contribution to differential selection at a site | def _get_aa_ordered_list():
return list("ARNDCQEGHILKMFPSTWYV") | [
"def iterAACombs(n,alfabet): \n AAs = alfabet\n AAcombsList = []\n for i in xrange(2,n+1):\n for combs in itertools.combinations_with_replacement(AAs,i): #itertools.product(AAs, repeat=i): \n yield ''.join(sorted(combs))",
"def aids(self):\n return self._aid_name_to_value.valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the default 40x40 cost matrix based on BLOSUM62 and assigns maximum cost to transport between opposite signed differential selection contributions. Returns | def get_cost_matrix():
substitution_matrix = substitution_matrices.load("BLOSUM62")
alphabet_list = _get_aa_ordered_list()
Naa = len(alphabet_list)
# chosen so that range of costs in the
# matrix is within an order of magnitude
nthroot = 7.0
# maximum cost assigned by the cost matrix
... | [
"def compute_B_matrix(s_data, t_data, s_branches, t_branches):\n\n\tdef compute_branch_mapping_cost(s_branch, t_branch, s_data, t_data):\n\t\t\"\"\" Gets the cost of mapping branch s to branch t. (i.e. Q(s_b, t_b))\n\t\t\tActually no -> It \"knows\" that a branch must be mapped to a certain other branch, i.e. the f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the list of weights for computing the weighted sum of similarity scores in region [loc_start, loc_end] | def _get_weights(ds, metric, sample_factor, sfact_val1, sfact_val2, loc_start, loc_end):
# Code assumes peptide annotation for location is called 'Loc'
loc_sums1 = []
loc_sums2 = []
for loc in range(loc_start, loc_end + 1):
ds1 = ds.loc[
dict(
peptide_id=id_query(ds... | [
"def compute_weights(self) -> list:\n weights = []\n for num in self.population:\n # Our purpose: find x with fitness value near 0 as much as possible\n # So if abs(x) is large, negative of it (weight) will be small\n weights.append(0 - abs(self.equation(num+self.offse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the similarity score given two distributions and the cost matrix. | def compute_sim_score(a, b, cost_matrix):
if np.sum(a) == 0 or np.sum(b) == 0:
return 0
cost = ot.emd2(a, b, cost_matrix)
return 1.0 / cost | [
"def similarity(topic_vector_a: TopicVector, topic_vector_b: TopicVector) -> float:\n return matutils.cossim(topic_vector_a, topic_vector_b)",
"def _compute_similarities(preds: List[Tuple[torch.FloatTensor, torch.FloatTensor]]) -> torch.FloatTensor:\n return -AlignmentMetric._compute_cost(preds)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the similarity score for comparison in the region [loc_start, loc_end]. | def region_sim_score(
ds, metric, cost_matrix, sample_factor, sfact_val1, sfact_val2, loc_start, loc_end
):
weights = _get_weights(
ds, metric, sample_factor, sfact_val1, sfact_val2, loc_start, loc_end
)
region_sim = 0
for loc in range(loc_start, loc_end + 1):
sim = weights[loc] * l... | [
"def _compute_region_score(self,\n saliency_map: torch.Tensor,\n region: Tuple[int, int, int, int],\n global_mean: float = 0) -> float:\n raw_score = self._select_region(saliency_map, region).sum().item()\n return r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If for any reason the parsing process returns an error, make sure that all data from a socket is removed to avoid data pollution with further parsing attempts. | def clearSocketData(self):
if not isinstance(self.fp, socket.socket):
# not a socket. Nothing to do here.
return
# Switch socket into non-blocking mode and read from it until it
# is empty (and hence socket.error is raised):
self.fp.setblocking(False)
try:... | [
"def _collectSocketDetails(self):\n del self.socket, self.fileno",
"def worker():\r\n unprocessed=bytes()\r\n while True:\r\n try:\r\n chunk = self.socket.recv(2048)\r\n if len(chunk)==0: \r\n break\r\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A boolean array consists of a 4byte word (i.e. integer) determining the number of boolean values in the following dataLength4 bytes. | def xt_array_bool(self, lexeme):
numBools = self.__unpack(XT_INT, 1)[0]
# read the actual boolean values, including padding bytes:
raw = self.read(lexeme.dataLength - 4)
# Check if the array contains any NA values (encoded as \x02).
# If so we need to convert the 2's to None's an... | [
"def _rand_bool_array(length):\n return [NTSimulation._rand_bool() for _ in range(length)]",
"def to_bool_list(bytes_array):\n ba = []\n index = 1\n for byte in bytes_array:\n for bit in range(7):\n if byte & 1 << bit:\n ba.append(index)\n index += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An array of one or more nullterminated strings. The XT_ARRAY_STR can contain trailing chars \x01 which need to be chopped off. Since strings are encoded as bytes (in Py3) they need to be converted into real strings. | def xt_array_str(self, lexeme):
if lexeme.dataLength == 0:
return ''
raw = self.read(lexeme.dataLength)
bytesStrList = raw.split(b'\0')[:-1]
strList = [stringEncode(byteString) for byteString in bytesStrList]
return numpy.array(strList) | [
"def s_xt_array_str(self, o):\n startPos = self._buffer.tell()\n rTypeCode = self.__s_write_xt_array_tag_data(o)\n\n # reshape into 1d array:\n o1d = o.reshape(o.size, order='F')\n # Byte-encode them:\n bo = [byteEncode(d) for d in o1d]\n # add empty string to that t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the identifier of the recipe. For recipes, the name is the identifier. | def id(self):
return self.recipe_name | [
"def identifier(self) -> str:\n if not self._identifier:\n self.load()\n return self._identifier",
"def _get_id(self) -> \"std::string\" :\n return _core.Material__get_id(self)",
"def get_recipe_by_name(self, name):\n pass",
"def get_id(self) -> str:\r\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the name of the recipe. | def name(self):
return self.recipe_name | [
"def id(self):\n return self.recipe_name",
"def bioc_name(recipe):\n return MetaData(recipe).meta['source']['fn'].split('_')[0]",
"def get_name(self):\n return self.__name_army",
"def _get_name(self):\n return self._trend['name']",
"def get_recipe_by_name(self, name):\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the definition of the recipe. | def set_definition_and_payload(self, definition):
warnings.warn("Recipe.set_definition_and_payload is deprecated, please use get_settings", DeprecationWarning)
definition._payload_to_str()
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.project_key, sel... | [
"async def pboss_edit(self, ctx, term, *, definition):\n await self._pboss_add(ctx, term, definition, False)",
"def _configure_using_fluent_definition(self):\r\n definition = Parser.parse(self.signature)\r\n\r\n self._config.set_name(definition[\"name\"])\r\n\r\n for name, flags, descr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the status of this recipe. The status of a recipe is made of messages from checks performed by DSS on the recipe, of messages related to engines availability for the recipe, of messages about testing the recipe on the engine, ... | def get_status(self):
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s/status" % (self.project_key, self.recipe_name))
return DSSRecipeStatus(self.client, data) | [
"def get_status (self):\n return self.__status",
"def get_status(self):\n return self.client.get_asg_ready(self.env, self.name)",
"def get_status(self):\n return StatusAPI.from_client(self)",
"def GetStatus(self):\n self.__SendMsg(\"status\")\n ##TODO: Parse the response into ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the metadata attached to this recipe. The metadata contains label, description checklists, tags and custom metadata of the recipe | def get_metadata(self):
return self.client._perform_json(
"GET", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name)) | [
"def get_metadata(self):\n return meta.get_metadata(self.ast)",
"def parse_metadata(self, recipe=None):\n if recipe:\n self.prepare_taskdata([recipe])\n filename = self.provide_to_fn(recipe)\n return self.parse_recipe_file(filename)\n else:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the metadata on this recipe. | def set_metadata(self, metadata):
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name),
body=metadata) | [
"def set_metadata(self, jobid, metadata):",
"def set_metadata(self, metadata, clear=False):\n self.client.set_object_metadata(self.container, self, metadata, clear=clear)",
"def set_metadata(self, metadata: MetaData) -> None:\n self._parent.set_metadata(metadata)\n self._child.set_metadata(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a handle to manage discussions on the recipe. | def get_object_discussions(self):
return DSSObjectDiscussions(self.client, self.project_key, "RECIPE", self.recipe_name) | [
"def discussion(self, disscussion_id, text_format=None):\n endpoint = 'discussions/{}'.format(disscussion_id)\n params = {'text_format': text_format or self.response_format}\n return self._make_request(path=endpoint, params_=params, public_api=True)",
"def create_divided_discussions(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move this object to a flow zone. | def move_to_zone(self, zone):
if isinstance(zone, basestring):
zone = self.client.get_project(self.project_key).get_flow().get_zone(zone)
zone.add_item(self) | [
"def move_to(self, mobject_or_point):\n layer_center = self.feature_maps.get_center()\n if isinstance(mobject_or_point, Mobject):\n target_center = mobject_or_point.get_center() \n else:\n target_center = mobject_or_point\n\n self.shift(target_center - layer_center)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the selected engine for this recipe. This method will raise if there is no selected engine, whether it's because the present recipe type has no notion of engine, or because DSS couldn't find any viable engine for running the recipe. | def get_selected_engine_details(self):
if not "selectedEngine" in self.data:
raise ValueError("This recipe doesn't have a selected engine")
return self.data["selectedEngine"] | [
"def engine(self) -> \"DatabaseInstanceEngine\":\n return self._values.get('engine')",
"def _get_engine(self, context=None):\n context = context or self.context\n engine = self.engine_class(context=context, stores=self.stores)\n return engine",
"def engine_version(self) -> typing.Opt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get details about all possible engines for this recipe. This method will raise if there is no engine, whether it's because the present recipe type has no notion of engine, or because DSS couldn't find any viable engine for running the recipe. | def get_engines_details(self):
if not "engines" in self.data:
raise ValueError("This recipe doesn't have engines")
return self.data["engines"] | [
"def available_engines() -> Sequence[\"DiffEngine\"]:\n try:\n return tuple(getattr(DiffEngine, \"_available_engines\"))\n except AttributeError:\n result = []\n try:\n result.append(DiffEngine.create(name=\"native\"))\n except ImportError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save back the recipe in DSS. | def save(self):
self._payload_to_str()
return self.recipe.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.recipe.project_key, self.recipe.recipe_name),
body=self.data) | [
"def saveShelf():\n pass",
"def SaveState(self):\n obj_file = open(self.Name + '.rlx', 'w')\n dump(self, obj_file)",
"def save(self): \r\n dataPath, metaPath, zipPath = self.expPath() \r\n self.save_as(self.data, dataPath) \r\n self.save_as(self.metadata, metaP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the type of the recipe. | def type(self):
return self.recipe_settings["type"] | [
"def read_type(self):\n return type_get_read_type(self)",
"def get_type(self) -> str:\n return self.request_type",
"def type(self):\n return self.kwargs.get(\"type\", str)",
"def get_recipes_by_types(self, recipe_type):\n return self.recopies_list[recipe_type]",
"def get_recipes_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the recipe definition. | def get_recipe_raw_definition(self):
return self.recipe_settings | [
"def recipe(self):\n if self.db.recipe:\n from world.dominion.models import CraftingRecipe\n try:\n recipe = CraftingRecipe.objects.get(id=self.db.recipe)\n return recipe\n except CraftingRecipe.DoesNotExist:\n pass",
"def defini... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |