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
schmittx/home-assistant-eero
custom_components/eero/switch.py
EeroSwitch.turn_on
python
def turn_on(self, **kwargs): setattr(self.resource, self.variable, True)
Turn the device on.
https://github.com/schmittx/home-assistant-eero/blob/3d6960ed239c63fe07d7b2a4da38bf70ea8f9eb0/custom_components/eero/switch.py#L163-L165
import logging from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity from . import EeroEntity from .const import ( CONF_CLIENTS, CONF_EEROS, CONF_NETWORKS, CONF_PROFILES, DATA_COORDINATOR, DOMAIN as EERO_DOMAIN, ) _LOGGER = logging.getLogger(__name__) BASIC_TYPES = { ...
MIT License
ciscodevnet/webexteamssdk
webexteamssdk/api/team_memberships.py
TeamMembershipsAPI.get
python
def get(self, membershipId): check_type(membershipId, basestring) json_data = self._session.get(API_ENDPOINT + '/' + membershipId) return self._object_factory(OBJECT_TYPE, json_data)
Get details for a team membership, by ID. Args: membershipId(basestring): The team membership ID. Returns: TeamMembership: A TeamMembership object with the details of the requested team membership. Raises: TypeError: If the parameter types are i...
https://github.com/ciscodevnet/webexteamssdk/blob/673312779b8e05cf0535bea8b96599015cccbff1/webexteamssdk/api/team_memberships.py#L165-L186
from __future__ import ( absolute_import, division, print_function, unicode_literals, ) from builtins import * from past.builtins import basestring from ..generator_containers import generator_container from ..restsession import RestSession from ..utils import ( check_type, dict_from_items_with_...
MIT License
gamechanger/monufacture
monufacture/helpers.py
random_number
python
def random_number(a, b=None): def build(*args): return random.randrange(a, b) return build
Inserts a random number in the given range into the document.
https://github.com/gamechanger/monufacture/blob/348a9ffeb8c1073d45a7a819208be17ce51fcb6a/monufacture/helpers.py#L211-L215
import monufacture import string import random from pytz import timezone from datetime import datetime, timedelta from bson.objectid import ObjectId from bson.dbref import DBRef class Sequence(object): def __init__(self): self.seq_num = 0 def next(self): self.seq_num = self.seq_num + 1 r...
MIT License
moluwole/bast
bast/controller.py
Controller.write_error
python
def write_error(self, status_code, **kwargs): reason = self._reason if self.settings.get("serve_traceback") and "exc_info" in kwargs: error = [] for line in traceback.format_exception(*kwargs["exc_info"]): error.append(line) else: error = None ...
Handle Exceptions from the server. Formats the HTML into readable form
https://github.com/moluwole/bast/blob/231d3b57fb8fd110e6ddbc668b3909bb6f66b326/bast/controller.py#L36-L50
import importlib import os import traceback from tornado.gen import coroutine from tornado.util import unicode_type from tornado.web import RequestHandler from bast import Bast from .exception import BastException from .jsonifier import Json as json_ from .view import TemplateRendering class Controller(RequestHandler, ...
MIT License
rebiocoder/bioforum
venv/Lib/site-packages/django/contrib/gis/geos/geometry.py
GEOSGeometryBase.geom_typeid
python
def geom_typeid(self): return capi.geos_typeid(self.ptr)
Return an integer representing the Geometry type.
https://github.com/rebiocoder/bioforum/blob/08c8ff2f07ae667d37ce343f537e878d78ac8fe2/venv/Lib/site-packages/django/contrib/gis/geos/geometry.py#L184-L186
import re from ctypes import addressof, byref, c_double from django.contrib.gis import gdal from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.coordseq import GEOSC...
MIT License
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.bottom
python
def bottom(self): return self.height
Bottom coordinate. :return: `int`
https://github.com/psd-tools/psd-tools/blob/00241f3aed2ca52a8012e198a0f390ff7d8edca9/src/psd_tools/api/psd_image.py#L290-L296
from __future__ import absolute_import, unicode_literals import logging from psd_tools.constants import ( Clipping, Compression, ColorMode, SectionDivider, Resource, Tag ) from psd_tools.psd import PSD, FileHeader, ImageData, ImageResources from psd_tools.api.layers import ( Artboard, Group, PixelLayer, ShapeLa...
MIT License
sublimelsp/lsp
plugin/session_buffer.py
SessionBuffer.language_id
python
def language_id(self) -> str: return self.get_language_id() or ""
Deprecated: use get_language_id
https://github.com/sublimelsp/lsp/blob/027333e68d740e1b708ab335f18fdec6d295283b/plugin/session_buffer.py#L133-L137
from .core.protocol import Diagnostic from .core.protocol import DiagnosticSeverity from .core.protocol import DocumentUri from .core.protocol import Range from .core.protocol import TextDocumentSyncKindFull from .core.protocol import TextDocumentSyncKindNone from .core.sessions import SessionViewProtocol from .core.se...
MIT License
ni/hoplite
hoplite/client/remote_job.py
RemoteJob._get_job
python
def _get_job(self, force=False): time_elapsed = time.time() - self._last_poll if time_elapsed > .2 or force: resp = self.jget(self._daemon_addr + '/jobs/{0}'.format(self.uuid)) if resp.status_code == 404: raise JobDoesNotExistError self._set_attributes...
I call this before most other requests to get the status code sanity check. This method is rate limited for sanity
https://github.com/ni/hoplite/blob/bc1b01aa08ba21daa36f46b06000b62890096787/hoplite/client/remote_job.py#L166-L180
import pickle import time from hoplite.client.helpers import ClientMixin from hoplite.exceptions import ( JobDoesNotExistError, TimeoutError, ConnectionError, JobFailedError) from hoplite.serializer import hoplite_loads import requests.exceptions class RemoteJob(ClientMixin): def __init__(self, addr...
MIT License
nipy/nipy
nipy/labs/utils/reproducibility_measures.py
cluster_threshold
python
def cluster_threshold(stat_map, domain, th, csize): if stat_map.shape[0] != domain.size: raise ValueError('incompatible dimensions') thresholded_domain = domain.mask(stat_map > th) label = thresholded_domain.connected_components() binary = - np.ones(domain.size) binary[stat_map > th] = label...
Perform a thresholding of a map at the cluster-level Parameters ---------- stat_map: array of shape(nbvox) the input data domain: Nifti1Image instance, referential- and domain-defining image th (float): cluster-forming threshold csize (int>0): cluster size threshold Retu...
https://github.com/nipy/nipy/blob/d16d268938dcd5c15748ca051532c21f57cf8a22/nipy/labs/utils/reproducibility_measures.py#L55-L92
from __future__ import absolute_import import numpy as np from nipy.io.nibcompat import get_affine from nipy.labs.spatial_models.discrete_domain import grid_domain_from_binary_array def histo_repro(h): k = np.size(h) - 1 if k == 1: return 0. nf = np.dot(h, np.arange(k + 1)) / k if nf == 0: ...
BSD 3-Clause New or Revised License
jgm/pandocfilters
pandocfilters.py
get_value
python
def get_value(kv, key, value = None): res = [] for k, v in kv: if k == key: value = v else: res.append([k, v]) return value, res
get value from the keyvalues (options)
https://github.com/jgm/pandocfilters/blob/06f4db99548a129c3ee8ac667436cb51a80c0f58/pandocfilters.py#L59-L67
import codecs import hashlib import io import json import os import sys import atexit import shutil import tempfile def get_filename4code(module, content, ext=None): if os.getenv('PANDOCFILTER_CLEANUP'): imagedir = tempfile.mkdtemp(prefix=module) atexit.register(lambda: shutil.rmtree(imagedir)) ...
BSD 3-Clause New or Revised License
ali5h/rules_pip
third_party/py/click/formatting.py
HelpFormatter.write_usage
python
def write_usage(self, prog, args="", prefix="Usage: "): usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent) text_width = self.width - self.current_indent if text_width >= (term_len(usage_prefix) + 20): indent = " " * term_len(usage_prefix) self.write( ...
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line.
https://github.com/ali5h/rules_pip/blob/fb02cb7bf5c03bc8cd4269679e4aea2e1839b501/third_party/py/click/formatting.py#L130-L162
from contextlib import contextmanager from ._compat import term_len from .parser import split_opt from .termui import get_terminal_size FORCED_WIDTH = None def measure_table(rows): widths = {} for row in rows: for idx, col in enumerate(row): widths[idx] = max(widths.get(idx, 0), term_len(col...
MIT License
neurotechx/moabb
moabb/datasets/base.py
BaseDataset.get_data
python
def get_data(self, subjects=None): if subjects is None: subjects = self.subject_list if not isinstance(subjects, list): raise (ValueError("subjects must be a list")) data = dict() for subject in subjects: if subject not in self.subject_list: ...
Return the data correspoonding to a list of subjects. The returned data is a dictionary with the folowing structure:: data = {'subject_id' : {'session_id': {'run_id': raw} } } subjects are on t...
https://github.com/neurotechx/moabb/blob/70d27fdb7b96b671d4dfa716451cbe6e49cd7bb6/moabb/datasets/base.py#L77-L115
import abc import logging from inspect import signature log = logging.getLogger(__name__) class BaseDataset(metaclass=abc.ABCMeta): def __init__( self, subjects, sessions_per_subject, events, code, interval, paradigm, doi=None, unit_factor=1e6,...
BSD 3-Clause New or Revised License
carlmontanari/nornir_ansible
nornir_ansible/plugins/inventory/ansible.py
_get_inventory_element
python
def _get_inventory_element( typ: Type[HostOrGroup], data: Dict[str, Any], name: str, defaults: Defaults ) -> HostOrGroup: return typ( name=name, hostname=data.get("hostname"), port=data.get("port"), username=data.get("username"), password=data.get("password"), pla...
Get inventory information for a given host/group Arguments: data: dictionary of host or group data to serialize
https://github.com/carlmontanari/nornir_ansible/blob/f5ef4e792bdcce7071a35ce624ef55497b423463/nornir_ansible/plugins/inventory/ansible.py#L475-L496
import configparser as cp import logging from collections import defaultdict from pathlib import Path from typing import Any, DefaultDict, Dict, List, MutableMapping, Optional, Tuple, Type, Union, cast import ruamel.yaml from mypy_extensions import TypedDict from nornir.core.exceptions import NornirNoValidInventoryErro...
Apache License 2.0
nosarthur/gita
gita/utils.py
get_relative_path
python
def get_relative_path(kid: str, parent: str) -> Union[List[str], None]: if parent == '': return None if parent == os.path.commonpath((kid, parent)): rel = os.path.normpath(os.path.relpath(kid, parent)).split(os.sep) if rel == ['.']: rel = [] return rel else: ...
Return the relative path depth if relative, otherwise MAX_INT. Both the `kid` and `parent` should be absolute paths without trailing /
https://github.com/nosarthur/gita/blob/09e6f755c95764ada1ca0e677aa74e49c32f5ab4/gita/utils.py#L20-L37
import sys import os import json import csv import asyncio import platform import subprocess from functools import lru_cache, partial from pathlib import Path from typing import List, Dict, Coroutine, Union, Iterator, Tuple from collections import Counter, defaultdict from . import info from . import common MAX_INT = s...
MIT License
mila-iqia/myia
myia/operations/prim_random_initialize.py
bprop_random_initialize
python
def bprop_random_initialize(seed, out, dout): return (zeros_like(seed),)
Backpropagator for primitive `random_initialize`.
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/operations/prim_random_initialize.py#L27-L29
import numpy as np from .. import xtype from ..lib import ( AbstractRandomState, bprop_to_grad_transform, standard_prim, zeros_like, ) from . import primitives as P def pyimpl_random_initialize(seed): return np.random.RandomState(seed) @standard_prim(P.random_initialize) async def infer_random_initi...
MIT License
tlc-pack/tenset
python/tvm/contrib/tedd.py
insert_dot_id
python
def insert_dot_id(sch): for stage_idx, stage in enumerate(sch["stages"]): dom_path = [stage_idx] stage["id"] = dom_path_to_string(dom_path, stage["type"]) for itervar_idx, itervar in enumerate(stage["all_itervars"]): dom_path = [stage_idx, itervar_idx] itervar["id"] =...
Insert unique ID for each node in the DOM tree. They are used as Dot node ID.
https://github.com/tlc-pack/tenset/blob/3f7ed0291df47331d43f43a064fffacdc2914b47/python/tvm/contrib/tedd.py#L62-L78
import html import json import warnings from graphviz import Digraph from graphviz import Source import tvm TVMDD_TABLE_BODY_WIDTH = 30 ITERVAR_TYPE_STRING_MAP = { 0: ("kDataPar", "#FFFFFF"), 1: ("kThreadIndex", "#2980B9"), 2: ("kCommReduce", "#FAD7A0"), 3: ("kOrdered", "#D35400"), 4: ("kOpaque", "#...
Apache License 2.0
ekimekim/factoriocalc
factoriocalc/calculator.py
split_into_steps
python
def split_into_steps(processes, input_limit=None, input_liquid_limit=None): def limit(item, input=False): if input and is_liquid(item) and input_liquid_limit is not None: return input_liquid_limit elif input and not is_liquid(item) and input_limit is not None: return input_limit else: return line_limit(...
Splits a dict of full processes into an unordered list of steps, where each step uses no more than 1 belt for each input or output. To prevent balance issues, all but the final step is maximised, ie. scaled to the point that one or more inputs or outputs is running at exactly 45 items/sec. Since raw inputs aren't ...
https://github.com/ekimekim/factoriocalc/blob/18583ee0ea16a12c061b272db68469edee86606d/factoriocalc/calculator.py#L257-L305
from fractions import Fraction from .util import line_limit, is_liquid class Process(object): def __init__(self, item, recipe, throughput, outputs=None): self.item = item self.recipe = recipe self.throughput = throughput if outputs: self.per_process_outputs = outputs elif self.recipe and self.recipe.is_vi...
MIT License
dmlc/gluon-nlp
src/gluonnlp/base.py
use_einsum_optimization
python
def use_einsum_optimization(): flag = os.environ.get('GLUONNLP_USE_EINSUM', False) return flag
Whether to use einsum for attention. This will potentially accelerate the attention cell Returns ------- flag The use einsum flag
https://github.com/dmlc/gluon-nlp/blob/5d4bc9eba7226ea9f9aabbbd39e3b1e886547e48/src/gluonnlp/base.py#L73-L84
import os import numpy as np __all__ = ['get_home_dir', 'get_data_home_dir'] INT_TYPES = (int, np.int32, np.int64) FLOAT_TYPES = (float, np.float16, np.float32, np.float64) def get_home_dir(): _home_dir = os.environ.get('GLUONNLP_HOME', os.path.join('~', '.gluonnlp')) _home_dir = os.path.expanduser(_home_dir) ...
Apache License 2.0
ciscodevnet/virl2-client
virl2_client/models/lab.py
Lab.create_interface_local
python
def create_interface_local( self, iface_id, label, node, slot, iface_type="physical" ): if iface_id not in self._interfaces: iface = Interface(iface_id, node, label, slot, iface_type) self._interfaces[iface_id] = iface else: self._interfaces[iface_id].no...
Helper function to create an interface in the client library.
https://github.com/ciscodevnet/virl2-client/blob/b1e6f5b40375f5154b40fce5d3d4fffdd67e7977/virl2_client/models/lab.py#L695-L707
import json import logging import time from .node import Node from .interface import Interface from .link import Link from ..exceptions import LabNotFound, LinkNotFound, NodeNotFound from .cl_pyats import ClPyats logger = logging.getLogger(__name__) class Lab: def __init__( self, title, lab_...
Apache License 2.0
emorynlp/bert-2019
bertsota/common/data.py
ParserVocabulary._add_pret_words
python
def _add_pret_words(self, pret_file): words_in_train_data = set(self._id2word) with open(pret_file) as f: for line in f: line = line.strip().split() if line: word = line[0] if word not in words_in_train_data: ...
Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_file : str path to pre-trained embedding file
https://github.com/emorynlp/bert-2019/blob/228b2046d92084ea3cd7c900c1d8af1f0a925cfe/bertsota/common/data.py#L197-L213
import pickle from collections import Counter import numpy as np from bertsota.common.k_means import KMeans from bertsota.common.savable import Savable class ConllWord(object): def __init__(self, id, form, lemma=None, cpos=None, pos=None, feats=None, head=None, relation=None, phead=None, pdeprel=No...
Apache License 2.0
openstack/rally-openstack
tests/functional/test_task_samples.py
TestTaskSamples._skip
python
def _skip(self, validation_output): skip_lst = ["[Ss]ervice is not available", "is not installed. To install it run", "extension.* is not configured"] for check_str in skip_lst: if re.search(check_str, validation_output) is not None: re...
Help to decide do we want to skip this result or not. :param validation_output: string representation of the error that we want to check :return: True if we want to skip this error of task sample validation, otherwise False.
https://github.com/openstack/rally-openstack/blob/d52e165320d87860930d6fbcca105e19bec0d879/tests/functional/test_task_samples.py#L39-L54
import copy import json import os import re import traceback import unittest from rally import api from rally.cli import yamlutils as yaml from rally.common import broker from rally import plugins import rally_openstack as rally_openstack_module from rally_openstack.common import consts from rally_openstack.common impo...
Apache License 2.0
ddorn/gui
GUI/base.py
BaseWidget.__init__
python
def __init__(self, pos, size, anchor=CENTER): self.__verify(pos) self.__verify(size) super().__init__((0, 0), (0, 0)) self._anchor = anchor self._pos = pos self._size = size self._focus = False self.clicked = False
Creates a Basic Widget with... nothing The pos, size and anchor can be tuples or funcions that returns a tuple (an anchostr for the anchor)
https://github.com/ddorn/gui/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/base.py#L24-L40
import pygame from GUI.locals import CENTER, TOPLEFT, TOPRIGHT, MIDTOP, MIDLEFT, MIDRIGHT, BOTTOMRIGHT, MIDBOTTOM, BOTTOMLEFT from pygame.event import EventType class BaseWidget(pygame.Rect):
MIT License
vovanec/supervisor_checks
supervisor_checks/bin/tcp_check.py
_make_argument_parser
python
def _make_argument_parser(): parser = argparse.ArgumentParser( description='Run TCP check program.') parser.add_argument('-n', '--check-name', dest='check_name', type=str, required=True, default=None, help='Check name.') parser.add_argument('-g', '--pr...
Create the option parser.
https://github.com/vovanec/supervisor_checks/blob/f44b105659d60d0e1f1845b111fec148ae5514e5/supervisor_checks/bin/tcp_check.py#L20-L50
import argparse import sys from supervisor_checks import check_runner from supervisor_checks.check_modules import tcp __author__ = 'vovanec@gmail.net'
MIT License
ibm/superglue-mtl
data_utils.py
COPALoader.get_labels
python
def get_labels(self): return [0]
this is set to [0] because we treat each subinstance as a logistic regression task
https://github.com/ibm/superglue-mtl/blob/1eb3e581c0ef3b4c261e0256ec26116d2b657c40/data_utils.py#L633-L635
import os import json import logging import torch import numpy as np from torch.utils.data import TensorDataset, Dataset logging.getLogger().setLevel(logging.INFO) DATA_PATH = os.environ["SG_DATA"] EXP_PATH = os.environ["SG_MTL_EXP"] BERT_LARGE_MNLI_PATH = "/datastor/xhua/Experiments/mnli_bert_large_no_transfer_seed_42...
Apache License 2.0
seldonio/alibi
alibi/utils/lang_model.py
BertBaseUncased.__init__
python
def __init__(self, preloading: bool = True): super().__init__("bert-base-uncased", preloading)
Initialize BertBaseUncased. Parameters ---------- preloading See `LanguageModel` constructor.
https://github.com/seldonio/alibi/blob/ef757b9579f85ef2e3dfc7088211969616ee3fdb/alibi/utils/lang_model.py#L343-L352
import abc import numpy as np from pathlib import Path from typing import List, Optional, Tuple, Union import tensorflow as tf import transformers from transformers import TFAutoModelForMaskedLM, AutoTokenizer class LanguageModel(abc.ABC): SUBWORD_PREFIX = '' def __init__(self, model_path: str, preloading: bool...
Apache License 2.0
uok-psychology/django-questionnaire
questionnaire/forms.py
generate_radioselect_field
python
def generate_radioselect_field(): return ChoiceField(widget=RadioSelect,choices=[])
@return radioselect field no default set TODO: this isn't actually true, it returns a ChoiceField that has a RadioSelect widget
https://github.com/uok-psychology/django-questionnaire/blob/50c85328306533554e0f9c56794f54422cb12bc9/questionnaire/forms.py#L54-L58
from django import forms from django.forms.fields import CharField,BooleanField,ChoiceField,MultipleChoiceField, TypedChoiceField from django.forms.widgets import RadioSelect, CheckboxInput from questionnaire.models import AnswerSet def get_choices(question): choices_list = question.selectoptions if choices_...
MIT License
vitorazor/lidar_rgb_detector
second/builder/dataset_builder.py
build
python
def build(input_reader_config, model_config, training, voxel_generator, target_assigner, multi_gpu=False): if not isinstance(input_reader_config, input_reader_pb2.InputReader): raise ValueError('input_reader_config not of type ' 'inp...
Builds a tensor dictionary based on the InputReader config. Args: input_reader_config: A input_reader_pb2.InputReader object. Returns: A tensor dict based on the input_reader_config. Raises: ValueError: On invalid input reader proto. ValueError: If no input paths are speci...
https://github.com/vitorazor/lidar_rgb_detector/blob/5308ba24a90d6e8d73940be4b40d31eccb4df94b/second/builder/dataset_builder.py#L34-L135
from second.protos import input_reader_pb2 from second.data.dataset import get_dataset_class from second.data.preprocess import prep_pointcloud from second.core import box_np_ops import numpy as np from second.builder import dbsampler_builder from functools import partial from second.utils.config_tool import get_downsa...
MIT License
rapid7/vm-console-client-python
rapid7vmconsole/models/site.py
Site.risk_score
python
def risk_score(self, risk_score): self._risk_score = risk_score
Sets the risk_score of this Site. The risk score (with criticality adjustments) of the site. # noqa: E501 :param risk_score: The risk_score of this Site. # noqa: E501 :type: float
https://github.com/rapid7/vm-console-client-python/blob/55e1f573967bce27cc9a2d10c12a949b1142c2b3/rapid7vmconsole/models/site.py#L310-L319
import pprint import re import six class Site(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. ...
MIT License
gadsbyfly/pybiomed
PyBioMed/PyMolecule/fingerprint.py
CalculateAtomPairsFingerprint
python
def CalculateAtomPairsFingerprint(mol): res = Pairs.GetAtomPairFingerprint(mol) return res.GetLength(), res.GetNonzeroElements(), res
################################################################# Calculate atom pairs fingerprints Usage: result=CalculateAtomPairsFingerprint(mol) Input: mol is a molecule object. Output: result is a tuple form. The first is the number of fingerprints. The second is a dict...
https://github.com/gadsbyfly/pybiomed/blob/8db017961390dbcdcb7060fec758b9b8b9fc604f/PyBioMed/PyMolecule/fingerprint.py#L219-L241
from openbabel import pybel from rdkit import Chem, DataStructs from rdkit.Chem import AllChem, ChemicalFeatures, MACCSkeys from rdkit.Chem.AtomPairs import Pairs, Torsions from rdkit.Chem.Fingerprints import FingerprintMols from rdkit.Chem.Pharm2D import Generate from rdkit.Chem.Pharm2D.SigFactory import SigFactory fr...
BSD 3-Clause New or Revised License
saketkc/pysradb
pysradb/utils.py
order_dataframe
python
def order_dataframe(df, columns): remaining_columns = [w for w in df.columns if w not in columns] df = df[columns + remaining_columns] return df
Order a dataframe Order a dataframe by moving the `columns` in the front Parameters ---------- df: Dataframe Dataframe columns: list List of columns that need to be put in front
https://github.com/saketkc/pysradb/blob/bce1726813a104ff83eb1221679bf93074252af6/pysradb/utils.py#L177-L191
import errno import gzip import io import ntpath import os import shlex import subprocess import urllib.request as urllib_request import warnings import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from tqdm.autonotebook import tqdm from .exceptions import In...
BSD 3-Clause New or Revised License
napari/napari
napari/_qt/containers/_base_item_model.py
_BaseEventedItemModel._on_end_insert
python
def _on_end_insert(self, e): self.endInsertRows()
Must be called after insert operation to update model.
https://github.com/napari/napari/blob/c4c987c880fe125da608edf427767eafe7f2b3f4/napari/_qt/containers/_base_item_model.py#L244-L246
from __future__ import annotations from collections.abc import MutableSequence from typing import TYPE_CHECKING, Any, Generic, Tuple, TypeVar, Union from qtpy.QtCore import QAbstractItemModel, QModelIndex, Qt from ...utils.events import disconnect_events from ...utils.events.containers import SelectableEventedList from...
BSD 3-Clause New or Revised License
compas-dev/compas
src/compas/data/data.py
Data.from_json
python
def from_json(cls, filepath): data = compas.json_load(filepath) return cls.from_data(data)
Construct an object from serialized data contained in a JSON file. Parameters ---------- filepath : path string, file-like object or URL string The path, file or URL to the file for serialization. Returns ------- :class:`compas.data.Data` An obje...
https://github.com/compas-dev/compas/blob/d795a8bfe9f21ffa124d09e37e9c0ed2e3520057/src/compas/data/data.py#L170-L184
from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import json from uuid import uuid4 from copy import deepcopy import compas from compas.data.encoders import DataEncoder from compas.data.encoders import DataDecoder class Data(object): def __init__...
MIT License
gaa-uam/scikit-fda
skfda/exploratory/visualization/_utils.py
_get_axes_shape
python
def _get_axes_shape( n_axes: int, n_rows: Optional[int] = None, n_cols: Optional[int] = None, ) -> Tuple[int, int]: if ( (n_rows is not None and n_cols is not None) and ((n_rows * n_cols) < n_axes) ): raise ValueError( f"The number of rows ({n_rows}) multiplied by...
Get the number of rows and columns of the subplots.
https://github.com/gaa-uam/scikit-fda/blob/1a6fc2c01e39871e09fd2ec6d0b14d378d6b069f/skfda/exploratory/visualization/_utils.py#L113-L140
import io import math import re from itertools import repeat from typing import Optional, Sequence, Tuple, TypeVar, Union import matplotlib.backends.backend_svg import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure from typing_extensions import Protocol from ...representa...
BSD 3-Clause New or Revised License
thecesrom/ignition
src/system/nav.py
openWindow
python
def openWindow(path, params=None): print(path, params) return FPMIWindow("Opened Window")
Opens the window with the given path. If the window is already open, brings it to the front. The optional params dictionary contains key:value pairs which will be used to set the target window's root container's dynamic variables. Args: path (str): The path to the window to open. param...
https://github.com/thecesrom/ignition/blob/c784e573530a217f4c430bd110889ce569152747/src/system/nav.py#L135-L154
from __future__ import print_function __all__ = [ "centerWindow", "closeParentWindow", "closeWindow", "desktop", "getCurrentWindow", "goBack", "goForward", "goHome", "openWindow", "openWindowInstance", "swapTo", "swapWindow", ] from com.inductiveautomation.factorypmi.appl...
MIT License
jdasoftwaregroup/kartothek
kartothek/io/eager.py
delete_dataset
python
def delete_dataset(dataset_uuid=None, store=None, factory=None): ds_factory = _ensure_factory( dataset_uuid=dataset_uuid, load_schema=False, store=store, factory=factory, load_dataset_metadata=False, ) garbage_collect_dataset(factory=ds_factory) delete_indices(dat...
Delete the entire dataset from the store. Parameters ----------
https://github.com/jdasoftwaregroup/kartothek/blob/6bc7e868435e98cbda0b695900f29d1ff7d49110/kartothek/io/eager.py#L71-L101
import warnings from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union, cast import pandas as pd from simplekv import KeyValueStore from kartothek.core.common_metadata import ( empty_dataframe_from_schema, make_meta, store_schema_metadata, ) from kartoth...
MIT License
asdf-format/asdf
asdf/util.py
BinaryStruct.pack
python
def pack(self, **kwargs): fields = [0] * len(self._names) for key, val in kwargs.items(): if key not in self._offsets: raise KeyError("No header field '{0}'".format(key)) i = self._names.index(key) fields[i] = val return struct.pack(self._fmt, ...
Pack the given arguments, which are given as kwargs, and return the binary struct.
https://github.com/asdf-format/asdf/blob/ee34d21e2d0e8834128716cc72fd47f31856d00e/asdf/util.py#L171-L182
import enum import inspect import math import struct import types import importlib.util import re from functools import lru_cache from urllib.request import pathname2url import numpy as np from . import constants urllib_parse_spec = importlib.util.find_spec('urllib.parse') patched_urllib_parse = importlib.util.module_f...
BSD 3-Clause New or Revised License
jahjajaka/afternoon_cleaner
object_detection/dataset_tools/create_coco_tf_record.py
create_tf_example
python
def create_tf_example(image, annotations_list, image_dir, category_index, include_masks=False): image_height = image['height'] image_width = image['width'] filename = image['file_name'] image_id = image['id'] full_path = o...
Converts image and annotations to a tf.Example proto. Args: image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] annotations_list: list of dicts with keys: [u'segmentation', u'area', u'iscrowd', u'image_id', ...
https://github.com/jahjajaka/afternoon_cleaner/blob/590bdf58a216cbc6cfc47ef8f49d7af3df3703b7/object_detection/dataset_tools/create_coco_tf_record.py#L73-L191
from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import io import json import os import contextlib2 import numpy as np import PIL.Image from pycocotools import mask import tensorflow as tf from object_detection.dataset_tools import tf_record_cre...
MIT License
edinburghnlp/nematus
nematus/server_translator.py
Translator._load_model_options
python
def _load_model_options(self): self._options = [] for model in self._models: config = load_config_from_json_file(model) setattr(config, 'reload', model) self._options.append(config) _, _, _, self._num_to_target = util.load_dictionaries(self._options[0])
Loads config options for each model.
https://github.com/edinburghnlp/nematus/blob/d55074a2e342a33a4d5b0288cbad6269bd47271d/nematus/server_translator.py#L63-L74
import logging import sys import time from multiprocessing import Process, Queue from collections import defaultdict from queue import Empty import numpy from beam_search_sampler import BeamSearchSampler from config import load_config_from_json_file import exception import model_loader import rnn_model from transformer...
BSD 3-Clause New or Revised License
webrecorder/wacz-format
py-wacz/wacz/util.py
get_py_wacz_version
python
def get_py_wacz_version(): return pkg_resources.get_distribution("wacz").version
Get version of the py-wacz package
https://github.com/webrecorder/wacz-format/blob/80083019bb0cbac645df356ff2d223e37671abe7/py-wacz/wacz/util.py#L30-L32
import hashlib, datetime, json from warcio.timeutils import iso_date_to_timestamp import pkg_resources WACZ_VERSION = "1.1.1" def check_http_and_https(url, ts, pages_dict): url_body = url.split(":")[1] checks = [ f"http:{url_body}", f"https:{url_body}", f"{ts}/http:{url_body}", f...
MIT License
hsuxu/magic-vnet
magic_vnet/blocks/squeeze_excitation.py
ChannelSELayer3D.__init__
python
def __init__(self, num_channels, reduction_ratio=2, act_type=nn.ReLU): super(ChannelSELayer3D, self).__init__() self.avg_pool = nn.AdaptiveAvgPool3d(1) num_channels_reduced = num_channels // reduction_ratio self.reduction_ratio = reduction_ratio self.fc1 = nn.Linear(num_channels,...
:param num_channels: No of input channels :param reduction_ratio: By how much should the num_channels should be reduced
https://github.com/hsuxu/magic-vnet/blob/6958932f3974d268e93bd6443369a3f43c497ed3/magic_vnet/blocks/squeeze_excitation.py#L13-L25
import torch from torch import nn from torch.nn import functional as F class ChannelSELayer3D(nn.Module):
MIT License
lbtcio/lbtc-lightwallet-server
wallet/bip32.py
PrivKey._privkey_secret_exponent
python
def _privkey_secret_exponent(cls, privkey): if not isinstance(privkey, (bytes, bytearray)): raise TypeError('privkey must be raw bytes') if len(privkey) != 32: raise ValueError('privkey must be 32 bytes') exponent = bytes_to_int(privkey) if not 1 <= exponent < cls...
Return the private key as a secret exponent if it is a valid private key.
https://github.com/lbtcio/lbtc-lightwallet-server/blob/4fe64576fb0c45c41cbf72de2390d23ebebfc9c3/wallet/bip32.py#L189-L200
import struct import ecdsa import ecdsa.ellipticcurve as EC import ecdsa.numbertheory as NT from lib.coins import Coin from lib.hash import Base58, hmac_sha512, hash160 from lib.util import cachedproperty, bytes_to_int, int_to_bytes class DerivationError(Exception): class _KeyBase(object): CURVE = ecdsa.SECP256k1 ...
MIT License
apache/cassandra-dtest
upgrade_tests/upgrade_manifest.py
VersionMeta.clone_with_local_env_version
python
def clone_with_local_env_version(self): cassandra_dir, cassandra_version = cassandra_dir_and_version(CONFIG) if cassandra_version: return self._replace(version=cassandra_version) return self._replace(version="clone:{}".format(cassandra_dir))
Returns a new object cloned from this one, with the version replaced with the local env version.
https://github.com/apache/cassandra-dtest/blob/7c3333958e2b2bd53018a50ab1f529e1a2cca173/upgrade_tests/upgrade_manifest.py#L144-L151
import logging from collections import namedtuple from dtest import RUN_STATIC_UPGRADE_MATRIX from conftest import cassandra_dir_and_version import ccmlib.repository from ccmlib.common import get_version_from_build from enum import Enum logger = logging.getLogger(__name__) UpgradePath = namedtuple('UpgradePath', ('name...
Apache License 2.0
ns1/ns1-python
ns1/__init__.py
NS1.zones
python
def zones(self): import ns1.rest.zones return ns1.rest.zones.Zones(self.config)
Return a new raw REST interface to zone resources :rtype: :py:class:`ns1.rest.zones.Zones`
https://github.com/ns1/ns1-python/blob/0fed6588108dc1bfe683286dd422541e75f74ca0/ns1/__init__.py#L46-L54
from .config import Config version = "0.16.1" class NS1: def __init__(self, apiKey=None, config=None, configFile=None, keyID=None): self.config = config if self.config is None: self._loadConfig(apiKey, configFile) if keyID: self.config.useKeyID(keyID) def _loadCon...
MIT License
square/bionic
bionic/persistence.py
Inventory.find_entry
python
def find_entry(self, provenance): logger.debug("In %s inventory for %r, searching ...", self.tier, provenance) n_prior_attempts = 0 while True: if n_prior_attempts in (10, 100, 1000, 10000, 100000, 1000000): message = f""" While searching in the {s...
Returns an InventoryEntry describing the closest match to the provided Provenance.
https://github.com/square/bionic/blob/357da8e2806996427e0aa6efd08f7ea8c5198f9b/bionic/persistence.py#L480-L535
import attr import cattr import os import shutil import tempfile from typing import List, Optional, Tuple import yaml import warnings from uuid import uuid4 from pathlib import Path from .datatypes import CodeFingerprint, Artifact from .utils.files import ( ensure_dir_exists, ensure_parent_dir_exists, ) from .u...
Apache License 2.0
lawsie/guizero
guizero/base.py
BaseWindow.__init__
python
def __init__(self, master, tk, title, width, height, layout, bg, visible): super(BaseWindow, self).__init__(master, tk, layout, False) self.tk.title( str(title) ) self.tk.geometry(str(width)+"x"+str(height)) self._on_close = None self._full_screen = False self._icon = Non...
Base class for objects which use windows e.g. `App` and `Window`
https://github.com/lawsie/guizero/blob/7744c41a1e747ade2e5913638586073c27b4db9b/guizero/base.py#L478-L498
from .tkmixins import ( ScheduleMixin, DestroyMixin, EnableMixin, FocusMixin, DisplayMixin, TextMixin, ColorMixin, SizeMixin, LayoutMixin, EventsMixin) from . import utilities as utils from .event import EventManager from . import dialog from tkinter import BOTH, X, Y, YES class ...
BSD 3-Clause New or Revised License
altosaar/deep-exponential-families-gluon
common/util.py
score_grad_variance_callback
python
def score_grad_variance_callback(my_model): params = my_model.collect_params() param_grads = collections.defaultdict(lambda: []) for name, param in params.items(): if param.grad_req != 'null': grads = np.stack(param_grads[name]) param.grad_variance = np.mean(np.var(grads, axis=0)) param.gr...
Get score function gradient variance.
https://github.com/altosaar/deep-exponential-families-gluon/blob/80d69b54081f622c0012bb181aa6d8ab9a740f15/common/util.py#L101-L121
import os import logging import mxnet as mx import numpy as np import collections from mxnet import nd def log_to_file(filename): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-4s %(levelname)-4s %(message)s', datefmt='%m-%d %H:%M', ...
MIT License
chandler37/immaculater
pyatdllib/ui/uicmd.py
_PerformLs
python
def _PerformLs(current_obj, location, state, recursive, show_uid, show_all, show_timestamps, view_filter_override=None): if show_all and isinstance(current_obj, container.Container): state.Print(_ListingForOneItem( show_uid, show_timestamps, current_obj, state.ToDo...
Performs 'ls'. Args: current_obj: AuditableObject location: basestring state: State recursive: bool show_uid: bool show_all: bool show_timestamps: bool view_filter_override: None|ViewFilter
https://github.com/chandler37/immaculater/blob/13bfe8c949a16945d2195920375ad6d522664208/pyatdllib/ui/uicmd.py#L734-L792
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import base64 import datetime import json import pipes import pytz import random import re import six from six.moves import xrange import time from absl import flags from google.protobuf import text_...
Apache License 2.0
pinterest/kingpin
kingpin/manageddata/decider.py
Decider.is_hashed_id_in_experiment
python
def is_hashed_id_in_experiment(self, unique_id, experiment_name): decider_value = self.get_decider_value(experiment_name) hash_val = hashlib.md5("decider_%s%s" % (experiment_name, unique_id)).hexdigest() val = int(hash_val, 16) % 100 return val < decider_value
Checks if a decider should be active given an ID (e.g. of a user, random request, etc.). This function computes a hash of the user ID and the decider, so different deciders will get different random samples of users. Ex: decider.is_hashed_id_in_decider(context.viewing_user.id, config.decider...
https://github.com/pinterest/kingpin/blob/baea08ae941a4e57edb9129658fe3e7d40e4d0c3/kingpin/manageddata/decider.py#L99-L114
import logging import hashlib import random from managed_datastructures import ManagedHashMap from ..kazoo_utils.decorators import SingletonMetaclass log = logging.getLogger(__name__) class Decider(object): __metaclass__ = SingletonMetaclass def __init__(self): self.initialized = False def initializ...
Apache License 2.0
davemlz/eemont
eemont/extra.py
require
python
def require(module): return ee_require(module)
Loads and executes a JavaScript GEE module. All modules must be first installed before requiring them. After requiring the module, it can be used in the same way as it is used in the Code Editor. Warning ------- This method is highly :code:`experimental`. Please report any irregularities in the ...
https://github.com/davemlz/eemont/blob/f8eb4099b5c1d07d217d6c1be054dc33c9283a00/eemont/extra.py#L10-L43
import ee from ee_extra.JavaScript.install import install as ee_install from ee_extra.JavaScript.install import uninstall as ee_uninstall from ee_extra.JavaScript.main import ee_require from .extending import extend @extend(ee)
MIT License
a3data/hermione
hermione/module_templates/__IMPLEMENTED_SAGEMAKER__/src/ml/analysis/feature_selection.py
FeatureSelector.inverse_transform
python
def inverse_transform(self, df: pd.DataFrame): pass
Apply the invese_transform of vectorizer to each column Options: index, bag_of_words and tf_idf Parameters ---------- df : pd.DataFrame dataframe with columns to be unvectorizer Returns ------- pd.DataFrame
https://github.com/a3data/hermione/blob/4a833e96664fc91c65bdd28b2637c291f4f5a4d6/hermione/module_templates/__IMPLEMENTED_SAGEMAKER__/src/ml/analysis/feature_selection.py#L317-L333
from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import SelectPercentile from sklearn.feature_selection import RFE from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import SequentialFeatureSelector...
Apache License 2.0
brendanhasz/probflow
src/probflow/utils/validation.py
ensure_tensor_like
python
def ensure_tensor_like(obj, name): if isinstance(obj, (int, float, np.ndarray, list)): return if get_backend() == "pytorch": import torch tensor_types = (torch.Tensor, BaseParameter) else: import tensorflow as tf tensor_types = (tf.Tensor, tf.Variable, BaseParameter) ...
Determine whether an object can be cast to a Tensor
https://github.com/brendanhasz/probflow/blob/27fade8d85d37ffc0193862d0329c9255f3c74e7/src/probflow/utils/validation.py#L18-L35
import numpy as np from probflow.utils.base import BaseParameter from probflow.utils.settings import get_backend
MIT License
twidi/mixt
src/mixt/vendor/pytypes/util.py
get_class_that_defined_method
python
def get_class_that_defined_method(meth): if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): try: cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.') ...
Determines the class owning the given method.
https://github.com/twidi/mixt/blob/adeff652784f0d814835fd16a8cacab09f426922/src/mixt/vendor/pytypes/util.py#L416-L438
from mixt.vendor import pytypes import subprocess import hashlib import sys import os import inspect import traceback from warnings import warn_explicit _code_callable_dict = {} _sys_excepthook = sys.__excepthook__ def _check_python3_5_version(): try: ver = subprocess.check_output([pytypes.python3_5_executa...
MIT License
jeeftor/alfredtoday
src/lib/pyexchange/exchange2010/__init__.py
Exchange2010CalendarEvent.resend_invitations
python
def resend_invitations(self): if not self.id: raise TypeError(u"You can't send invites for an event that hasn't been created yet.") if self._dirty_attributes: raise ValueError(u"There are unsaved changes to this invite - please update it first: %r" % self._dirty_attributes) self.refresh_change_k...
Resends invites for an event. :: event = service.calendar().get_event(id='KEY HERE') event.resend_invitations() Anybody who has not declined this meeting will get a new invite.
https://github.com/jeeftor/alfredtoday/blob/f6e2c2228caa71015e654e1fdbf552e2ca4f90ad/src/lib/pyexchange/exchange2010/__init__.py#L267-L289
import logging from ..base.calendar import BaseExchangeCalendarEvent, BaseExchangeCalendarService, ExchangeEventOrganizer, ExchangeEventResponse from ..base.folder import BaseExchangeFolder, BaseExchangeFolderService from ..base.soap import ExchangeServiceSOAP from ..exceptions import FailedExchangeException, ExchangeS...
MIT License
databand-ai/dbnd
modules/dbnd/src/dbnd/_vendor/dulwich/repo.py
BaseRepo._init_files
python
def _init_files(self, bare): from dbnd._vendor.dulwich.config import ConfigFile self._put_named_file("description", b"Unnamed repository") f = BytesIO() cf = ConfigFile() cf.set("core", "repositoryformatversion", "0") if self._determine_file_mode(): cf.set("co...
Initialize a default set of named files.
https://github.com/databand-ai/dbnd/blob/ec0076f9a142b20e2f7afd886ed1a18683c553ec/modules/dbnd/src/dbnd/_vendor/dulwich/repo.py#L212-L229
from io import BytesIO import errno import os import sys import stat import time from dbnd._vendor.dulwich.errors import ( NoIndexPresent, NotBlobError, NotCommitError, NotGitRepository, NotTreeError, NotTagError, CommitError, RefFormatError, HookError, ) from dbnd._vendor.dulwich.fi...
Apache License 2.0
hbldh/pyefd
pyefd.py
elliptic_fourier_descriptors
python
def elliptic_fourier_descriptors( contour, order=10, normalize=False, return_transformation=False ): dxy = np.diff(contour, axis=0) dt = np.sqrt((dxy ** 2).sum(axis=1)) t = np.concatenate([([0.0]), np.cumsum(dt)]) T = t[-1] phi = (2 * np.pi * t) / T orders = np.arange(1, order + 1) const...
Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficients should be normalized; see references for details. :param bool r...
https://github.com/hbldh/pyefd/blob/17da03001365a24a9570790133ea39b58d5cd2c0/pyefd.py#L37-L84
from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import numpy as np try: _range = xrange except NameError: _range = range
MIT License
sdispater/orator
orator/orm/relations/relation.py
Relation.__init__
python
def __init__(self, query, parent): self._query = query self._parent = parent self._related = query.get_model() self._extra_query = None self.add_constraints()
:param query: A Builder instance :type query: orm.orator.Builder :param parent: The parent model :type parent: Model
https://github.com/sdispater/orator/blob/0666e522be914db285b6936e3c36801fc1a9c2e7/orator/orm/relations/relation.py#L13-L26
from contextlib import contextmanager from ...query.expression import QueryExpression from ..collection import Collection from ..builder import Builder class Relation(object): _constraints = True
MIT License
theetcher/fxpt
fxpt/side_utils/profilehooks.py
FuncTimer.__call__
python
def __call__(self, *args, **kw): fn = self.fn timer = self.timer self.ncalls += 1 try: start = timer() return fn(*args, **kw) finally: duration = timer() - start self.totaltime += duration if self.immediate: ...
Profile a singe call to the function.
https://github.com/theetcher/fxpt/blob/d40c571885c7c4056f548a60140740c7beb8703d/fxpt/side_utils/profilehooks.py#L731-L749
__author__ = "Marius Gedminas <marius@gedmin.as>" __copyright__ = "Copyright 2004-2014 Marius Gedminas" __license__ = "MIT" __version__ = "1.7.1" __date__ = "2014-12-02" import atexit import inspect import sys import re from profile import Profile import pstats try: import hotshot import hotshot.stats except Im...
MIT License
adaptivepele/adaptivepele
AdaptivePELE/utilities/utilities.py
getMetricsFromReportsInEpoch
python
def getMetricsFromReportsInEpoch(reportName, outputFolder, nTrajs): metrics = [] for i in range(1, nTrajs): report = np.loadtxt(os.path.join(outputFolder, reportName % i)) if len(report.shape) < 2: metrics.append(report.tolist()+[i, 0]) else: traj_line = np.array(...
Extract the metrics in report file from an epoch to a numpy array
https://github.com/adaptivepele/adaptivepele/blob/b7c908a53a2ba9ec19fa81a517377cc365176036/AdaptivePELE/utilities/utilities.py#L640-L653
from __future__ import absolute_import, division, print_function, unicode_literals import os import ast import sys import glob import json import errno import socket import shutil import string from builtins import range import six from six import reraise as raise_ import numpy as np import mdtraj as md from scipy impo...
MIT License
iristyle/chocolateypackages
EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/capp_lint.py
LintChecker.block_comment
python
def block_comment(self): commentOpenCount = self.line.count('/*') commentOpenCount -= self.line.count('*/') if commentOpenCount: if self.verbose: print u'%d: BLOCK COMMENT START' % self.lineNum else: return match = None while not ma...
Find the end of a block comment
https://github.com/iristyle/chocolateypackages/blob/8c9833710577de6db6e8b1db5d9196e19e19d117/EthanBrown.SublimeText2.WebPackages/tools/PackageCache/SublimeLinter/sublimelinter/modules/libs/capp_lint.py#L512-L531
from __future__ import with_statement from optparse import OptionParser from string import Template import cgi import cStringIO import os import os.path import re import sys import unittest EXIT_CODE_SHOW_HTML = 205 EXIT_CODE_SHOW_TOOLTIP = 206 def exit_show_html(html): sys.stdout.write(html.encode('utf-8')) sy...
MIT License
kytos/kytos
kytos/core/interface.py
Interface.get_next_available_tag
python
def get_next_available_tag(self): try: return self.available_tags.pop() except IndexError: return False
Get the next available tag from the interface. Return the next available tag if exists and remove from the available tags. If no tag is available return False.
https://github.com/kytos/kytos/blob/3b9731c08fe7550a27d159f4e2de71419c9445f1/kytos/core/interface.py#L167-L177
import json import logging from enum import IntEnum from pyof.v0x01.common.phy_port import Port as PortNo01 from pyof.v0x01.common.phy_port import PortFeatures as PortFeatures01 from pyof.v0x04.common.port import PortFeatures as PortFeatures04 from pyof.v0x04.common.port import PortNo as PortNo04 from kytos.core.common...
MIT License
scrapinghub/exporters
exporters/writers/filebase_base_writer.py
FilebaseBaseWriter.create_filebase_name
python
def create_filebase_name(self, group_info, extension='gz', file_name=None): dirname = self.filebase.formatted_dirname(groups=group_info) if not file_name: file_name = self.filebase.prefix_template + '.' + extension return dirname, file_name
Return tuple of resolved destination folder name and file name
https://github.com/scrapinghub/exporters/blob/b14f70530826bbbd6163d9e56e74345e762a9189/exporters/writers/filebase_base_writer.py#L145-L152
import datetime import hashlib import os import re import uuid import six from exporters.write_buffers.grouping import GroupingBufferFilesTracker from exporters.write_buffers.utils import get_filename from exporters.writers.base_writer import BaseWriter MD5_FILE_NAME = 'md5checksum.md5' def md5_for_file(f, block_size=2...
BSD 3-Clause New or Revised License
sorsnce/red-team
1. Information Gathering/recon-ng/recon/core/framework.py
Framework.insert_locations
python
def insert_locations(self, latitude=None, longitude=None, street_address=None, mute=False): data = dict( latitude = latitude, longitude = longitude, street_address = street_address ) rowcount = self.insert('locations', data.copy(), data.keys()) if not ...
Adds a location to the database and returns the affected row count.
https://github.com/sorsnce/red-team/blob/5cd1932ccafcd2c1b92b8642e9a64fa0d2e99324/1. Information Gathering/recon-ng/recon/core/framework.py#L430-L439
from contextlib import closing import cmd import codecs import inspect import json import os import random import re import requests import socket import sqlite3 import string import subprocess import sys import traceback class FrameworkException(Exception): pass class Colors(object): N = '\033[m' R = '\03...
MIT License
checkpointsw/karta
src/thumbs_up/utils/function.py
FeatureClassifier.train
python
def train(self, scoped_functions): clf = RandomForestClassifier(n_estimators=100) eas = [self._interest(x) for x in scoped_functions] + [self._interest(x) + self._inner_offset for x in scoped_functions] data_set = [self.extractSample(x) for x in eas] data_results = [self._tag(x) for x in...
Train the classifier on the scoped functions. Args: scoped_functions (list): list of all relevant (scoped) functions Note: Training must happen *after* the calibration phase
https://github.com/checkpointsw/karta/blob/b845928487b50a5b41acd532ae0399177a4356aa/src/thumbs_up/utils/function.py#L80-L97
from sklearn import metrics from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split import idc import ida_nalt import sark import numpy import struct import time CALIBRATION_LOWER_BOUND = 0.75 CALIBRATION_UPPER_BOUND = 0.96 CALIBRA...
MIT License
stypr/clubhouse-py
clubhouse/clubhouse.py
Clubhouse.get_club
python
def get_club(self, club_id, source_topic_id=None): data = { "club_id": int(club_id), "source_topic_id": source_topic_id, "query_id": None, "query_result_position": None, "slug": None, } req = requests.post(f"{self.API_URL}/get_club", he...
(Clubhouse, int, int) -> dict Get the information about the given club_id.
https://github.com/stypr/clubhouse-py/blob/a0aad17a42a4f391fc40eebc36e5535e629bdd9a/clubhouse/clubhouse.py#L532-L545
import uuid import random import secrets import functools import requests class Clubhouse: API_URL = "https://www.clubhouseapi.com/api" API_BUILD_ID_IOS = "434" API_BUILD_VERSION = "0.1.40" API_BUILD_ID_ANDROID = "3389" API_BUILD_VERSION_ANDROID= "1.0.1" API_UA_IOS = f"clubhouse/{API_BUILD_ID_IO...
MIT License
ngageoint/sarpy
sarpy/io/product/sidd2_elements/Measurement.py
PlaneProjectionType.__init__
python
def __init__(self, ReferencePoint=None, SampleSpacing=None, TimeCOAPoly=None, ProductPlane=None, **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] super(PlaneProjectionType, self).__ini...
Parameters ---------- ReferencePoint : ReferencePointType SampleSpacing : RowColDoubleType|numpy.ndarray|list|tuple TimeCOAPoly : Poly2DType|numpy.ndarray|list|tuple ProductPlane : ProductPlaneType kwargs
https://github.com/ngageoint/sarpy/blob/91405721a7e6ffe7c76dd7b143915fee4bee1e82/sarpy/io/product/sidd2_elements/Measurement.py#L132-L149
__classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union, List from sarpy.io.xml.base import Serializable, SerializableArray from sarpy.io.xml.descriptors import SerializableDescriptor, UnitVectorDescriptor, FloatDescriptor, StringEnumDescriptor, SerializableArrayDescriptor from ...
MIT License
elliot79313/tra-tracking-on-gae
gaesessions/__init__.py
Session.make_cookie_headers
python
def make_cookie_headers(self): if not self.sid: return [EXPIRE_COOKIE_FMT % k for k in self.cookie_keys] if self.cookie_data is None: return [] if self.is_ssl_only(): m = MAX_DATA_PER_COOKIE - 8 fmt = COOKIE_FMT_SECURE else: m...
Returns a list of cookie headers to send (if any).
https://github.com/elliot79313/tra-tracking-on-gae/blob/9f920a6e96b357bccba2d4328a3a7e2dcdebfc0a/gaesessions/__init__.py#L120-L149
from Cookie import CookieError, SimpleCookie from base64 import b64decode, b64encode import datetime import hashlib import hmac import logging import pickle import os import threading import time from google.appengine.api import memcache from google.appengine.ext import db COOKIE_NAME_PREFIX = "DgU" COOKIE_PATH = "/"...
MIT License
ziirish/burp-ui
burpui/tools/logging.py
Logger.init_logger
python
def init_logger(self, config): level = config.get("level", None) level = self.level if level is None else level level = convert_level(level) logfile = config.get("logfile") if self._handler is not None: self.removeHandler(self._handler) if logfile: ...
:param config: Logger configuration :type config: dict
https://github.com/ziirish/burp-ui/blob/668922753d97f0a71844d6985d9b8b2695fb2421/burpui/tools/logging.py#L84-L121
import logging def convert_level(verbose): if logging.getLevelName(verbose) != "Level %s" % verbose and ( not isinstance(verbose, int) or verbose > 0 ): return verbose if isinstance(verbose, bool): if verbose: verbose = logging.DEBUG else: verbose = lo...
BSD 3-Clause New or Revised License
galacticpuzzlehunt/gph-site
puzzles/views.py
hints
python
def hints(request): puzzle = request.context.puzzle team = request.context.team open_hints = [] if ONE_HINT_AT_A_TIME: open_hints = [hint for hint in team.asked_hints if hint.status == Hint.NO_RESPONSE] relevant_hints_remaining = (team.num_hints_remaining if puzzle.round.slug == INTR...
List or submit hint requests for a puzzle.
https://github.com/galacticpuzzlehunt/gph-site/blob/1f7b123106fb78f2ea5b05d5692126d708d4c7ff/puzzles/views.py#L770-L830
import csv import datetime import itertools import json import logging import os import requests from collections import defaultdict, OrderedDict, Counter from functools import wraps from urllib.parse import unquote from django.conf import settings from django.contrib import messages from django.contrib.auth import log...
MIT License
plangrid/flask-rebar
flask_rebar/authenticators/header_api_key.py
HeaderApiKeyAuthenticator.register_key
python
def register_key(self, key, app_name=DEFAULT_APP_NAME): self.keys[key] = app_name
Register a client application's shared secret. :param str app_name: Name for the application. Since an application can have multiple shared secrets, this does not need to be unique. :param str key: The shared secret.
https://github.com/plangrid/flask-rebar/blob/9aa839badb97e1048f261d1573a0dc1341b335eb/flask_rebar/authenticators/header_api_key.py#L51-L61
from flask import request, g from werkzeug.security import safe_str_cmp from flask_rebar import errors, messages from flask_rebar.authenticators.base import Authenticator def get_authenticated_app_name(): return g.authenticated_app_name class HeaderApiKeyAuthenticator(Authenticator): DEFAULT_APP_NAME = "default...
MIT License
bitmovin/bitmovin-api-sdk-python
bitmovin_api_sdk/models/akamai_net_storage_input.py
AkamaiNetStorageInput.__eq__
python
def __eq__(self, other): if not isinstance(other, AkamaiNetStorageInput): return False return self.__dict__ == other.__dict__
Returns true if both objects are equal
https://github.com/bitmovin/bitmovin-api-sdk-python/blob/79dd938804197151af7cbe5501c7ec1d97872c15/bitmovin_api_sdk/models/akamai_net_storage_input.py#L187-L192
from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model from bitmovin_api_sdk.models.input import Input import pprint import six class AkamaiNetStorageInput(Input): @poscheck_model def __init__(self, id_=None, na...
MIT License
yuxixie/rl-for-question-generation
discriminators/src/answerability/pretraining/fairseq/data/iterators.py
EpochBatchIterator.next_epoch_itr
python
def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False): if self._next_epoch_itr is not None: self._cur_epoch_itr = self._next_epoch_itr self._next_epoch_itr = None else: self.epoch += 1 self._cur_epoch_itr = self._get_iterator_for_epoch( ...
Return a new iterator over the dataset. Args: shuffle (bool, optional): shuffle batches before returning the iterator. Default: ``True`` fix_batches_to_gpus: ensure that batches are always allocated to the same shards across epochs. Requires ...
https://github.com/yuxixie/rl-for-question-generation/blob/188cd7b04528e4f192023a596a072b3245c62838/discriminators/src/answerability/pretraining/fairseq/data/iterators.py#L96-L114
import itertools import math import numpy as np import torch from . import data_utils class CountingIterator(object): def __init__(self, iterable): self.iterable = iterable self.count = 0 self.itr = iter(self) def __len__(self): return len(self.iterable) def __iter__(self): ...
MIT License
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.get_alternative_short_names
python
def get_alternative_short_names(cls, entry): names = [] query = "./n:protein/n:alternativeName/n:shortName" for name in entry.iterfind(query, namespaces=XN): names.append(models.AlternativeShortName(name=name.text)) return names
get list of models.AlternativeShortName objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.AlternativeShortName` objects
https://github.com/cebel/pyuniprot/blob/19cef498bf9cb01955da1673c00361f8e2d4e8f9/src/pyuniprot/manager/database.py#L440-L452
import configparser import gzip import logging import os import re import shutil import sys import time import lxml from configparser import RawConfigParser from datetime import datetime from typing import Iterable import numpy as np import sqlalchemy from sqlalchemy.engine import reflection from sqlalchemy.orm import ...
Apache License 2.0
intel/openfl
openfl/protocols/director_pb2_grpc.py
FederationDirectorServicer.CollaboratorHealthCheck
python
def CollaboratorHealthCheck(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
https://github.com/intel/openfl/blob/4bda3850b6bce7c904a5ac3ed56115bec00be2e0/openfl/protocols/director_pb2_grpc.py#L123-L127
import grpc from . import director_pb2 as director__pb2 class FederationDirectorStub(object): def __init__(self, channel): self.AcknowledgeShard = channel.unary_unary( '/FederationDirector/AcknowledgeShard', request_serializer=director__pb2.ShardInfo.SerializeToString, ...
Apache License 2.0
jgurtowski/ectools
nucio.py
getNucmerAlignmentIterator
python
def getNucmerAlignmentIterator(fh): return lineRecordIterator(fh, NucRecord, NucRecordTypes)
Get nucmer alignments from show-coords output (Deprecated legacy)
https://github.com/jgurtowski/ectools/blob/031eb0300c82392915d8393a5fedb4d3452b15bf/nucio.py#L68-L72
import sys from collections import namedtuple from itertools import imap, izip, ifilter from misc import trueFunc NucRecord = namedtuple('NucRecord', ["sstart","send","b3","qstart","qend", "b6", "salen","qalen","b9","pctid", "b11","slen","qlen","b14...
BSD 3-Clause New or Revised License
awused/cynaoko
naoko/lib/database.py
NaokoDB.insertVideo
python
def insertVideo(self, site, vid, title, dur, nick): self.logger.debug("Inserting %s into videos", (site, vid, int(dur * 1000), title, 0)) self.logger.debug("Inserting %s into video_stats", (site, vid, nick)) self.executeDML("INSERT OR IGNORE INTO videos VALUES(?, ?, ?, ?, ?)", (site, vid, int(du...
Inserts a video into the database. The video is assumed to be valid so it also removes the invalid flag from the video. dur is supplied in seconds as a float but stored in milliseconds as an integer. nick is the username of the user who added it, with unregistered users using an empty string.
https://github.com/awused/cynaoko/blob/23e3f287814535e80268a0fa8dfb6d415bb4a9a2/naoko/lib/database.py#L465-L480
import sqlite3 import logging import time try: from settings import LOG_LEVEL except: print "Defaulting to LOG_LEVEL debug [%s]" % (__name__) LOG_LEVEL = logging.DEBUG ProgrammingError = sqlite3.ProgrammingError DatabaseError = sqlite3.DatabaseError def dbopen(fn): def dbopen_func(self, *args, **kwargs)...
BSD 2-Clause Simplified License
kriaga/health-checker
HealthChecker/venv/Lib/site-packages/nltk/app/wordnet_app.py
page_from_reference
python
def page_from_reference(href): word = href.word pos_forms = defaultdict(list) words = word.split(',') words = [w for w in [w.strip().lower().replace(' ', '_') for w in words] if w != ""] if len(words) == 0: return "", "Please specify a word to search for...
Returns a tuple of the HTML page built and the new current word :param href: The hypertext reference to be solved :type href: str :return: A tuple (page,word), where page is the new current HTML page to be sent to the browser and word is the new current word :rtype: A tuple (s...
https://github.com/kriaga/health-checker/blob/3d9ce933f131bcbb897103b0f509cc45393cae4a/HealthChecker/venv/Lib/site-packages/nltk/app/wordnet_app.py#L723-L764
from __future__ import print_function from sys import path import os import sys from sys import argv from collections import defaultdict import webbrowser import datetime import re import threading import time import getopt import base64 import pickle import copy from six.moves.urllib.parse import unquote_plus from nlt...
MIT License
centerforthebuiltenvironment/clima
my_project/tab_wind/app_wind.py
sliders
python
def sliders(): return html.Div( className="container-col justify-center", id="slider-container", children=[ html.Div( className="container-row each-slider", children=[ html.P("Month Range"), dcc.RangeSlider( ...
Returns 2 sliders for the hour
https://github.com/centerforthebuiltenvironment/clima/blob/b3bec2839aed4a3766dd31d9369817073ac465cf/my_project/tab_wind/app_wind.py#L11-L50
from dash import dcc, html from my_project.global_scheme import month_lst, container_row_center_full from dash.dependencies import Input, Output, State from my_project.template_graphs import heatmap, wind_rose from my_project.utils import title_with_tooltip, generate_chart_name from my_project.utils import code_timer f...
MIT License
mgraffg/evodag
EvoDAG/base.py
EvoDAG.generations
python
def generations(self): return self._generations
Number of generations
https://github.com/mgraffg/evodag/blob/d553444d6505a3885760250955f47383c064f6d8/EvoDAG/base.py#L182-L184
import numpy as np import logging from SparseArray import SparseArray from .node import Variable from .node import Add, Mul, Div, Fabs, Exp, Sqrt, Sin, Cos, Log1p from .node import Sq, Min, Max from .node import Atan2, Hypot, Acos, Asin, Atan, Tan, Cosh, Sinh from .node import Tanh, Acosh, Asinh, Atanh, Expm1, Log, Log...
Apache License 2.0
apiad/sublime-browser-integration
selenium/webdriver/phantomjs/service.py
Service.__init__
python
def __init__(self, executable_path, port=0, service_args=None, log_path=None): self.port = port self.path = executable_path self.service_args= service_args if self.port == 0: self.port = utils.free_port() if self.service_args is None: self.service_args = [...
Creates a new instance of the Service :Args: - executable_path : Path to PhantomJS binary - port : Port the service is running on - service_args : A List of other command line options to pass to PhantomJS - log_path: Path for PhantomJS service to log to
https://github.com/apiad/sublime-browser-integration/blob/3914a8cd80ceabe58593a4123dd9e9493c5d5ebd/selenium/webdriver/phantomjs/service.py#L28-L50
import subprocess import time import signal from selenium.common.exceptions import WebDriverException from selenium.webdriver.common import utils class Service(object):
MIT License
dcoles/pycurl-requests
pycurl_requests/_pycurl.py
debug_function
python
def debug_function(infotype: int, message: bytes): if infotype > CURLINFO_HEADER_OUT: return message = message.decode('utf-8', 'replace') if infotype == CURLINFO_TEXT: LOGGER_TEXT.debug(message.rstrip()) elif infotype == CURLINFO_HEADER_IN: for line in message.splitlines(): ...
cURL `DEBUGFUNCTION` that writes to logger
https://github.com/dcoles/pycurl-requests/blob/4365c7797d7897a655e9d7f91081dc7e303d230a/pycurl_requests/_pycurl.py#L195-L210
import datetime import http.client import io from io import BytesIO import logging import pycurl from pycurl_requests import exceptions from pycurl_requests import models from pycurl_requests import structures try: from urllib3.util.timeout import Timeout except ImportError: Timeout = None CURLINFO_TEXT = 0 CUR...
MIT License
mikeiacovacci/axiom-framework
lib/classes.py
AxiomTool.resolve_command
python
def resolve_command(self, number): if number >= 0 and number in range(self.combined_list.__len__()): command_name = self.combined_list[number] return self.resolve_command_name(command_name) else: return None, int(-1)
SUMMARY: determines the object's type (command or action) and finds its ID value INPUT: command/action ID number integer OUTPUT: two-item tuple containing 1) "command", "action", or None and 2) ID value, -1 if unresolved
https://github.com/mikeiacovacci/axiom-framework/blob/2edc8bb1a123eb3c67897b0742050ee6956058bf/lib/classes.py#L953-L962
import lib.config as config from lib.config import print_error from os import devnull, path from pexpect import exceptions, pty_spawn from prompt_toolkit import prompt, PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.history import FileHistory from queue import Queue fro...
Apache License 2.0
humancompatibleai/rlsp
src/envs/env.py
Env.step
python
def step(self, action, r_vec=None): self.s = self.state_step(action) self.timestep+=1 obs = self.s_to_f(self.s) reward = 0 if r_vec is None else np.array(obs.T @ r_vec) done = False info = defaultdict(lambda : '') return np.array(obs, dtype='float32'), reward, np....
given an action, takes a step from self.s, updates self.s and returns: - the observation (features of the next state) - the associated reward - done, the indicator of completed episode - info
https://github.com/humancompatibleai/rlsp/blob/cacae643752a02b2be092870df2ce3de8d674144/src/envs/env.py#L68-L83
import numpy as np from collections import defaultdict from copy import deepcopy from scipy.sparse import lil_matrix class Env(object): def __init__(self): raise ValueError('Cannot instantiate abstract class Env') def is_deterministic(self): return False def get_initial_state_distribution(se...
MIT License
instadeepai/mava
mava/wrappers/pettingzoo.py
PettingZooParallelEnvWrapper.extra_spec
python
def extra_spec(self) -> Dict[str, specs.BoundedArray]: return {}
Extra data spec. Returns: Dict[str, specs.BoundedArray]: spec for extra data.
https://github.com/instadeepai/mava/blob/3159ed45bce4936c8298085cad1bdefbac50160f/mava/wrappers/pettingzoo.py#L549-L555
import copy from typing import Any, Dict, Iterator, List, Optional, Union import dm_env import gym import numpy as np from acme import specs from acme.wrappers.gym_wrapper import _convert_to_spec from pettingzoo.utils.env import AECEnv, ParallelEnv from supersuit import black_death_v1 from mava import types from mava.u...
Apache License 2.0
bbn-q/auspex
src/auspex/stream.py
DataStreamDescriptor.axis_names
python
def axis_names(self, with_metadata=False): vals = [] for a in self.axes: if a.unstructured: for p in a.parameter: vals.append(p.name) else: vals.append(a.name) if with_metadata and a.metadata is not None: ...
Returns all axis names included those from unstructured axes
https://github.com/bbn-q/auspex/blob/e9763e1907546ad49210415a6b8c2f6d9999f31a/src/auspex/stream.py#L392-L406
import os import sys if sys.platform == 'win32' or 'NOFORKING' in os.environ: import threading as mp from queue import Queue else: import multiprocessing as mp from multiprocessing import Queue from multiprocessing import Value, RawValue, RawArray import ctypes import logging import numbers import itert...
Apache License 2.0
lsgos/uncertainty-adversarial-paper
ROC_curves_cats.py
create_adv_examples
python
def create_adv_examples(model, input_t, x_to_adv, attack_dict): if attack_dict['method'] == 'fgm': attack = attacks.FastGradientMethod(model, sess=K.get_session(), back='tf') elif attack_dict['method'] == 'bim': attack = attacks.BasicIterativeMethod(model, sess=K.get_session(), back='tf') el...
This fn may seem bizarre and pointless, but the point of it is to enable the entire attack to be specified as a dict from the command line without editing this script, which is convenient for storing the settings used for an attack
https://github.com/lsgos/uncertainty-adversarial-paper/blob/7f39d1ebf15061bd9b6c33f9c5fe4afb5bce42cf/ROC_curves_cats.py#L70-L87
import argparse import h5py import json import numpy as np from keras import backend as K from sklearn.metrics import roc_auc_score, roc_curve, precision_recall_curve, average_precision_score from keras.utils import to_categorical import src.utilities as U from cleverhans import attacks from cleverhans.model import Cal...
MIT License
sulab/wikidataintegrator
wikidataintegrator/wdi_fastrun.py
FastRunContainer.clear
python
def clear(self): self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set) self.rev_lookup_ci = defaultdict(set)
convinience function to empty this fastrun container
https://github.com/sulab/wikidataintegrator/blob/5feff88d7e97ffad1713a086202efa93ebe49516/wikidataintegrator/wdi_fastrun.py#L585-L592
import copy from collections import defaultdict from functools import lru_cache from itertools import chain from wikidataintegrator.wdi_config import config example_Q14911732 = {'P1057': {'Q14911732-23F268EB-2848-4A82-A248-CF4DF6B256BC': {'v': 'Q847102', ...
MIT License
napari/napari
napari/_qt/widgets/qt_highlight_preview.py
QtTriangle.maximum
python
def maximum(self): return self._max_value
Return maximum value. Returns ------- int Maximum value of triangle widget.
https://github.com/napari/napari/blob/c4c987c880fe125da608edf427767eafe7f2b3f4/napari/_qt/widgets/qt_highlight_preview.py#L239-L247
import numpy as np from qtpy.QtCore import QSize, Qt, Signal from qtpy.QtGui import QColor, QIntValidator, QPainter, QPainterPath, QPen from qtpy.QtWidgets import ( QFrame, QHBoxLayout, QLabel, QLineEdit, QSlider, QVBoxLayout, QWidget, ) from ...utils.translations import translator trans = t...
BSD 3-Clause New or Revised License
aoldoni/tetre
lib/tetre/graph_processing_children.py
Obj.remove_tags
python
def remove_tags(self, root, node_set, spacy_tree): is_applied = False node_set = set(node_set) - self.tags_to_be_removed for child in spacy_tree.children: if child.dep_ in self.tags_to_be_removed: is_applied = True child.no_follow = True return...
1) Consider the following sentence: "2 Related work Learning to rank has been a promising research area which continuously improves web search relevance (Burges et al." In this case, the dependency parser puts not the action the improves something as a parent of the word ...
https://github.com/aoldoni/tetre/blob/a8b07aa47a9adf7dce46dff96e20be63a761e9f7/lib/tetre/graph_processing_children.py#L160-L204
from tetre.rule_applier import * from tree_utils import find_in_spacynode class Children(RuleApplier): def __init__(self): RuleApplier.__init__(self) self.tags_to_be_removed = {'det', ' ', ''} def bring_grandchild_prep_or_relcl_up_as_child(self, root, node_set, spacy_tree): bring_up = [ ...
MIT License
mukund109/word-mesh
wordmesh/utils.py
PlotlyVisualizer.__init__
python
def __init__(self, words, fontsizes_norm, height, width, filename='temp-plot.html', title=None, textcolors='white', hovertext=None, axis_visible=False, bg_color='black', title_fontcolor='white', title_fontsize='auto', title_font_family='Courier New,...
Parameters ----------
https://github.com/mukund109/word-mesh/blob/2be945d988d661bd51afa6bd646f944c9c5d202a/wordmesh/utils.py#L19-L44
import numpy as np import plotly.offline as py import plotly.graph_objs as go PLOTLY_FONTSIZE_BBW = 0.6 PLOTLY_FONTSIZE_BBH = 0.972+0.088 class PlotlyVisualizer():
MIT License
datadotworld/data.world-py
datadotworld/client/api.py
RestApiClient.get_user_data
python
def get_user_data(self): try: return self._user_api.get_user_data().to_dict() except _swagger.rest.ApiException as e: raise RestApiError(cause=e)
Retrieve data for authenticated user :returns: User data, with all attributes :rtype: dict :raises RestApiException: If a server error occurs Examples -------- >>> import datadotworld as dw >>> api_client = dw.api_client() >>> user_data = api_client.get_...
https://github.com/datadotworld/data.world-py/blob/7e5f474b655f4f0c88cc6862353e4d52c0e0bb31/datadotworld/client/api.py#L501-L519
from __future__ import absolute_import, division import functools import glob import json import os import shutil import uuid import zipfile from os import path import requests import six from datadotworld.client import _swagger from datadotworld.client.content_negotiating_api_client import ( ContentNegotiatingApiC...
Apache License 2.0
engineering-course/lip_jppnet
utils/utils.py
save
python
def save(saver, sess, logdir, step): if not os.path.exists(logdir): os.makedirs(logdir) model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The ...
Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step.
https://github.com/engineering-course/lip_jppnet/blob/1899e8d18656312b6f9cea1c908205dcdf6c95e5/utils/utils.py#L84-L100
from PIL import Image import numpy as np import tensorflow as tf import os import scipy.misc from scipy.stats import multivariate_normal import matplotlib.pyplot as plt n_classes = 20 label_colours = [(0,0,0) ,(128,0,0),(255,0,0),(0,85,0),(170,0,51),(255,85,0) ,(0,0,85),(0,119,221),(85,8...
MIT License
rajammanabrolu/worldgeneration
evennia-engine/evennia/evennia/contrib/turnbattle/tb_magic.py
is_in_combat
python
def is_in_combat(character): return bool(character.db.combat_turnhandler)
Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat
https://github.com/rajammanabrolu/worldgeneration/blob/5e97df013399e1a401d0a7ec184c4b9eb3100edd/evennia-engine/evennia/evennia/contrib/turnbattle/tb_magic.py#L265-L275
from random import randint from evennia import DefaultCharacter, Command, default_cmds, DefaultScript, create_object from evennia.commands.default.muxcommand import MuxCommand from evennia.commands.default.help import CmdHelp TURN_TIMEOUT = 30 ACTIONS_PER_TURN = 1 def roll_init(character): return randint(1, 100...
MIT License
hipchat/curler
curler/twisted_gears/client.py
GearmanWorker.doJob
python
def doJob(self): return self.getJob().addCallback(self._finishJob)
Do a single job
https://github.com/hipchat/curler/blob/b22bf79ecc4c1985038e0ba183ca7125be4b8ac0/curler/twisted_gears/client.py#L164-L166
import sys import struct from collections import deque from twisted.internet import defer from twisted.protocols import stateful from twisted.python import log from constants import * __all__ = ['GearmanProtocol', 'GearmanWorker', 'GearmanClient'] class GearmanProtocol(stateful.StatefulProtocol): unsolicited = [ WO...
MIT License
xanaduai/strawberryfields
strawberryfields/backends/tfbackend/ops.py
beamsplitter
python
def beamsplitter( theta, phi, mode1, mode2, in_modes, cutoff, pure=True, batched=False, dtype=tf.complex64 ): theta = tf.cast(theta, dtype) phi = tf.cast(phi, dtype) matrix = beamsplitter_matrix(theta, phi, cutoff, batched, dtype) output = two_mode_gate(matrix, mode1, mode2, in_modes, pure, batched)...
returns beamsplitter unitary matrix on specified input modes
https://github.com/xanaduai/strawberryfields/blob/c1eed81a93419cb9c28a6ca205925691063722ce/strawberryfields/backends/tfbackend/ops.py#L825-L833
from string import ascii_lowercase as indices import tensorflow as tf import numpy as np from scipy.special import factorial from thewalrus.fock_gradients import displacement as displacement_tw from thewalrus.fock_gradients import grad_displacement as grad_displacement_tw from thewalrus.fock_gradients import squeezing ...
Apache License 2.0
pyglet/pyglet
pyglet/media/drivers/xaudio2/interface.py
XA2SourceVoice.cone_outside_volume
python
def cone_outside_volume(self): if self.is_emitter: return self._emitter.pCone.contents.OuterVolume else: return 0
The volume scaler of the sound beyond the outer cone.
https://github.com/pyglet/pyglet/blob/b9a63ea179735c8f252ac31d51751bdf8a741c9d/pyglet/media/drivers/xaudio2/interface.py#L529-L534
import weakref from collections import namedtuple, defaultdict import pyglet from pyglet.libs.win32.types import * from pyglet.util import debug_print from pyglet.media.devices import get_audio_device_manager from . import lib_xaudio2 as lib _debug = debug_print('debug_media') class XAudio2Driver: allow_3d = True ...
BSD 3-Clause New or Revised License
sassoftware/python-pipefitter
pipefitter/estimator/regression.py
LogisticRegression.fit
python
def fit(self, table, *args, **kwargs): params = self.get_combined_params(*args, **kwargs) return self._get_super(table).fit(table, **params)
Fit function for logistic regression Parameters ---------- *args : dicts or two-element tuples or consecutive key/value pairs, optional The following types are allowed: * Dictionaries contain key/value pairs of parameters. * Two-element tuples must ...
https://github.com/sassoftware/python-pipefitter/blob/d3199b72dfd66729753da50e9e15eb303361ee8a/pipefitter/estimator/regression.py#L96-L125
from __future__ import print_function, division, absolute_import, unicode_literals import functools from ..base import BaseEstimator, BaseModel from ..utils.params import (param_def, check_int, check_string, check_boolean, check_float, check_variable, check_variable_list) class LogisticRegre...
Apache License 2.0
pybricks/pybricksdev
pybricksdev/ble/lwp3/messages.py
ErrorMessage.code
python
def code(self) -> ErrorCode: return ErrorCode(self._data[4])
Gets an error code describing the error.
https://github.com/pybricks/pybricksdev/blob/3a89ec32d0abc484b898ca4fd8b4b3079112aa70/pybricksdev/ble/lwp3/messages.py#L593-L595
import abc import struct from enum import IntEnum from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Type, Union, overload from .bytecodes import ( Feedback, MAX_NAME_SIZE, AlertKind, AlertOperation, AlertStatus, BatteryKind, BluetoothAddress, DataFormat, EndInfo, E...
MIT License
opennetworkingfoundation/tapi
RI/flask_server/tapi_server/models/tapi_oam_oam_service.py
TapiOamOamService.__init__
python
def __init__(self, operational_state=None, lifecycle_state=None, administrative_state=None, name=None, uuid=None, layer_protocol_name=None, meg_level=None, direction=None, oam_profile=None, end_point=None, meg=None): self.openapi_types = { 'operational_state': TapiCommonOperationalState, ...
TapiOamOamService - a model defined in OpenAPI :param operational_state: The operational_state of this TapiOamOamService. # noqa: E501 :type operational_state: TapiCommonOperationalState :param lifecycle_state: The lifecycle_state of this TapiOamOamService. # noqa: E501 :type lifecycl...
https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_oam_oam_service.py#L30-L94
from __future__ import absolute_import from datetime import date, datetime from typing import List, Dict from tapi_server.models.base_model_ import Model from tapi_server.models.tapi_common_admin_state_pac import TapiCommonAdminStatePac from tapi_server.models.tapi_common_administrative_state import TapiCommonAdm...
Apache License 2.0
liberai/nspm
gsoc/zheyuan/pipeline/paraphrase_questions.py
paraphrase_questions
python
def paraphrase_questions(tokenizer, device, model, sentence): sentence = sentence.replace("<A>", "XYZ") text = "paraphrase: " + sentence + " </s>" max_len = 256 encoding = tokenizer.encode_plus(text, pad_to_max_length=True, return_tensors="pt") input_ids, attention_masks = encoding["input_ids"].to(d...
@param tokenizer: Tokenizer is in charge of preparing the inputs for a model @param device: Device the model will be run on @param model: The pre-trained model @param sentence: The sentence need to be templates @return: final_outputs: the candidates of templates questions
https://github.com/liberai/nspm/blob/cc352dbbda6751e8cf19769c9440c03e31687829/gsoc/zheyuan/pipeline/paraphrase_questions.py#L61-L101
import tensorflow_hub as hub import tensorflow as tf import zipfile import requests, zipfile, io import os import re import argparse import torch from transformers import T5ForConditionalGeneration,T5Tokenizer from constant import Constant from textual_similarity import similarities, minDistance, words_distance, tags_d...
MIT License
openstack/keystone
keystone/federation/backends/base.py
FederationDriverBase.list_mappings
python
def list_mappings(self): raise exception.NotImplemented()
List all mappings. :returns: list of mapping refs :rtype: list of dicts
https://github.com/openstack/keystone/blob/1e7ecca881a51144d61ae8026e1a77d6669997e2/keystone/federation/backends/base.py#L218-L225
import abc from keystone import exception class FederationDriverBase(object, metaclass=abc.ABCMeta): @abc.abstractmethod def create_idp(self, idp_id, idp): raise exception.NotImplemented() @abc.abstractmethod def delete_idp(self, idp_id): raise exception.NotImplemented() @abc.abs...
Apache License 2.0