query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Convert the given byte value to GB. | def to_gb(byte_value):
return "{:.2f}".format(int(byte_value)/1073741824) | [
"def convert_byte_to_gb(attribute_value):\r\n try:\r\n attribute_value = int(attribute_value) / 1024\r\n new_attribute_value = str(attribute_value) + ' GB'\r\n return new_attribute_value\r\n except:\r\n traceback.print_exc()\r\n return ''",
"def convert_bytes_gb(bytes_: in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NODE sends a message containing an invalid publickey to OTHER. OTHER should drop it | def test_invalid_public_key(self):
node, other = self.create_nodes(2)
other.send_identity(node)
message = node.create_bin_key_text('Should drop')
packet = node.encode_message(message)
# replace the valid public-key with an invalid one
public_key = node.my_member.public_... | [
"def test_send_find_value_unknown(port, version, public_key, private_key):\n item = {\n 'uuid': str(uuid.uuid4()),\n 'recipient': REMOTE_NODE_PUBLIC_KEY,\n 'sender': public_key,\n 'reply_port': 1908,\n 'version': version,\n 'key': sha512('an un-findable key'.encode('utf-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NODE sends a message containing an invalid signature to OTHER. OTHER should drop it | def test_invalid_signature(self):
node, other = self.create_nodes(2)
other.send_identity(node)
message = node.create_full_sync_text('Should drop')
packet = node.encode_message(message)
# replace the valid signature with an invalid one
invalid_packet = packet[:-node.my_m... | [
"def test_submit_invalid_signed_message(self):\n r = self._submit_message('Not a PGP-signed message.')\n self.assertIn(err_messages['not_signed'], r.data)\n\n # Submit a signed message that's been modified.\n f = open(os.path.join(self.files, 'invalid.sig'))\n invalid_msg = f.read... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the suffixes that match the given principal | def _get_suffixes_for_principal(self, config, value, principal):
suffixes_principals = [(suffix, self._format_principal(value, suffix))
for suffix in config.keys()]
return [s for s, p in suffixes_principals if p == principal] | [
"def suffixes(self) -> Dict[str, Union[Tuple[str, ...], Dict[str, Tuple[str, ...]]]]:\n return self._normalize(\"suffixes\")",
"def suffixes(self) -> List[str]:\n\t\treturn self.path.suffixes",
"def suffixes (self, suffix = ''):\n results = []\n\n if self.is_word and suffix != \"\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the id and the values of the LocalRolesField objects on the current context | def field_and_values_list(self):
fields = get_localrole_fields(self.fti)
field_and_values = []
for fieldname, _field in fields:
try:
if not base_hasattr(self.context, fieldname):
continue
except RequiredMissing:
continue... | [
"def get_role_id(self):\n lis1 = []\n for roleids in self.mysession.query(Role.roleID.label('roleID')).all():\n lis1.append(roleids.roleID)\n return lis1",
"def get_local_roles(obj, principal):\n ctype = ContentType.objects.get_for_model(obj)\n\n if isinstance(principal, User... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the config from FTI for a given fieldname | def get_config(self, fieldname):
if not base_hasattr(self.fti, 'localroles'):
return {}
return self.fti.localroles.get(fieldname, {}) | [
"def get_config_fields(self):\n raise NotImplementedError",
"def _get_field_by_name(model, field):\n field_dict = {x.name: x for x in model._meta.get_fields()} # noqa\n return field_dict[field]",
"def get_value(self, config_field):\n raise NotImplementedError",
"def read_attr(self, fieldn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all property templates in this dataset. | def property_templates(self) -> PropertyTemplateCollection:
return PropertyTemplateCollection(self.project_id, self.uid, self.session) | [
"def file_properties_templates_list_for_team(self):\n arg = None\n r = self.request(\n file_properties.templates_list_for_team,\n 'file_properties',\n arg,\n None,\n )\n return r",
"def _get_instance_templates(self):\r\n return [(insta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all condition templates in this dataset. | def condition_templates(self) -> ConditionTemplateCollection:
return ConditionTemplateCollection(self.project_id, self.uid, self.session) | [
"def list_question_templates(self):\n return self.query(\"\"\"{\n allQuestionTemplates {\n edges {\n node {\n id\n scId\n questionType\n text\n expec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all parameter templates in this dataset. | def parameter_templates(self) -> ParameterTemplateCollection:
return ParameterTemplateCollection(self.project_id, self.uid, self.session) | [
"def parameter_template(self) -> Template:\n return self.__parameter_template",
"def _get_instance_templates(self):\r\n return [(instance.name, instance.t)\r\n for instance in self.get_instances()]",
"def get_all_resource(self):\n query = APIData.query()\n query = quer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all material templates in this dataset. | def material_templates(self) -> MaterialTemplateCollection:
return MaterialTemplateCollection(self.project_id, self.uid, self.session) | [
"def _all_templates(self):\n for startmodel in self._all_starting_models():\n for template in startmodel.templates:\n yield template",
"def templates(self):\n if self._templates is None:\n templates = {}\n dom = self._get_xml(self.TEMPLATES_PATH)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all measurement templates in this dataset. | def measurement_templates(self) -> MeasurementTemplateCollection:
return MeasurementTemplateCollection(self.project_id, self.uid, self.session) | [
"def all_templates(self):\n if self._all_templates is None:\n all_templates = {}\n dom = self._get_xml(self.ALL_TEMPLATES_PATH)\n for e in dom.getElementsByTagName('template'):\n user = e.getAttribute('userName')\n name = e.getAttribute('name')\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all process templates in this dataset. | def process_templates(self) -> ProcessTemplateCollection:
return ProcessTemplateCollection(self.project_id, self.uid, self.session) | [
"def list_by_template(self,\n uid: Union[UUID, str, LinkByUID, GEMDProcessTemplate]\n ) -> Iterator[ProcessSpec]:\n return self._get_relation('process-templates', uid=uid)",
"def iter_templates(self):\n for page in self.iter_templates_pages():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all process runs in this dataset. | def process_runs(self) -> ProcessRunCollection:
return ProcessRunCollection(self.project_id, self.uid, self.session) | [
"def processes(self):\n r = requests.get(self.uri+'processes')\n r.raise_for_status()\n return r.json()",
"def processes(self):\n ret = self._get_attr(\"processes\")\n return [IGuestProcess(a) for a in ret]",
"async def get_info_all_process():\n return supervisord_daemo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all measurement runs in this dataset. | def measurement_runs(self) -> MeasurementRunCollection:
return MeasurementRunCollection(self.project_id, self.uid, self.session) | [
"def get_all_measurements():\n measurements = Measurement.objects.all()\n return measurements",
"def list_runs(self):\n res = self.api_client.ListRuns()\n return res.response().result",
"def load_all_runs(self) -> Sequence[RunResult]:",
"def runs(self):\n\t\treturn copy.copy(self._runs)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all material runs in this dataset. | def material_runs(self) -> MaterialRunCollection:
return MaterialRunCollection(self.project_id, self.uid, self.session) | [
"def get_materials():\n\n return Material.query.all()",
"def get_all_resource(self):\n query = APIData.query()\n query = query.filter(APIData.indexed_data == \"TYPE->RESOURCE\")\n query = query.filter(APIData.indexed_data == \"DATASET_ID->\" + str(self.key.id()))\n\n resources = que... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all ingredient runs in this dataset. | def ingredient_runs(self) -> IngredientRunCollection:
return IngredientRunCollection(self.project_id, self.uid, self.session) | [
"def get_recipe_ingredients():\n\n \"\"\"IN USE\"\"\"\n\n return RecipeIngredient.query.all()",
"def get(self):\n auth_header = request.headers.get('authorization')\n data = get_all_ingredient.parse_args(request)\n return MealBusiness.get_all_ingredient(auth_token=auth_header,data=data)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all process specs in this dataset. | def process_specs(self) -> ProcessSpecCollection:
return ProcessSpecCollection(self.project_id, self.uid, self.session) | [
"def processes(self):\n r = requests.get(self.uri+'processes')\n r.raise_for_status()\n return r.json()",
"def processes(self):\n ret = self._get_attr(\"processes\")\n return [IGuestProcess(a) for a in ret]",
"def list_user_defined_processes(self) -> List[dict]:\n data ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all measurement specs in this dataset. | def measurement_specs(self) -> MeasurementSpecCollection:
return MeasurementSpecCollection(self.project_id, self.uid, self.session) | [
"def get_all_measurements():\n measurements = Measurement.objects.all()\n return measurements",
"def measurements(self):\n return dict([(x['name'], x) for x in self.meta['measurements']])",
"def collect_data_spec(self):\n pass",
"def get(self):\n measurements = {}\n for monit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all material specs in this dataset. | def material_specs(self) -> MaterialSpecCollection:
return MaterialSpecCollection(self.project_id, self.uid, self.session) | [
"def get_materials():\n\n return Material.query.all()",
"def _get_materials(self) -> \"adsk::core::Ptr< adsk::core::Materials >\" :\n return _core.MaterialLibrary__get_materials(self)",
"def create_materials(self):\n Mat = namedtuple('Mat', ['name', 'is_waste'])\n Mat.__new__.__defaults_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a resource representing all ingredient specs in this dataset. | def ingredient_specs(self) -> IngredientSpecCollection:
return IngredientSpecCollection(self.project_id, self.uid, self.session) | [
"def get_recipe_ingredients():\n\n \"\"\"IN USE\"\"\"\n\n return RecipeIngredient.query.all()",
"def get(self):\n auth_header = request.headers.get('authorization')\n data = get_all_ingredient.parse_args(request)\n return MealBusiness.get_all_ingredient(auth_token=auth_header,data=data)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a data model object to the appropriate collection. | def register(self, model: DataConcepts, *, dry_run=False) -> DataConcepts:
return self.gemd._collection_for(model).register(model, dry_run=dry_run) | [
"def register_data(self):\n raise NotImplementedError",
"def register_model(name: str) -> None:\n # Add the model to the list of valid models.\n VALID_MODELS.append(name)",
"def register(cls_list):\n global REGISTERED_MODELS\n REGISTERED_MODELS = cls_list",
"def register(self, model: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update a data model object using the appropriate collection. | def update(self, model: DataConcepts) -> DataConcepts:
return self.gemd._collection_for(model).update(model) | [
"def update(self, collection, model, id):\n self._validate_collection(collection)\n return {\n \"command\": \"update\",\n \"kwargs\": {\n \"type\": collection,\n \"model\": model,\n \"id\": id,\n }\n }",
"def update... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a GEMD resource from the appropriate collection. | def delete(self, uid: Union[UUID, str, LinkByUID, DataConcepts], *, dry_run=False):
if isinstance(uid, DataConcepts):
collection = self.gemd._collection_for(uid)
else:
collection = self.gemd
return collection.delete(uid, dry_run=dry_run) | [
"def delete_collection(collection):\r\n collection.delete_many({})",
"def delete(self, entity):",
"def delete(self):\n if self.data:\n self.data.delete()\n super(Resource, self).delete()",
"def delete(self):\n failed, model, entity = self._get_model_and_entity(True, True)\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new dataset in the collection, or update an existing one. If the Dataset has an ID present, then we update the existing resource, else we create a new one. This differs from super().register() in that None fields are scrubbed, and the json response is not assumed to come in a dictionary with a single entry 'da... | def register(self, model: Dataset) -> Dataset:
path = self._get_path()
dumped_dataset = model.dump()
dumped_dataset["deleted"] = None
# Only use the idempotent put approach if a) a unique name is provided, and b)
# the session is configured to use it (default to False for backwa... | [
"def update(self, dataset_id, name=None, description=None):\n\n dataset = models.Dataset(\n name=name,\n description=description\n )\n\n repository = self.build_repository(repositories.UpdateDataset)\n return repository.update(dataset_id, dataset)",
"def modify_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List datasets using pagination. Leaving page and per_page as default values will yield all elements in the collection, paginating over all available pages. | def list(self, *, per_page: int = 1000) -> Iterator[Dataset]:
return super().list(per_page=per_page) | [
"async def paginate(\n self, url: str, page_sz: Optional[int] = None, **params\n ) -> List[Dict]:\n\n # always make a copy of the Caller provided parameters so we\n # do not trample any of their settings.\n\n _params = params.copy()\n\n # fetch the first page of data, which wil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a Dataset with the given unique name. | def get_by_unique_name(self, unique_name: str) -> Dataset:
if unique_name is None:
raise ValueError("You must supply a unique_name")
path = self._get_path(query_terms={"unique_name": unique_name})
data = self.session.get_resource(path)
if len(data) == 1:
return s... | [
"def get_dataset(self, name):\n return Dataset(self.get_dataset_path(name))",
"def dataset(self, name):\n return Dataset(name, client=self)",
"def get_saved_dataset(self, name: str) -> SavedDataset:\n if not flags_helper.is_test():\n warnings.warn(\n \"Retrieving d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sample program demonstrating what this system can do adds 1 store adds 2 customers adds 8 videos the customers rent/return videos | def main():
store1 = Store(address1)
store1.add_customer(Customer(first_name1, last_name1, phone_number1, dob, email))
store1.add_customer(Customer(first_name2, last_name2, phone_number2, dob, email))
video1 = store1.add_video(Video("300"))
video2 = store1.add_video(Video("Spaceballs"))
video3 =... | [
"def netflix_build_actual_ratings () :\r\n \r\n global verbose\r\n global MOVIES_DIR, PROBE_PATH\r\n global actualRatings, probe\r\n \r\n # allows for testing with hard-coded probe data\r\n if probe == None :\r\n f = open(PROBE_PATH)\r\n probe = f.read()\r\n f.close()\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resize and subtract mean from video input | def preprocess_input(video):
intervals = np.ceil(np.linspace(0, video.shape[0] - 1, 16)).astype(int)
frames = video[intervals]
# Reshape to 128x171
reshape_frames = np.zeros((frames.shape[0], 128, 171, frames.shape[3]))
for i, img in enumerate(frames):
img = imresize(img, (128, 171), 'bicub... | [
"def video_mean(self):\r\n self.imganalysis_averageimage = np.mean(self.videostack, axis = 0)\r\n self.pw_averageimage.setImage(self.imganalysis_averageimage)\r\n self.samplingrate_cam = self.Spincamsamplingrate.value() \r\n self.cam_time_label = np.arange(self.videostack.shape[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates a C3D Kerasl model | def C3D(weights='sports1M'):
if weights not in {'sports1M', None}:
raise ValueError('weights should be either be sports1M or None')
if K.image_data_format() == 'channels_last':
shape = (16, 112, 112,3)
else:
shape = (3, 16, 112, 112)
model = Sequential()
mo... | [
"def __generateC3DModel(self, input_shape, custom_weights_path):\n\n c3dModel = C3D(input_shape=input_shape, weights_path=custom_weights_path)\n\n model = c3dModel.generateModel()\n\n new_model = tf.keras.Model(inputs=model.input, outputs=model.layers[16].output)\n\n return new_model",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate SIGMA, SIGMA_SPECTRUM, WEIGHT, WEIGHT_SPECTRUM columns in the MS | def apply_weights(self, rms):
if rms.shape != self.data.shape:
abort('The rms array used to populate SIGMA, SIGMA_SPECTRUM, WEIGHT, and WEIGHT_SPECTRUM does not have the expected dimensions:\n'\
'rms.shape = '+rms.shape+'. Expected dimensions: '+self.data.shape)
ta... | [
"def defineSigmaLevels():\n # A and B values for the definition of sigma levelist\n # Since there are 72 model levels, there are 73 half levels, so it is for A and B values\n # the unit of A is hPa!!!!!!!!!!!!\n # from surface to TOA\n A = np.array([\n 0.000000e+00, 4.8... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert mean delays (i.e. nonturbulent) due to dry and wet components | def trop_calc_mean_delays(self):
delay = self.trop_ATM_dispersion() / speed_of_light
self.delay_alltimes = delay / np.sin(self.elevation_tropshape)
phasedelay_alltimes = 2*np.pi * delay / np.sin(self.elevation_tropshape) * self.chan_freq.reshape((1, self.chan_freq.shape[0], 1))
np.save(I... | [
"def propigate_delays(self, elements, math):\n pass",
"def update_delay(self, delay):",
"def delay() -> None:\n print(\"DELAY \" + str(int(numpy.random.normal(MU, SIGMA))))",
"def get_delay_minimum(self, synapse_info):",
"def _delay(self):\n time.sleep(random.randint(self.min_delay,self.max... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will change the pointing error for each antenna every pointing_timescale which one of could essentially think of as a scan length (e.g. 10 minutes) | def pointing_constant_offset(self,pointing_rms, pointing_timescale,PB_FWHM230):
self.PB_FWHM = PB_FWHM230 / (self.chan_freq.mean() / 230e9) # convert 230 GHz PB to current obs frequency
self.num_mispoint_epochs = max(1, int(np.floor(self.obslength / (pointing_timescale * 60.)))) # could be numbe... | [
"def pid(self):\n\n # Calculating Error for altitude, latitude, longitude\n self.check_obstacle()\n self.waypoint_setter()\n rospy.loginfo(\"##Setpoint:%s, %s, %s\",str(self.setpoint[1]),str(self.setpoint[2]),str(self.setpoint[0]))\n self.error_in_meters()\n self.marker_sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read in the bandpass info from an ASCII table, interpolate (spline) MS frequencies, and apply to data | def bandpass_correct(self):
info("Applying scalar B-Jones amplitudes")
# Read in the file
bjones_inp = np.loadtxt(self.bandpass_table,dtype=str)
self.bpass_input_freq = bjones_inp[0][1:].astype(np.float64)
self.bpass_input_freq *= 1e9 # convert from GHz to Hz
self.bjones_... | [
"def read_esa_predicts(filename,frequency_hz=401.585625e6):\n\n with open(filename) as f:\n lines = f.readlines()\n\n data_start=False\n lineskip=0\n\n m={}\n k=0\n c=299792458; # Speed of light\n\n for line in lines:\n if not data_start and line.find('KM') > 0:\n data_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add constant stationbased polarization leakage (DJones term) | def add_pol_leakage_manual(self):
if self.parang_corrected == False:
# Compute P-Jones matrices
self.pjones_mat = np.zeros((self.Nant,self.time_unique.shape[0],2,2),dtype=complex)
self.djones_mat = np.zeros((self.Nant,self.time_unique.shape[0],2,2),dtype=complex)
for ant in range... | [
"def ode_rhs(self):\n\n #: Bandpass l_ce\n #b, a = signal.butter(2, 50, 'low', analog=True)\n #l_ce_filt = signal.lfilter(b, a, self._l_ce.sym)\n\n l_ce_tol = cas.fmax(self._l_ce.sym, 0.0)\n _stim = cas.fmax(0.01, cas.fmin(self._stim.sym, 1.))\n\n #: Algrebaic Equation\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the paths of all .wav files found recursively in the path. | def recursive_wav_paths(path):
absolute_paths = []
for folder, subs, files in os.walk(path):
for file in files:
extension = os.path.splitext(file)[1]
if extension.lower() == '.wav':
file_path = os.path.join(folder, file)
absolute_paths.append(os.pa... | [
"def _get_wav_files(dir_path):\n files = []\n for file in os.listdir(dir_path):\n if file.endswith(\".wav\"):\n files.append(file)\n return files",
"def _get_files(path):\n ret_val = []\n for root, _, files in os.walk(path):\n for f in files:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the spectrogram of a reference recording located at path. Code written by Bongjun Kim. | def reference_spectrogram(path, augmentations: audaugio.ChainBase):
try:
y, sr = librosa.load(path, sr=44100)
except audioop.error as e:
logger = logging.getLogger('logger')
logger.warning("Could not load {0}\n{1}".format(path, e))
return None
augmented_audio = augmentations... | [
"def get_spectrogram_data(frame_rate, np_frames):\n # Set format details for plot.\n #fig = plt.figure(num=None, figsize=(12, 7.5), dpi=300)\n #ax = fig.add_subplot(111)\n #ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n #ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))\n #ax.yaxis.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the spectrogram of an imitation located at path. Code written by Bongjun Kim. | def imitation_spectrogram(path, augmentations: audaugio.ChainBase):
try:
y, sr = librosa.load(path, sr=16000)
except audioop.error as e:
logger = logging.getLogger('logger')
logger.warning("Could not load {0}\n{1}".format(path, e))
return None
augmented_audio = augmentations... | [
"def create_spectrogram(self, audio_path):\n audio_name = audio_path.split(\"/\")[-1].replace(\".wav\", \"\")\n fs, w = wavfile.read(audio_path)\n if len(w.shape) == 2:\n w = w[:, 0]\n dur = len(w) / fs\n\n cmap = plt.cm.get_cmap('Greys')\n cmap.set_under('w')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output relative mouse move position based on angles and accelerations. | def handle_mouse_move(self, angles, acc):
if angles['theta'] > THETA_TRESHOLD and acc['a_x'] < -ACC_TRESHOLD:
print('move left')
pyautogui.moveRel(-10, 0)
elif angles['theta'] > THETA_TRESHOLD and acc['a_x'] > ACC_TRESHOLD:
print('move right')
pyautogui.m... | [
"def get_mouse_position(self):\r\n\t\treturn -Vector.origin[0] + pygame.mouse.get_pos()[0], \\\r\n\t\tVector.origin[1] - pygame.mouse.get_pos()[1]",
"def mousepos():\n data = display.Display().screen().root.query_pointer()._data\n return data[\"root_x\"], data[\"root_y\"]",
"def display_mouse_position(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the pathname of the latest ragel trie. | def LatestRagelTriePath(top_level_dir, bitness):
if bitness not in (32, 64):
raise AssertionError('invalid bitness: ', bitness)
ragel_dirs = {32: 'ragel_trie_x86_32', 64: 'ragel_trie_x86_64'}
tries = os.listdir(os.path.join(top_level_dir, ragel_dirs[bitness]))
if not tries:
raise AssertionError('no trie... | [
"def lastpath(self):\n if self._lastpath is None:\n return \"\"\n maplist = self.mapstr[:].split()\n for xval, yval, tree in self._lastpath:\n maplist[xval] = f\"{maplist[xval][:yval]}{tree}{maplist[xval][yval + 1:]}\"\n\n return \"\\n\".join(maplist)",
"def _look... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A horizontal dual spin box widget designed for the XY size of a maze. | def __init__(
self,
minimum: XY,
maximum: XY,
initialValue: XY,
parent: Optional[QWidget] = None,
label: str = "by",
*args: Tuple[Any, Any],
**kwargs: Tuple[Any, Any],
) -> None:
valid = True
if (initialValue.x < minimum.x) or (initialV... | [
"def inflatebox(factor, lft, bot, rt, top):\n midx = (rt + lft)/2\n halfwidth = factor*(rt - lft)/2\n midy = (top + bot)/2\n halfheight = factor*(top - bot)/2\n return midx - halfwidth, midy - halfheight, \\\n midx + halfwidth, midy + halfheight",
"def draw_box(self, boxsize):\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the X and Y values of this input widget. Returns Tuple[int, int] The X and Y values of the number picker spin boxes. | def getValues(self) -> XY:
return XY(
self.__xSpinBox.value(),
self.__ySpinBox.value(),
) | [
"def _get_plot_coordinates(self) -> Tuple[int, int]:\n return self._x0 + AXIS_SPACE_PX, self._y0 # y does not need to be added AXIS_SPACE_PX, since it is at bottom",
"def unpack_coords(self):\n y = self.flat_value/Point.width\n x = abs((y * self.width) - self.flat_value)\n return x, y... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a cUR50 tfrecord Record into a tuple of tensors | def cUR50_parser(record):
keys_to_features = {
"uniref_id": tf.FixedLenFeature([], tf.string),
"seq_len": tf.FixedLenFeature([], tf.int64),
"seq": tf.FixedLenFeature([], tf.string),
"seq_phyche": tf.VarLenFeature(tf.float32),
}
parsed = tf.parse_single_example(record, k... | [
"def _parse_record(example_proto):\n\n example = tf.parse_single_example(example_proto, feature)\n im = tf.decode_raw(example['image'], tf.float32)\n im = tf.reshape(im, (img_rows, img_cols, 1))\n\n label = tf.decode_raw(example['label'], tf.int32)\n label = tf.reshape(label, (4, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open a tfrecords file in the cpdb format, parse, and return a tf.data.Dataset object | def cpdb_dataset(tfrecords):
dataset = tf.data.TFRecordDataset(tfrecords)
dataset = dataset.map(lambda x: cpdb_parser(x))
return dataset | [
"def read_tfrecord_dataset(filepaths):\n return tf.data.TFRecordDataset(filenames=filepaths).map(parse_tf_example)",
"def read_tfrecord(\n tfrecord_infile='{}-00000-of-00001.gz'.format(TFRECORD_OUTFILE),\n idx=0):\n raw_dataset = get_raw_dataset(tfrecord_infile)\n\n parsed_dataset = raw_datas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Speaks the string input | def speak(text):
proc.stdin.write('(SayText "%s")\n' % text) | [
"def handle_speak(event):\n bus.emit(Message('speak', event))",
"def stringReceived(self, string):\n raise NotImplementedError()",
"def string(self, string):\n\n self.__emulate_keyboard('type', string)",
"def printAndSay(self, string): \n tts = gTTS(text=string, lang='en')\n tts... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone `endpoint` in the indicated `destination` folder | def clone_to_folder(destination, endpoint):
click.echo('... cloning ' + endpoint + ' to ' + destination)
execute('git clone -q ' + endpoint) | [
"def clone_files(session, uuid, source, target):\n payload = {'site': uuid, 'path': 'environments/'+target+'/files'}\n data = {\n 'clone-from-environment': source,\n }\n return api.request(session, payload, 'POST', data)",
"def clone_url(self):\n raise NotImplementedError",
"def copy(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Returns the GMSD between `x` and `y`, without downsampling and color space conversion. `_gmsd` is an auxiliary function for `gmsd` and `GMSD`. | def _gmsd(
x: torch.Tensor,
y: torch.Tensor,
kernel: torch.Tensor,
value_range: float = 1.,
c: float = 0.00261, # 170. / (255. ** 2)
alpha: float = 0.,
) -> torch.Tensor:
c *= value_range ** 2
# Gradient magnitude
pad = kernel.size(-1) // 2
gm_x = tensor_norm(filter2d(x, kern... | [
"def _msgmsd(\n x: torch.Tensor,\n y: torch.Tensor,\n kernel: torch.Tensor,\n weights: torch.Tensor,\n alpha: float = 0.5,\n **kwargs,\n) -> torch.Tensor:\n\n gmsds = []\n\n for i in range(weights.numel()):\n if i > 0:\n x = F.avg_pool2d(x, kernel_size=2, ceil_mode=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Returns the MSGMSD between `x` and `y`, without color space conversion. `_msgmsd` is an auxiliary function for `msgmsd` and `MSGMSD`. | def _msgmsd(
x: torch.Tensor,
y: torch.Tensor,
kernel: torch.Tensor,
weights: torch.Tensor,
alpha: float = 0.5,
**kwargs,
) -> torch.Tensor:
gmsds = []
for i in range(weights.numel()):
if i > 0:
x = F.avg_pool2d(x, kernel_size=2, ceil_mode=True)
y = F.av... | [
"def msd(x, y):\n # WARNING: We hardcode the max and min value here\n max_ = 5\n min_ = 1\n\n if len(x) == 0:\n return -np.inf\n else:\n return 1 - (1 / len(x)) * np.sum(((x - y) / (max_ - min_)) ** 2)",
"def rmsd_no_align(frame1, frame2):\n ## find the displacement for each coordi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set configured GPIO pin direction | def set_direction(self, direction): | [
"def setup_pin(self, pin):\n # TODO add some extra checks here. Maybe verify BCM?\n GPIO.setup(pin, GPIO.OUT)",
"def set_pin_mode(self, pin, mode):\n if isRasPi:\n GPIO.setup(pin, mode)\n self.pin_config[pin] = mode\n return self.get_pin_mode(pin)",
"def set_pin_direction(self, pin,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function sends a monitoring record to a Java Gateway and receives the reply as a json. | def send_to_network(gateway, line):
values = line.split(',') + [0.0, 0.0, 0.0, 0.0]
raw_record = gateway.jvm.MonitoringRecord(*values)
record = gateway.entry_point.mappingFunc('1', raw_record).toJson()
return record | [
"def send(self):\n json_report = None\n try:\n json_report = json.dumps(self.report)\n except Exception as err:\n print(\"Could not convert the report to JSON. Threw exception: {}\".format(err))\n print('Report: {}'.format(self.report))\n\n if json_report:\n try:\n response = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds all the shared caracters from left to right. find_uninflected_stem('rAmaH', 'rAmo') => 1+aH | def find_uninflected_stem(stem, form):
i = 0
while i <= len(stem) - 1 and i <= len(form) - 1 and stem[i] == form[i]:
i += 1
stem_ending = stem[i:]
form_ending = form[i:]
if stem_ending == '' and form_ending == '':
operation = ''
else:
form_ending_len = len(form_ending)
... | [
"def fold_stem(l_seq, r_seq):\n fc = RNA.fold_compound(l_seq + r_seq)\n fc.hc_add_from_db('<'*len(l_seq) + '>'*len(r_seq))\n fc, mfe = fc.pf()\n return fc, mfe",
"def test_search_small(self):\n seq = \"GCCTGGAAAGGC\"\n motif = [(4, \"CTGGAAAG\")]\n self.assertEqual(stem.search(mot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the path of the tshark executable. If the user has provided a path or specified a location in config.ini it will be used. Otherwise default locations will be searched. | def get_process_path(tshark_path=None, process_name="tshark"):
config = get_config()
possible_paths = [config.get(process_name, "%s_path" % process_name)]
# Add the user provided path to the search list
if tshark_path is not None:
possible_paths.insert(0, tshark_path)
# Windows search orde... | [
"def whereis(progName, logger: logging.Logger = None):\n cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')\n\n if platform == \"win32\":\n filename, file_extension = os.path.splitext(progName)\n if file_extension != '.exe' or fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns 'Y' for tshark versions >= 1.10.0 and 'R' for older versions. | def get_tshark_display_filter_flag(tshark_version):
if tshark_version >= LooseVersion("1.10.0"):
return '-Y'
else:
return '-R' | [
"def yn(value: bool) -> str:\n return \"Y\" if value else \"N\"",
"def yn_bool(yn_flag: str) -> bool:\n\n return True if yn_flag.upper() == 'Y' else False",
"def test_radio_version_inc(self):\n assert bs.return_radio_version(\"10.3.2.2639\") == \"10.3.2.2640\"",
"def get_roaster_state(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot pixels in 3D. | def plot3d(pixels, colors_rgb, axis_labels=list("RGB"),
axis_limits=[(0, 255), (0, 255), (0, 255)], plot=False):
# Create figure and 3D axes
fig = plt.figure(figsize=(8, 8))
ax = Axes3D(fig)
# Set axis limits
ax.set_xlim(*axis_limits[0])
ax.set_ylim(*axis_limits[1])
ax.set_zlim(... | [
"def plot_3d(pts):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs, ys, zs = zip(*pts)\n ax.scatter(xs, ys, zs, c='r', marker='o')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n plt.show()",
"def plot_original_3d(self, path=\"images\"):\n rai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the atom's morgan index | def refresh_morgan(self):
self.morgan = self.new_morgan
self.new_morgan=0 | [
"def show_atom_index(self):\r\n try:\r\n self.show_atom_index_judge = True\r\n self.show_atom_element_judge = False\r\n\r\n self.plot(self.Atomsobject)\r\n except Exception as e:\r\n print(e)",
"def modIndex(self, suffix, attr, mod):\n entries_backe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Include the morgan index into the atom's name | def include_morgan_in_name(self):
self.name=self.old_name+str(self.morgan) | [
"def getMarkerName(index):",
"def atom_name(self):\n return self.atom.name.strip()",
"def index_file_name(name: str) -> str:\n return name + '-idx.json'",
"def get_index_name(msg_date):\n return 'email-message-index-{}'.format(msg_date.format('YYYYMM'))",
"def _make_index_name(z_type, colum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
duplicates an object within a scene | def duplicate(scene, ob):
copy = ob.copy()
# some ops will fail (like triangle mesh) if the object we're operating on
# is hidden. i think its safe to unhide it
copy.hide = False
copy.data = ob.data.copy()
scene.objects.link(copy)
return copy | [
"def duplicate_helper_object(scene, remote_groups, ob, instance):\n newob = find_cached(scene, ob, instance)\n if newob: return newob\n newob = ob.copy()\n newob.data = newob.data.copy()\n scene.objects.link(newob)\n newob.layers = scene.layers\n newob.matrix_world = ob.matrix_world\n make_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate incoming meter_value supposed to be negative (1) because it is about consumption | def _calc_result(self):
return self.pv_value + self.meter_value*(-1) | [
"def meter_value(self):\n return int(\n (self.amountused / self.amounttotal)\n * self.arcrange + self.arcoffset\n )",
"def electric_meter(self, data):\n # convert power diff from kwh to kws\n #self.watts = (self.powerDiff * 3600 /self.timeDiff)\n\n dtime = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide generated photovoltaic value | def _get_simulated_photovoltaic_value(self):
return random.randint(5000,9000) | [
"def change_value(image):\n\n out = None\n\n ### YOUR CODE HERE\n out = 0.5 * image ** 2\n ### END YOUR CODE\n\n return out",
"def vat_rate():",
"def volumen_cilindro(radio, altura):\n volumen = pi * radio ** 2 * altura\n return volumen",
"def getValue(self, *args) -> \"PyObject *\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the consume method of PVSimulator | def main():
pv_simulator = PVSimulator()
pv_simulator.consume() | [
"def produce_consume():\n logger = logging.getLogger(__name__)\n\n even_consumer = actors.Printer.start(\"Even Printer\")\n odd_consumer = actors.Printer.start(\"Odd Printer\")\n producer = NumberGenerator.start(\"RNG\")\n producer.proxy().register(even_consumer, 'even number')\n producer.proxy().... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list that has `length` number of elements, and each element is the integer 1. Returns the list. | def create_ones_list(length):
return 0 | [
"def build_list(length):\n return build_list_with_step(length, 1)",
"def count(length):\n return list(range(length))",
"def build_list_with_step(length, step):\n lst = []\n i = 0\n while len(lst) < length:\n if i % step == 0:\n lst.append(i)\n i += 1\n return lst",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the length of the list is even. Returns False otherwise. | def is_even(values):
return False | [
"def is_even(x):\n return True",
"def is_even(name):\n \n return get_name_length(name) % 2 == 0",
"def even_number_of_evens(numbers):\n\n # Check to see if the list is empty\n if numbers == []:\n return False\n else:\n # Set a `number_of_evens` variable that will be incremented e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the list is even, return string_list without changing anything. If the list is not even, append the string "SIKE" to the end of string_list, then return the string_list. | def make_even(string_list):
return 0 | [
"def format_list(my_list):\n my_list[-1] = \"and \" + my_list[-1] #add the and requirement to appear before the last item\n print(my_list, type(my_list))\n new_even_list = my_list[1::2]\n print(new_even_list, type(new_even_list))\n formated_string = \", \".join(new_even_list)\n print(formated_stri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts how many times `target` appears in `values` and returns an int. | def count_value_1(values, target):
return 0 | [
"def count_in_sorted(arr, target, target_inc):\n return lowest_index(arr, target_inc) - lowest_index(arr, target)",
"def get_target_counts(camera, target_scaling, scaling_tolerance):\n try:\n bit_depth = camera.bit_depth.to_value(u.bit)\n except NotImplementedError:\n bit_depth = 16\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor function initializes object with title and year | def __init__(self, title, year):
self.title = title
self.year = year
# id is a field that is required for rendering of the website later
self.id = "-".join(title.split()) | [
"def __init__(self,season,year):\n seasondict = buildseasondict(season,year)\n self.season = seasondict[\"season\"]\n self.year = seasondict[\"year\"]",
"def __init__(self, author, title):\r\n self.author = author\r\n self.title = title",
"def __init__(self, year: int, start_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets poster image of movie | def set_poster(self, poster):
self.poster = poster | [
"def update_poster_path(self, movie, poster_path):\n movie.poster_path = poster_path\n movie.save()",
"async def _poster(self, ctx, *, value=None):\r\n key = 'poster'\r\n # test key for url\r\n if ctx.message.server.id not in self.guilds:\r\n data = _unknown_guild(ctx... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets trailer of movie | def set_trailer(self, trailer):
self.trailer = trailer | [
"def get_trailer(movie_id, api_key):\n\n # initialize trailer variable with a placeholder YouTube video\n trailer = \"https://www.youtube.com/watch?v=D-CQVnuiR1I\"\n\n # structure the URL for the API request\n url = \"https://api.themoviedb.org/3/movie/\"\n url += str(movie_id) #\n url += \"/vide... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handles the Add Teacher button being clicked | def addTeacherBtn_clicked(self):
first = str(self.ui.firstNameLineEdit.text()).strip()
first = sanitize(first)
last = str(self.ui.lastNameLineEdit.text()).strip()
last = sanitize(last)
address = str(self.ui.addressLineEdit.text()).strip()
address = sanitize(address)
... | [
"def createNewTeacherBtn_clicked(self):\n dialog = AddTeacherDialog(testing=self.testing, closeAfterAdd=True)\n # For Modal dialog\n result = dialog.exec_()\n\n if result == True:\n t = dialog.getTeacher()\n self.ui.teacherLineEdit.setText(t.first + ' ' + t.last)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flushes the messages send to the bot during downtime so that the bot does not start spamming when it gets online again. | def flush_messages(bot):
updates = bot.get_updates()
while updates:
print("Flushing {} messages.".format(len(updates)))
time.sleep(1)
updates = bot.get_updates(updates[-1]["update_id"] + 1) | [
"async def flush(ctx):\r\n\tisAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator\r\n\t# Only allow admins to change server stats\r\n\tif not isAdmin:\r\n\t\treturn\r\n\t# Flush settings\r\n\tawait quickFlush()\r\n\tmsg = 'Flushed settings to disk.'\r\n\tawait bot.send_message(ctx.message.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles and returns a regular expression for word tokenization | def _word_tokenizer_re(self):
try:
return self._re_word_tokenizer
except AttributeError:
self._re_word_tokenizer = re.compile(
self._word_tokenize_fmt %
{
'NonWord': self._re_non_word_chars,
'MultiChar': self... | [
"def regex_from_tokens(tokens, word_boundary=True, capture=True):\n tokens_ = tokens[:]\n\n # The longest tokens are first in the list\n tokens_.sort(key=lambda word: len(word), reverse=True)\n\n # Some tokens might contain parentheses or other problematic characters\n tokens_ = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles and returns a regular expression to find contexts including possible sentence boundaries. | def period_context_re(self):
try:
return self._re_period_context
except:
self._re_period_context = re.compile(
self._period_context_fmt %
{
'NonWord': self._re_non_word_chars,
'SentEndChars': self._re_sent_en... | [
"def compile(self):\n return re.compile(self.pattern, self.flags)",
"def getContext(self, word = None, scope = 10, exact = False):\n\n\t\tif word == None:\n\t\t\treturn None\n\t\telif exact == False:\n\t\t\tword = word.lower()\n\n\t\ttextList = self.tokens(includePunctuation = False, lc = True)\n\t\tconcLi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields pairs of tokens from the given iterator such that each input token will appear as the first element in a yielded tuple. The last pair will have None as its second element. | def _pair_iter(it):
it = iter(it)
prev = next(it)
for el in it:
yield (prev, el)
prev = el
yield (prev, None) | [
"def pairs(seq):\n iterable, copied = tee(seq)\n next(copied)\n for x, y in zip(iterable, copied):\n yield x, y",
"def iter_pairs(l, last=True):\r\n i = iter(l)\r\n b = i.next()\r\n done = 0\r\n while not done:\r\n a = b\r\n try:\r\n b = i.next()\r\n exc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The type with its final period removed if it has one. | def type_no_period(self):
if len(self.type) > 1 and self.type[-1] == '.':
return self.type[:-1]
return self.type | [
"def remove_type(self, unit_type):\n new_polymer = []\n unit_type = unit_type.lower()\n for unit in self.units:\n if unit.lower() == unit_type:\n continue\n else:\n new_polymer.append(unit)\n \n self.units = new_polymer",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The type with its final period removed if it is marked as a sentence break. | def type_no_sentperiod(self):
if self.sentbreak:
return self.type_no_period
return self.type | [
"def type_no_period(self):\n if len(self.type) > 1 and self.type[-1] == '.':\n return self.type[:-1]\n return self.type",
"def fix_missing_period(self,line):\n\n if line == \"\": \n return line\n if line[-1] in self.END_TOKENS: \n return line\n return line + \" .\""... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the token's first character is uppercase. | def first_upper(self):
return self.tok[0].isupper() | [
"def check_word_capitalization(word):\n return_value = False\n if (len(word) > 1):\n return_value = True if (word[0].isupper() and word[1].islower()) else False",
"def _has_capital(the_string):\n if any(char in ascii_uppercase for char in the_string):\n return True\n else:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the token's first character is lowercase. | def first_lower(self):
return self.tok[0].islower() | [
"def to_lower(token):\r\n return token.lower() if token else None",
"def is_first_letter(val):\n return ord(val[0].lower()) in range(ord('a'), ord('z') + 1)",
"def contains_lowercase(s):\n return contain_lower_regexp.search(s) is not None",
"def IsNameStartChar(c):\n if c <= u\"z\":\n if c ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the token text is that of an ellipsis. | def is_ellipsis(self):
return self._RE_ELLIPSIS.match(self.tok) | [
"def has_more_tokens(self):",
"def hasMoreTokens(self):\r\n return len(self.lines) != 0",
"def does_end_token_exist(self) -> bool:",
"def is_maybe_off_by_one(text, anno):\n span = anno.text_span()\n start = span.char_start\n end = span.char_end\n start_ok = start == 0 or text[start - 1].iss... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the token text is that of an initial. | def is_initial(self):
return self._RE_INITIAL.match(self.tok) | [
"def _is_expansion_initial_acronym(acro: str, full: str) -> bool:\n words = full.split()\n if len(words) == 1:\n return True\n last_word = words[-1]\n initial = last_word[0]\n pos = acro.lower().rfind(initial.lower()) # Last occurence of initial in the acronym.\n if pos < 0:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the token text is all alphabetic. | def is_alpha(self):
return self._RE_ALPHA.match(self.tok) | [
"def covers_alphabet(sentence: str) -> bool:\n # greater than or equal to include , ; ! etc.\n return set(sentence.lower()) >= set(\"abcdefghijklmnopqrstuvwxyz\")",
"def is_alphabetic(word_str):\n return re.match(r'^[a-zA-Z]+$', word_str) is not None",
"def isAlpha(self, char):\n return char in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform the first pass of annotation, which makes decisions | def _annotate_first_pass(self, tokens):
for aug_tok in tokens:
self._first_pass_annotation(aug_tok)
yield aug_tok | [
"def onApplyAnnotation(self):\r\n # get fiducial, output and ref nodes\r\n fiducialNode = self.inputFiducialsNodeSelector.currentNode()\r\n outputVolumeNode = self.outputSelector.currentNode()\r\n refNode = self.refSelector.currentNode()\r\n\r\n # Run the annotation stuff\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a tokenized copy of s. | def tokenize(self, s):
if overridden(self.batch_tokenize):
return self.batch_tokenize([s])[0]
else:
raise NotImplementedError() | [
"def tokenize(self):",
"def __tokenize(self, is_useful=None):\n unfiltered_tokens = nltk.tokenize.word_tokenize(self.document)\n if is_useful:\n return filter(is_useful, unfiltered_tokens)\n else:\n return unfiltered_tokens",
"def tokenize(self) :\n\n\t\traw1 = re.sub(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Classifies candidate periods as sentence breaks, yielding a dict for each that may be used to understand why the decision was made. See format_debug_decision() to help make this output readable. | def debug_decisions(self, text):
for match in self._lang_vars.period_context_re().finditer(text):
decision_text = match.group() + match.group('after_tok')
tokens = self._tokenize_words(decision_text)
tokens = list(self._annotate_first_pass(tokens))
while not token... | [
"def get_decisionCPTs(self, mode=None):\n cptdict = {}\n if mode == 'basename':\n try:\n for bn in list(self.bn_part.keys()):\n if self.bn_part[bn][0].player != 'nature':\n cptdict[bn] = self.bn_part[bn][0].CPT\n except Att... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a text, returns a list of the (start, end) spans of sentences in the text. | def span_tokenize(self, text):
return [(sl.start, sl.stop) for sl in self._slices_from_text(text)] | [
"def split_sentences(cls, text):\n last_index = 0\n intervaled = []\n for match in cls.SENTENCE_SPLITTER.finditer(text):\n begin, end = match.span()\n intervaled.append(text[last_index:begin])\n intervaled.append(text[begin:end])\n last_index = end\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a text, generates the sentences in that text by only testing candidate sentence breaks. If realign_boundaries is True, includes in the sentence closing punctuation that follows the period. | def sentences_from_text(self, text, realign_boundaries=True):
sents = [text[sl] for sl in self._slices_from_text(text)]
if realign_boundaries:
sents = self._realign_boundaries(sents)
return sents | [
"def split_into_sentences(text):\n if \".)\" in text: text = text.replace(\".)\", \"<prd>)\")\n sentences = text.split(\".\")\n text = text.replace(\"<prd>\", \".\")\n for s in sentences:\n s = s.replace(\"<prd>\", \".\")\n return sentences",
"def split_sentences(text):\n text = re.sub(r'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the given text includes a sentence break. | def text_contains_sentbreak(self, text):
found = False # used to ignore last token
for t in self._annotate_tokens(self._tokenize_words(text)):
if found:
return True
if t.sentbreak:
found = True
return False | [
"def check_sentence(text):\n result = re.search(r\"^[A-Z][a-z\\s]*[.?!]$\", text)\n return result != None",
"def isWordIn(self, text):\n temp = text\n temp2 = \"\"\n temp = temp.lower()\n for c in temp:\n if c in \"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a text, generates the sentences in that text. Annotates all tokens, rather than just those with possible sentence breaks. Should produce the same results as ``sentences_from_text``. | def sentences_from_text_legacy(self, text):
tokens = self._annotate_tokens(self._tokenize_words(text))
return self._build_sentence_list(text, tokens) | [
"def __parse_sentences_from_text(text: str) -> List[Sentence]:\n doc = nlp(text)\n return doc.sentences",
"def split_into_sentences(text: str) -> typing.List[str]:\n\n return nltk.sent_tokenize(text)",
"def _build_sentence_list(self, text, tokens):\n # Most of the work here is making sure that w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a sequence of tokens, generates lists of tokens, each list corresponding to a sentence. | def sentences_from_tokens(self, tokens):
tokens = iter(self._annotate_tokens(self._Token(t) for t in tokens))
sentence = []
for aug_tok in tokens:
sentence.append(aug_tok.tok)
if aug_tok.sentbreak:
yield sentence
sentence = []
if se... | [
"def make_token_seq(seq):\n ret = []\n for name in seq: ret.append(make_token(name))\n return ret",
"def _build_sentence_list(self, text, tokens):\n # Most of the work here is making sure that we put the right\n # pieces of whitespace back in all the right places.\n\n # Our position ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a set of tokens augmented with markers for linestart and paragraphstart, returns an iterator through those tokens with full annotation including predicted sentence breaks. | def _annotate_tokens(self, tokens):
# Make a preliminary pass through the document, marking likely
# sentence breaks, abbreviations, and ellipsis tokens.
tokens = self._annotate_first_pass(tokens)
# Make a second pass through the document, using token context
# information to ch... | [
"def _annotate_first_pass(self, tokens):\n for aug_tok in tokens:\n self._first_pass_annotation(aug_tok)\n yield aug_tok",
"def generate_tokenized_sentences(paragraph: str) -> Iterator[str]:\n word_tokenizer = RegexpTokenizer(r'[-\\'\\w]+')\n\n for sentence in sent_tokenize(para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the original text and the list of augmented word tokens, construct and return a tokenized list of sentence strings. | def _build_sentence_list(self, text, tokens):
# Most of the work here is making sure that we put the right
# pieces of whitespace back in all the right places.
# Our position in the source text, used to keep track of which
# whitespace to add:
pos = 0
# A regular expres... | [
"def engTokenize(text):\n return [token.text for token in eng.tokenizer(text)]",
"def prep_text(mission):\n sentences = nltk.sent_tokenize(mission)\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\n return sentences",
"def sentence_tokenize(self, text_list):\n return [sent_token... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return the offsets of the tokens in s, as a sequence of ``(start, end)`` tuples, by splitting the string at each successive match of regexp. | def regexp_span_tokenize(s, regexp):
left = 0
for m in finditer(regexp, s):
right, nxt = m.span()
if right != 0:
yield left, right
left = nxt
yield left, len(s) | [
"def span_tokenize(self, text):\n return [(sl.start, sl.stop) for sl in self._slices_from_text(text)]",
"def preprocess_with_offsets(text: str) -> List[Tuple[int, str]]:\n\n def finditer():\n offset = 0\n\n for mo in __PARAGRAPH_SEP.finditer(text):\n yield (offset, text[offset:m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
User adds a new stock. Displays a message requesting the user to enter a stock symbol. | def addNewStock(bot, update):
if update.message.chat.username is None:
# User has no username
update.message.reply_text(
"It seems you do not have a Telegram Username.\nI'll need your username in order to function :( /start me up when you have one! (You can set your username in S... | [
"def create_stock():\n return {\n \"code\": \"success\",\n \"message\": \"stock created\"\n }",
"def display_stock():",
"def addStock(self, stock_id, quantity , unit_price, commission_price, date, trans_type):\n self.conn.execute(\n \"\"\"INSERT INTO portfolio (stock_id, qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Permanently removes user from application and ends conversation. | def exit(bot, update, user_data):
update.message.reply_text(
"Thank you for using me! All your data has been cleared and you will no longer receive notifications.")
bots.clearChatFromApp(update.message.chat.id)
user_data.clear()
return ConversationHandler.END | [
"def end() -> None:\n session.pop(KEY_USER_ID, None)\n session.pop(KEY_USER_AUTH_TOKEN, None)\n session.permanent = False",
"def remove_user():\r\n user_input = input(\"| Enter the name of the User |\")\r\n aduser.ADUser.from_cn(user_input).delete()\r\n return \"| User removed |\"",
"def delet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends registered users a notification if their saved threshold was exceeded. JEN first updates prices for all stocks saved in the application. For each stock with an exceeded threshold, JEN sends a notification to the corresponding user. | def notifyUsersIfThresholdExceeded(bot, job):
bots.updatePriceOfExistingStocks()
userIDs, messages = bots.extractTriggeredStocks()
for i in range(len(userIDs)):
print(userIDs[i], messages[i])
bot.send_message(chat_id=userIDs[i],
text=messages[i], parse_mode='HTML') | [
"def notification_trigger(self):\n self.today = self.entry_date.strftime(\"%Y-%m-%d\")\n #finding notify items\n self.df_notify = self.df_user.loc[self.df_user[\"notify (days)\"] <= self.today] \n self.name_notify = list(self.df_notify[\"title\"])\n #EXPIRED THINGS\n self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main function to be executed. If database does not exist, JEN proceeds to set it up. A job to update existing stock prices is added to the jobQueue once every 24 hours. During which, JEN checks if users' threshold has been exceeded and proceeds to send a notification accordingly. The polling process runs continuously. | def main():
bots.setup_database()
updater = Updater(token=TOKEN)
jobQueue = updater.job_queue
dispatcher = updater.dispatcher
# Set price updater and notifier to execute every 24 hours
job_minute = jobQueue.run_repeating(
notifyUsersIfThresholdExceeded, interval=86400, first=0)
# S... | [
"def create_jobs_and_queue(self):\n new_job_exists = False\n\n #c = self.db.cursor(cursor_factory=psycopg2.extras.DictCursor)\n #c.execute(\"SELECT * FROM deepstyle_job WHERE job_status='Q'\")\n c = self.safe_execute_sql(\"SELECT * FROM deepstyle_job WHERE job_status='Q'\", curs_fact=Tru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes list of array and number of trials as argument. It prints time taken to perfrom giftwrap algorithm for given lists | def analyse_time(size_to_test, no_of_trials):
if sys.version_info < (3, 3):
get_time = time.clock
else:
get_time = time.perf_counter
REZ = time.get_clock_info('perf_counter').resolution
total_time = 0
for trial in range(no_of_trials):
list_to_test = generate_ra... | [
"def time_it(input_list):\n for i in range(501):\n start = time.time()\n radix_sort(input_list)\n time_passed = time.time() - start\n avg_time = time_passed / 500\n return avg_time",
"def timing_analysis(func, start, stop, inc, runs):\n\n for n in range(start, stop, inc): ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save a contact probability matrix as an RR file. | def save_rr_file(filename, probs, domain, sequence,
method='dm-contacts-resnet'):
assert len(sequence) == probs.shape[0]
assert len(sequence) == probs.shape[1]
with tf.io.gfile.GFile(filename, 'w') as f:
f.write(RR_FORMAT.format(domain, method, sequence))
for i in range(probs.shape[0]):
... | [
"def export_matrix(self):\n self.matrix_filename = f'similarity_matrix_{self.m1}_{self.m2}_{self.type}_{self.parce}_{self.net}_{self.corr}'\n\n self.path_matrix_final = f'{self.output}/similarity_matrices/{self.type}/{self.parce}/{self.corr}'\n if not os.path.exists(self.path_matrix_final):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save Torsions to a file as pickle of a dict. | def save_torsions(torsions_dir, filebase, sequence, torsions_probs):
filename = os.path.join(torsions_dir, filebase + '.torsions')
t_dict = dict(probs=torsions_probs, sequence=sequence)
with tf.io.gfile.GFile(filename, 'w') as fh:
pickle.dump(t_dict, fh, protocol=2) | [
"def pickle_save_dict(f, d):\n import pickle\n pickle.dump( d, open( f, 'wb' ) )",
"def pickle_dump(what, file):\n with open(file, 'wb') as f:\n pickle.dump(what, f)",
"def storeMoments(filename, data):\n\tfileObject = open(filename, 'wb')\n\tpickle.dump(data, fileObject)\n\tprint ('Data success... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take weather data in weewx format and transform to param/value dict | def format_weather_data(data_str):
## Data sample direct from weewx (shortened)
# "altimeter: 72.317316, ... maxSolarRad: None, ... windGustDir: 359.99994, windSpeed: 5.1645e-09"
# Replace "None" values with 0's
data_str = data_str.replace("None", "0.0")
# Grab the list of param/values
pairs... | [
"def get_weather(self):\n to_ret = {}\n weather = self.get_location_weather()\n\n to_ret['relative_humidity'] = weather['main']['humidity']\n to_ret['temperature'] = weather['main']['temp']\n to_ret['wind_speed'] = weather['wind']['speed']\n to_ret['wind_direction'] = weath... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inject the Eetlijst client from cache, if available. Otherwise, create a new one. | def inject_client(func):
@functools.wraps(func)
def _inner():
username = request.args.get("username")
password = request.args.get("password")
if not username or not password:
return abort(400)
# Fetch eetlijst client from cache
key = username + "-" + passwo... | [
"def _create_client(self):\r\n self.association_refresh_time = {}\r\n auth_plugin = k_loading.load_auth_from_conf_options(\r\n cfg.CONF, 'placement')\r\n client = k_loading.load_session_from_conf_options(\r\n cfg.CONF, 'placement', auth=auth_plugin)\r\n client.addit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lowd representation is a 21element vector First 20 elements are the count of each amino acid present in the active site Last element is the average distance between the center of each residue | def get_low_d_rep(active_site):
aas = [sum(res.type == AA for res in active_site.residues) for AA in AAs]
aas.append(np.nanmean(distance_matrix(active_site.residues).flatten()))
return(np.array(aas)) | [
"def get_totalleng(self):\n length_count = 0\n for base in (self.sequence):\n if base:\n length_count += 1\n exon_count = 0\n for base in (self.sequence):\n if base == exon:\n exon_count += 1\n if base != exon:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the int elements in every element of L. It does not return anything. | def deep_reverse(L):
L.reverse()
for i in L:
i.reverse() | [
"def deep_reverse(L):\n temp = list(L)\n for i in range(len(L)):\n # reverse top list\n L[len(L) - 1 - i] = temp[i]\n\n # reverse inner list\n inL = L[len(L) - 1 - i]\n temp2 = list(inL)\n for j in range(len(inL)):\n inL[len(inL) - 1 - j] = temp2[j]",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |