query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Initialize the handler. Read all config variables and creates a connection to OpenStack. | def __init__(self, config):
self.USERNAME = os.environ["OS_USERNAME"]
self.PASSWORD = os.environ["OS_PASSWORD"]
self.PROJECT_NAME = os.environ["OS_PROJECT_NAME"]
self.PROJECT_ID = os.environ["OS_PROJECT_ID"]
self.USER_DOMAIN_NAME = os.environ["OS_USER_DOMAIN_NAME"]
self.... | [
"def _do_custom_setup(self):\n self._create_handle(\n hostname=self.configuration.ixsystems_server_hostname,\n port=self.configuration.ixsystems_server_port,\n login=self.configuration.ixsystems_login,\n password=self.configuration.ixsystems_password,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Image with Tags. | def get_Image_with_Tag(self, id):
self.LOG.info(f"Get Image {id} with tags")
try:
img = self.conn.get_image(name_or_id=id)
if not img:
return Image()
properties = img.get("properties")
if not properties:
properties = {}
... | [
"def getOGTagsImage(self):",
"def retrieve_pictures_by_tag(tag_):\n database = get_db()\n return database.retrieve_pictures_by_tag(tag_)",
"def get_photos_by_tag(tag, **args):\n args.update({\n 'access_key': ACCESS_KEY\n })\n\n url = API_BASE + \"/by_tag/\" + str(tag) + '?' + u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the Limits. (maxTotalVolumes,maxTotalVolumeGigabytes, maxTotalInstances,totalRamUsed,totalInstancesUsed) of the OpenStack Project from the Client. | def get_limits(self):
self.LOG.info("Get Limits")
limits = {}
limits.update(self.conn.get_compute_limits())
limits.update(self.conn.get_volume_limits()["absolute"])
return {
"max_total_cores": str(limits["max_total_cores"]),
"max_total_instances": str(lim... | [
"def ex_limits(self):\r\n\r\n result = self._sync_request(command='listResourceLimits',\r\n method='GET')\r\n\r\n limits = {}\r\n resource_map = {\r\n 0: 'max_instances',\r\n 1: 'max_public_ips',\r\n 2: 'max_volumes',\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A lightweight dummy request. This request is ultralightweight and should be used only when the request itself is not a large focus in the callstack. It is way easier to mock and control sideeffects using this object. It does not have request extensions applied. Threadlocals are not properly pushed. | def dummy_request(app):
request = DummyRequest()
request.registry = app.registry
request.host = 'example.com'
return request | [
"def _mock_request():\n return _MockRequestClient().request()",
"def dummy_request(db_session):",
"def test_request_init(self):\n\n\t\tself.assertEqual(self.request.path, '/index')\n\t\tself.assertEqual(self.request.method, 'GET')\n\t\tself.assertEqual(self.request._get_data, None)\n\t\tself.assertEqual(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the specified handle into an NBRF record. | def parse(self, handle):
self._consumer = _RecordConsumer()
self._scanner.feed(handle, self._consumer)
return self._consumer.data | [
"def create_rec_parser(self, file_handle):\n parser = AdcptMLog9Parser(self.rec_config,\n file_handle,\n self.exception_callback)\n return parser",
"def parse(cls, buf):\n kwargs = {}\n\n # Splits buf containing the re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that all keyword with the given name and args have the given status Keyword names need to be passed in as fully qualified names exactly as they appear in the logs. expected_status should be either PASS or FAIL Example Log Hello, world Assert keyword status PASS BuiltIn.log Hello, world | def assert_keyword_status(self, expected_status, keyword_name, *args):
keyword_was_found = False
for name, attrs in self.keyword_log:
if name == keyword_name and args == tuple(attrs["args"]):
keyword_was_found = True
if attrs["status"] != expected_status:
... | [
"def test_find_words_by_status(self):\n pass",
"def assert_job_status(job: BatchJob, expected_status: str):\n # If the next assert is going to fail, then first show the logs of the job.\n actual_status = job.status()\n message = (\n f\"job {job}: did not end with expected status '{expected_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current working directory as a `remote path ` object | def getpath(self):
return RemotePath(self.remote, self) | [
"def remote_path(self) -> str:\n return self._remote_path",
"def get_local_directory(self):\n \n # Gives Local Direcory path equivalent to URL Path in server\n rval = os.path.join(self.rootdir, self.domain)\n\n for diry in self.dirpath:\n if not diry: continue\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads a local file/directory (``src``) to a remote destination (``dst``). | def upload(self, src, dst):
raise NotImplementedError() | [
"def upload(self, source, dest=None, overwrite=False, fs=None):\n from ..filesystems.local import LocalFsClient\n\n if fs is None or isinstance(fs, LocalFsClient):\n logger.info('Copying file from local...')\n dest = dest or posixpath.basename(source)\n cmd = (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Creates an SSH tunnel from the TCP port (``lport``) of the local machine (``lhost``, defaults to ``"localhost"``, but it can be any IP you can ``bind()``) to the remote TCP port (``dport``) of the destination machine (``dhost``, defaults to ``"localhost"``, which means this remote machine). The returned | def tunnel(self, lport, dport, lhost = "localhost", dhost = "localhost"):
opts = ["-L", "[%s]:%s:[%s]:%s" % (lhost, lport, dhost, dport)]
return SshTunnel(ShellSession(self.popen((), opts), self.encoding)) | [
"def ssh_port_forward(context, port, host=None, local_port=None):\n\n # Load the SSH config\n ssh_config = aws_infrastructure.tasks.ssh.SSHConfig.load(ssh_config_path=ssh_config_path)\n\n # Remote port is required\n remote_port = int(port)\n\n # If no remote host is provided, use ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the first position ('i') a given threshold ('thresh') is exceeded (for switch=1), or not exceeded (for switch=0), in a given list ('sequence') for a moving window specified by the moving_window module. If you want to see which week in a year the temperature first exceeds 15 degrees, this will do that for you. | def first_threshold (sequence, winsize, step, thresh, switch):
import numpy as np
import moving_window
try: chunks=moving_window(sequence,winsize,step)
except TypeError:
raise Exception("**ERROR** moving_window poorly specified**")
import sys
sys.exit(1)
i=0
for chunk in chunks:
if switch == 1: test1 ... | [
"def startFinder( xyBinStds, threshold ):\n\n for i in range(1,len(xyBinStds)):\n if (xyBinStds[i] - xyBinStds[i-1]) > threshold:\n return i",
"def get_thresh(data,threshold):\r\n for i in range(len(data)):\r\n if np.abs(data[i]) >= threshold:\r\n return i\r\n return m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draw x, mu std | def draw_mean_std(x, mu, std, title = None): | [
"def gaussian(x, mean, std):\n return (1/(std*np.sqrt(2*np.pi))) * np.exp(-0.5*np.square((x-mean)/std))",
"def normalize(X, mu=None, stdev=None):\n ### START YOUR CODE ###\n if mu == None:\n mu = np.mean(X)\n if stdev == None:\n stdev = np.std(X, ddof=1)\n X1 = (X - mu)/stdev\n ##... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This should return a button with appropriate classes for an action in a given context this will typiclly be called by a get_buttons function which will take call get actions to get the actions and then make | def make_button(action, id, context='std', rectype='quest', eventid=0, questid=0):
# Below is result for call to link question to event
session = current.session
stdclass = "btn btn-primary btn-xs btn-group-xs"
warnclass = "btn btn-warning btn-xs btn-group-xs"
successclass = "btn btn-success btn-xs... | [
"def translateButtonsFromKupu(self, context, buttons):\n return_buttons = []\n\n for button in buttons:\n if button == 'save-button':\n try:\n if not context.checkCreationFlag():\n return_buttons.append('save')\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots the points xs,ys with labels drawn on each point | def plot(self, xs, ys, labels, colours=None):
plt.scatter(xs, ys, c=colours)
if labels is not None:
for label, x, y in zip(labels, xs, ys):
plt.annotate(
label,
xy=(x, y), xytext=(-30, 30),
textcoords='offset points', ha='right', va='bottom',
arrowprops=dict... | [
"def plot(X,Ys,labels,xlabel=\"\",ylabel=\"\",title=\"\"):\n for Y,label in zip(Ys,labels):\n plt.plot(X,Y,label=label)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.suptitle(title)\n plt.legend()\n plt.show()",
"def draw_points(self, pts_x, pts_y):\n pylab.clf()\n pylab.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots the centroids of the cluster | def plot_cluster(self, centroids):
self.plot(centroids[:, 0], centroids[:, 1], labels=None, colours=['g'] * centroids.shape[1]) | [
"def plotClusters(data_points, centroids, labels):\r\n plt.scatter(data_points[:, 0], data_points[:, 1], c=labels)\r\n for i, _ in enumerate(centroids):\r\n label = \"Centroid \" + str(i)\r\n colors = [\"red\", \"green\", \"blue\"]\r\n plt.scatter(centroids[i][0], cent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots documents on the maps (similar documents clustered together | def plot_documents(self, svd, names, doc_clusters, no_clusters):
u, vt = svd
pts = vt
# each cluster gets a different colour
colormap = plt.get_cmap("hsv")
norm = matplotlib.colors.Normalize(vmin=0, vmax=no_clusters)
scalarMap = matplotlib.cm.ScalarMappable(cmap=colormap, norm=norm)
self.plo... | [
"def plot_1d_all(self, map_data):\r\n import plotly\r\n import plotly.graph_objs as go\r\n import numpy as np\r\n\r\n nx = self.reservoir.nx\r\n nc = self.physics.n_components\r\n\r\n data = []\r\n for i in range(nc - 1):\r\n data.append(go.Scatter(x=np.li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a PR curve summary op for a single binary classifier. Computes true/false positive/negative values for the given `predictions` against the ground truth `labels`, against a list of evenly distributed threshold values in `[0, 1]` of length `num_thresholds`. Each number in `predictions`, a float in `[0, 1]`, is com... | def op(
name,
labels,
predictions,
num_thresholds=None,
weights=None,
display_name=None,
description=None,
collections=None,
):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if num_thresholds is None:
num_th... | [
"def compute_roc_curve(labels, predictions, num_thresholds=None, weights=None):\n if isinstance(labels, list):\n labels = np.array(labels)\n if isinstance(predictions, list):\n predictions = np.array(predictions)\n _MINIMUM_COUNT = 1e-7\n\n if weights is None:\n weights = 1.0\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a PR curves summary protobuf from raw data values. | def raw_data_pb(
name,
true_positive_counts,
false_positive_counts,
true_negative_counts,
false_negative_counts,
precision,
recall,
num_thresholds=None,
display_name=None,
description=None,
):
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import ... | [
"def pr_curve_raw(tag, tp, fp, tn, fn, precision, recall, step, walltime):\n \"\"\"\n if isinstance(tp, np.ndarray):\n tp = tp.astype(int).tolist()\n if isinstance(fp, np.ndarray):\n fp = fp.astype(int).tolist()\n if isinstance(tn, np.ndarray):\n tn = tn.astype(int).tolist()\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get apache beam pipeline options to run with Dataflow on the cloud | def get_cloud_pipeline_options():
options = {
'runner': 'DataflowRunner',
'job_name': ('relation-extraction-{}'.format(
datetime.now().strftime('%Y%m%d%H%M%S'))),
'staging_location': "gs://relation_extraction/beam/binaries/",
'temp_location': "gs://relation_extraction/be... | [
"def pipeline_options_local(argv):\n\n from google.cloud.dataflow import Pipeline\n from google.cloud.dataflow.utils.options import PipelineOptions\n\n options = PipelineOptions(flags=argv)\n\n # [START pipeline_options_define_custom_with_help_and_default]\n class MyOptions(PipelineOptions):\n\n @classmetho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes a file track, extracting it's features | def process_track(filename):
track = Track.from_gpx(filename)[0]
track.compute_metrics()
for segment in track.segments:
features = extract_features_2(segment.points)
return features | [
"def get_features(track_id: str, sp: ...) -> ...: # TODO ***************\n features = sp.audio_features('spotify:track:' + track_id)\n return([features[0]['acousticness'], features[0]['danceability'], features[0]['energy'],\n features[0]['duration_ms'], features[0]['instrumentalness'], features[\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_capacities_and_distinct_transports method returns two dicts with values 0 for empty data | def test_get_capacities_and_distinct_transports_returns_0_for_empty_data(self):
capacities, distinct_transports = \
transport.get_capacities_and_distinct_transports(self.empty_data)
expected_capacities = {
'cars': 0,
'trains': 0,
'planes': 0
}
... | [
"def test_get_capacities_and_distinct_transports_returns_totals(self):\n capacities, distinct_transports = \\\n transport.get_capacities_and_distinct_transports(self.test_data)\n\n expected_capacities = {\n 'cars': 14,\n 'trains': 150,\n 'planes': 524\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_capacities_and_distinct_transports method returns two dicts with correct totals for example data | def test_get_capacities_and_distinct_transports_returns_totals(self):
capacities, distinct_transports = \
transport.get_capacities_and_distinct_transports(self.test_data)
expected_capacities = {
'cars': 14,
'trains': 150,
'planes': 524
}
... | [
"def test_get_capacities_and_distinct_transports_returns_0_for_empty_data(self):\n capacities, distinct_transports = \\\n transport.get_capacities_and_distinct_transports(self.empty_data)\n\n expected_capacities = {\n 'cars': 0,\n 'trains': 0,\n 'planes': 0\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the sort_values method returns a list of sets sorted by value given a dict with totals returned by get_capacities_and_distinct_transports method | def test_sort_values_returns_list_of_set_sorted_by_value(self):
sorted_capacities = transport.sort_values(self.test_capacities)
expected_capacities = [
(6, 'cars'),
(3, 'planes'),
(1, 'trains')
]
self.assertListEqual(sorted_capacities, expected_capaci... | [
"def test_get_capacities_and_distinct_transports_returns_totals(self):\n capacities, distinct_transports = \\\n transport.get_capacities_and_distinct_transports(self.test_data)\n\n expected_capacities = {\n 'cars': 14,\n 'trains': 150,\n 'planes': 524\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert list_maze to nested list | def convert_maze(self):
self.maze = [[line[i]
for i in range(len(line))] for line in self.list_line]
return 0 | [
"def generate_maze(self):\n with open(self.maze, \"r\") as file:\n global_maze = []\n # We iterate on each row contained in our file .txt\n for row in file:\n maze_row = []\n # We iretate on each sprite from rows, to create lists with each value\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out the position of IA | def get_IA_position(self, maze):
for y in range(len(maze)):
for x in range(len(maze[y])):
if maze[y][x] == self.letter:
self.posx = x
self.posy = y
break
return 0 | [
"def agent_initial_position(i: int, total: int) -> Position:\n layout_base = int(np.ceil(np.sqrt(total)))\n idx_map = np.arange(layout_base ** 2).reshape(layout_base, layout_base)\n (rows, cols) = np.where(idx_map == i)\n row, col = rows[0], cols[0]\n return Position(row, col) + (1, 1)\n # return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the resistance. It first ensures that the next measurement reading is up to date by first sending the "ADC" command. | def resistance(self):
# First make sure the mux is on the correct channel
if self._parent.mux_channel != self._idx:
self._parent.input_source = self._parent.InputSource.ground
self._parent.mux_channel = self._idx
self._parent.input_source = self._p... | [
"def __calculate_resistance(self, voltage, resistance=None):\n\n resistance = resistance if resistance else self.LOAD_RESISTANCE\n\n return float(resistance * (1023.0 - voltage) / float(voltage))",
"def read_RADC(self):\n return self._read_single_frame(FrameCode.RADC)",
"def ultrasonic_get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the value of a key from the server | def get(self, key):
socksend(self.sock, _t1(C.get, key))
socksuccess(self.sock)
return sockstr(self.sock) | [
"def get(self, key):\n\n key = str(key)\n database = self._get_database()\n return database.get(key, None)",
"def __getitem__(self, key):\n query = select([self.store.c.value]).where(self.store.c.key == key)\n result = self.conn.execute(query).fetchone()\n if result:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call func(key, value) with opts opts is a bitflag that can be RDBXOLCKREC for record locking and/or RDBXOLCKGLB for global locking | def ext(self, func, opts, key, value):
# tcrdbext opts are RDBXOLCKREC, RDBXOLCKGLB
socksend(self.sock, _t3F(C.ext, func, opts, key, value))
socksuccess(self.sock)
return sockstr(self.sock) | [
"def _lock_and_transform(func):\n\n @wraps(func)\n def wrapper(self, key):\n with self._lock:\n return func(self, _transform_key(key))\n\n return wrapper",
"def wrapper(*args, **kwargs):\n key = wrapper.__cache_key__(*args, **kwargs)\n result = g.cache.get(key, ENO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate the position of a player against a location for now we have only a sphere and cube next will be rooms, then polygons for more exotic bases. the goal is to use exactly the space one needs instead of arbitrary shapes dictated by my lack of mathskills! | def player_is_inside_boundary(self, player_object):
player_is_inside_boundary = False
if self.shape == "sphere":
""" we determine the location by the locations radius and the distance of the player from it's center,
spheres make this especially easy, so I picked them first ^^
... | [
"def calculate_chemistry_position(player_pos, squad_pos):\n chemistry_position = 0\n pos_points = [1, 2, 3]\n if player_pos == squad_pos:\n chemistry_position = pos_points[2]\n return chemistry_position\n if squad_pos == \"LWB\" and player_pos == \"LB\":\n chemistry_position = pos_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(TESTED AND WORKS) Adds new followers activities to user's feed | def add_new_follower_latest_activities(cls, user_id, to_follow_id):
payload = {'user_id': user_id, 'to_follow_id': to_follow_id}
response = requests.get('http://localhost:6543/add_new_follower_acts', params=payload)
json_response = json.loads(response.text)
activities = json_response['a... | [
"def follow_user(user_id, follower_id):\n added = add_follower(user_id, follower_id)\n all_activities_key = \"activities:%s\" % (user_id,)\n\n if not added:\n return\n\n redis_connection = redis.StrictRedis(\n host='localhost', port=6379, db=REDIS_DB, decode_responses=True)\n\n retries ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulls out song name from file path, strips disc/track numbers and file extension. IN | def song_name_extractor(file_link):
# first pattern takes everything between last / and .ext
p1 = re.compile(r"/([^/]+)\.\w{3}")
# next takes everything after track/disc number and whitespace
p2 = re.compile(r"[\d-]*\s(.+)")
# testing both cases
step1 = p1.search(file_link)
if step1:
... | [
"def songCleaner(filename):\r\n \"\"\"NOTE: For now, you need to manually remove lyrics, alternate versions,\r\n \"variations\", and anything else that comes after the body of\r\n the song! \"\"\"\r\n # Be careful that the first song starts at the top of the file!\r\n file1 = open(filename, '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Feeds each song in queue directory to the chunk_song() function. IN | def chunk_queue(dir_in="../audio/chunk_queue",
dir_out="../audio/wav_chunked",
chunk_len=5,
sr=22050,
log=True
):
for root, dirs, files in os.walk(dir_in):
for fname in files:
if not re.match(r'^\.', fname):
... | [
"def queue_callback(self):\n selected_song, index = self._player.selected_song()\n response = requests.get('http://localhost:5000/song/' + selected_song)\n song_object = response.json()\n media_file = song_object['pathname']\n media_file = media_file.replace('/', '\\\\')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts all .wav files in a directory to .mp3 with bitrate specified. Checks destination directory to see if file has been converted already. IN | def wav_to_mp3_batch(dir_in,
dir_out="../audio/mp3_chunked",
bitrate=96
):
existing = set()
bitrate = str(bitrate)
for mp3_fpath in glob(dir_out + "/*.mp3"):
f_id = os.path.splitext(os.path.basename(mp3_fpath))[0]
existing.a... | [
"def wav2mp3(wavfile, mp3file, bitrate=128):\n cmd = \"sox -c 1 %s -C %d %s\" % (wavfile, bitrate, mp3file)\n subprocess.call(cmd.split(\" \"))",
"def mp3_to_wav(self, pathname):\n if self.folder_method == 'folder':\n label_list = open(self.out_folder + '/' + 'labels.txt', 'w')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints labeled status of samples in Mongo DB, adds a status record to a separate status DB. | def db_status():
db = kdb.test_songs
# pull last record from status DB for comparison
last = kdb.status.find_one({"last": True})
labels = [
("Total samples\t", 'total'),
("Labeled samples\t", 'labeled'),
("Skipped samples\t", 'skipped'),
("Vocals, foregroun... | [
"def add_to_mongodb(self, status):\r\n try:\r\n insert = self.mongo_coll_tweets.insert_one(status._json)\r\n insert_it = insert.inserted_id\r\n self.media_download(insert_id)\r\n self.counter += 1\r\n except errors.ServerSelectionTimeoutError:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a datagroup in db by randomly sampling an equal number from records where the positive label has a value of 2 (foreground) and records where the positive label has a value of 2 (none). IN | def create_datagroup_in_db(group_name, pos_label, n_per_label='auto'):
assert_msg = "Invalid input for n_per_label"
assert n_per_label == 'auto' or type(n_per_label) == int, assert_msg
pos_ids = np.array([])
neg_ids = np.array([])
if n_per_label == 'auto':
n_per_label = kdb.test_songs.fin... | [
"def create(self, **kwargs):\r\n new_id = str(self.group_counter.next())\r\n fsg = FakeScalingGroup(new_id, **kwargs)\r\n self.groups[new_id] = fsg\r\n return fsg",
"def StratifiedSample(data, nperlabel):\n sample = pd.DataFrame()\n datagrp = data.groupby('label')\n sortedgrp ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulls datagroup from Mongo DB, returns a list of chunk_id, label tuples. IN | def pull_datagroup_from_db(group_name, df=True):
datagroup = []
for item in kdb.test_songs.find({group_name: {"$exists": True}}):
datagroup.append((item['chunk_id'], item[group_name]))
if df:
dg_trans = list(zip(*datagroup))
datagroup = pd.DataFrame({
'chunk_id': d... | [
"def create_datagroup_in_db(group_name, pos_label, n_per_label='auto'):\n\n assert_msg = \"Invalid input for n_per_label\"\n assert n_per_label == 'auto' or type(n_per_label) == int, assert_msg\n\n pos_ids = np.array([])\n neg_ids = np.array([])\n\n if n_per_label == 'auto':\n n_per_label = kd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
OBSOLETE, USE create_datagroup_in_db(), pull_datagroup_from_db(), and tts() instead Creates dataset labels in MongoDB under provided round name. First pass only deals with two labels; future versions will accommodate more as necessary. IN | def tts_full(
round_name,
train_size=0.8,
n_labels=2,
n_per_label='auto',
pos_label='sax'
):
pos_ids = np.array([])
neg_ids = np.array([])
if n_per_label == 'auto':
n_per_label = kdb.test_songs.find({pos_label: 2}).count()
# find cutoff index val... | [
"def create_datagroup_in_db(group_name, pos_label, n_per_label='auto'):\n\n assert_msg = \"Invalid input for n_per_label\"\n assert n_per_label == 'auto' or type(n_per_label) == int, assert_msg\n\n pos_ids = np.array([])\n neg_ids = np.array([])\n\n if n_per_label == 'auto':\n n_per_label = kd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make spectrograms out of all audio files in given directory for which spectrograms do not exist in out directory. IN | def batch_spectros(
dir_in="../audio/wav_chunked",
dir_out="../specs/mel",
files='labeled',
sample_rate=22050,
hl=256,
n_fft=1024,
n_mels=512,
normalize=False
):
assert_msg = "Error: files arg must be either 'all' or 'labeled'"
assert files ==... | [
"def analyse_multiple_audio_files(context, source_path, dest_path):\n context.obj[\"dest_path\"] = dest_path\n for file in os.listdir(source_path):\n file_path = os.path.join(file)\n context.invoke(\n generate_spectrograms,\n source_path=os.path.join(source_path, file_path)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints basic stats for any np array. IN | def arr_stats(ndarray):
print("Min:", np.min(ndarray))
print("Max:", np.max(ndarray))
print("Mean:", np.mean(ndarray))
print("Std:", np.std(ndarray))
print("Shape:", np.shape(ndarray)) | [
"def print_stats( slopes, cr_total):\n\n wh_slope_0 = np.where( slopes == 0.) # insuff data or no signal\n for ii in range( cr_total.max()+1 ): \n cr_ii = np.where( cr_total == ii )\n print 'The number of pixels in 2d array having ' , ii,\\\n ' crs : ' , len(cr_ii[0])\n\n print 'Th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The beginnings of a grand function for making and storing a spectrogram for each file using librosa. | def make_spectro_old(
fname,
sample_rate=22050,
n_fft=1024,
hl=256,
n_mels=512,
cmap='magma',
show=True,
save=False
):
# update this with os.path.join()
fpath = "../audio/" + fname + ".wav"
y, sr = librosa.load(fpath,
... | [
"def save_spectrogram_tisv():\n print(\"start text independent utterance feature extraction\")\n os.makedirs(hp.data.train_path, exist_ok=True) # make folder to save train file\n os.makedirs(hp.data.test_path, exist_ok=True) # make folder to save test file\n\n utter_min_len = (hp.data.tisv_frame * ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary to compare against a funding source. | def get_funding_source_verify(self, funding_source):
verify = funding_source.__dict__['json_response']
del verify['created_time']
del verify['last_modified_time']
del verify['date_sent_for_verification']
return verify | [
"def prevalence_G_dict(self):\n ret = {}\n for finding in self.findings:\n if(self.isCountry(finding[0])):\n ret[finding[0]] = finding[1]\n return ret",
"def get_base_sourcedict(payload, sample, name):\n sourcedict = {}\n sourcedict[\"_event\"] = 1 if is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies the ach account with the correct verification amounts. | def test_ach_save_success(self):
funding_source = FundingSources.get_user_ach_funding_source()
amounts = self.client.funding_sources.ach(
funding_source.token).verification_amounts()
ach_verification = {
"verify_amount1": amounts.verify_amount1,
"verify_amo... | [
"def test_account_verified(self):\n user = User.objects.get()\n token, uid = RegistrationAPIView.send_account_activation_email(user=user, send_email=False)\n response = self.verify_account(token, uid)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n user = User.obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to verify the ach account with incorrect verification amounts. | def test_ach_save_fail(self):
funding_source = FundingSources.get_user_ach_funding_source()
amounts = self.client.funding_sources.ach(
funding_source.token).verification_amounts()
ach_verification = {
"verify_amount1": amounts.verify_amount1 + 0.01,
"verify... | [
"def test_ach_save_success(self):\n\n funding_source = FundingSources.get_user_ach_funding_source()\n\n amounts = self.client.funding_sources.ach(\n funding_source.token).verification_amounts()\n\n ach_verification = {\n \"verify_amount1\": amounts.verify_amount1,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies behavior when the funding source cannot be found. | def test_ach_save_unknown_source(self):
ach_verification = {
"verify_amount1": 0.01,
"verify_amount2": 0.01
}
with self.assertRaises(MarqetaError):
self.client.funding_sources.ach.save(
'Not a funding source token', ach_verification) | [
"def test_download_with_unreachable_source(self, gcp_provider):\n gcp_provider.return_value.cost_usage_source_is_reachable.side_effect = ValidationError\n billing_source = {\"table_id\": FAKE.slug(), \"dataset\": FAKE.slug()}\n credentials = {\"project_id\": FAKE.slug()}\n with self.asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getting tweets from twitter live stream api. | def get_tweets(auth):
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
query_data = [('language', 'en'), ('locations', '-130,-20,100,50'), ('track', '#')]
query_url = url + '?' + '&'.join([str(t[0]) + '='+str(t[1]) for t in query_data])
res = requests.get(query_url, auth=auth, stream=True)
... | [
"def get_tweets(self):\n try:\n self.response = get(self.query_url, auth=AUTH, stream=True)\n print(self.query_url, self.response)\n return self.response\n except exceptions.HTTPError as e:\n print(\"Response error:\", e)\n exit(1)",
"def do_twe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sending twitter stream response to pySpark stream. | def send_tweets_to_spark(http_resp, tcp_connection, t_in_sec):
end_time = time.time()+t_in_sec
for line in http_resp.iter_lines():
if time.time() >= end_time:
break
try:
full_tweet = json.loads(line)
data_dict = {
'created_at': full_tweet['crea... | [
"def send_tweets_to_spark(self, client_sock):\n num_tweets = 0\n for line in self.response.iter_lines():\n if not line.decode('utf-8'):\n continue\n try:\n full_tweet = json.loads(line.decode('utf-8'))\n if 'text' in full_tweet:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
configuring a spark stream using TCP socket. | def create_socket():
tcp_ip = SparkStream.TCP_IP.value
tcp_port = SparkStream.TCP_PORT.value
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((tcp_ip, tcp_port))
s.listen(1)
print("Waiting for tcp connection... ")
conn, address = s.accept()
print("current address is", address... | [
"def create_socket(self):\n super(TCPSocket, self).create_socket()\n self.adjust_buffers()",
"def connect_stream(stream):\n return factory.connect_stream(stream, SlaveService)",
"def __init__(self, address=DEFAULT_CLIENT_ADDRESS, port=DEFAULT_TCP_PORT):\n binding = 'tcp://*:{}'.format(po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a cycle of `num_chunks` chunks from `array`. if repeat is False, generates one cycle only. | def chunk_generator(array, num_chunks, repeat=True):
chunk_len = int(np.ceil(len(array) / num_chunks))
array_iter = iter(array)
while True:
subset = tuple(itertools.islice(array_iter, chunk_len))
if len(subset) > 0:
yield subset
elif repeat:
array_iter = iter(array)
else:
return | [
"def repeat_or_chunk(data, chunk_size):\n if len(data) < chunk_size:\n repeats = chunk_size // len(data)\n if (repeats * len(data)) != chunk_size:\n logging.info('skipping something that does not divide four bars')\n data = []\n else:\n data = list(data) * re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get next round of testing subjects. | def next_round(self):
testing_round = []
if self.schedule[self.day]:
testing_round = next(self._tested_chunks)
self.day = (self.day + 1) % len(self.schedule)
return testing_round | [
"def next_trial(self):\n next_trial = None\n if self._challenger_list:\n next_trial = self._challenger_list.pop()\n return next_trial",
"def next_trial(self):\n try:\n trial = next(self.trial_iter)\n except StopIteration:\n return None\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests node given test sensitivity and specificity. | def test_state(node_state, sensitivity=1., specificity=1.,):
if node_state == "I":
# Patient is positive, true positive rate is sensitivity
positive = 1 == np.random.binomial(1, sensitivity)
else:
# Patient is negative, false positive rate is 1 - specificity
positive = 1 == np.random.binomial(1, 1 - spe... | [
"def visitCase(self, testCase):",
"def test_binary_decision_function(*args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def test_run_feature_selection(self):",
"def test_002_ironic_node_actions(self):\n # Step 1\n fail_msg = \"Error creating node.\"\n self.node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a simple plot of the SIR curve | def plot_SIR(S, I, R):
plt.figure()
plt.plot(S, label="S")
plt.plot(I, label="I")
plt.plot(R, label="R")
plt.legend()
plt.show() | [
"def signal_plot(t, y, **kwargs):\n\n\n fun = kwargs['vin']\n\n plt.figure(figsize=kwargs['figsize'])\n (plt.plot(t, fun(t), 'r', linewidth = 2, label = 'Input'),\n plt.plot(t, y[1].T, 'b', linewidth = 2, label = \"Out \"),\n plt.plot(t, y[0].T*0.2, 'orange', linewidth = 2, label = 'Change in S (Scal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot SIR curves and their average. and show each infection curve on the plot too. | def plot_averaged_SIRs(SIRs,
max_t=None,
lines_to_plot="IR",
means_to_plot="SIR",
figname="SIRs.png",
figtitle=None,
show_plot=False,
save_data=False):
compartments = ("S", "I", "R")
colors = {"S": u'#1f77b4', "I": u'#ff7f0e', "R": u'#2ca02c'}
if ... | [
"def plot_SIR(S, I, R):\r\n\tplt.figure()\r\n\tplt.plot(S, label=\"S\")\r\n\tplt.plot(I, label=\"I\")\r\n\tplt.plot(R, label=\"R\")\r\n\tplt.legend()\r\n\tplt.show()",
"def Emergent_IntensityPlot():\n\tI_comp , mean = Emergent_Intensity()\n\n\tplt.title(\"Observed and computed continuum intensity\")\n\tplt.plot(w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Repeats an outbreak simulation given its config. | def repeat_simulation(sim_config={},
num_sim=100,
parallel=None):
# Define simulation task based on given config.
# This will return a function `sim(sim_id)` that takes an identifier.
sim = functools.partial(outbreak_simulation, **sim_config)
sim_ids = list(range(num_sim))
# Run simulatio... | [
"def cycle(self, outlet, expectation=True):\n outlet_state = self.state\n result = ReturnCode(True)\n outlet = str(outlet)\n logger.info(\"cycle %s\" % outlet)\n self.send(\"1\")\n self.expect(\"Control Sub Menu\")\n self.send(\"1\")\n self.expect(\"Outlet Sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes all flashcards of given Note object and then deletes given Note object itself. | def delete_note(self, note:Note):
if note:
# Delete card(s) of given note
for card in note.flashcards:
db.session.delete(card)
db.session.commit()
# Delete note
if self.user_id == current_user.id:
db.session.delete(... | [
"def delete_cards(self):\n self._stage = []\n self._hand = []",
"def delete_all_objects_and_materials():\n # select all objects and delete them\n bpy.ops.object.select_all(action='SELECT')\n bpy.ops.object.delete(use_global=False, confirm=False)\n # delete all physics bakes\n bpy.ops.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter the provided entries. | def _filter_entries(self,
entries: List[VICEmergencyIncidentsFeedEntry]) \
-> List[VICEmergencyIncidentsFeedEntry]:
filtered_entries = super()._filter_entries(entries)
if self._filter_inc_categories:
filtered_entries = list(filter(lambda entry:
... | [
"def _filter_entries(self, entries: List[FeedEntry]) -> List[FeedEntry]:\n filtered_entries = entries\n if self._apply_filters:\n # Always remove entries without coordinates.\n filtered_entries = list(\n filter(\n lambda entry: (entry.coordinates... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract global metadata from feed. | def _extract_from_feed(self, feed: FeatureCollection) -> Optional[Dict]:
return None | [
"def iter_feed_metadata(\n self, feed: Union[str, Feed]\n ) -> Iterable[Tuple[str, JSONType]]:\n feed_url = feed_argument(feed)\n return self._storage.iter_feed_metadata(feed_url)",
"def get_feed_metadata(\n self,\n feed: FeedInput,\n key: Optional[str] = None,\n ) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a nhentai url to its digit. | def parse_to_n_digit(url: str) -> Optional[str]:
n_digit_match = re.search('([1-9][0-9]*)', url)
return n_digit_match.group(1) if n_digit_match is not None else None | [
"def parseURI(self,url):\n addr = \"\"\n parts = []\n ip = False\n parts = url.split('/')\n #extract ip address with port\n if(len(parts)>2):\n addr = parts[2] #this contains X.X.X.X:PORT\n else:\n addr = parts[0] #it is possible the mtURL i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True when at top of game board. | def at_top(self) -> bool:
return self.ycor() >= self.max_top | [
"def is_top(self) -> bool:\n return self.timestamp.is_top",
"def is_top_block(self):\n return self._parent_block is None",
"def is_at_home(self):\n return self.position == self.home_position",
"def _on_board(self, point):\n return self.board[point]!= BORDER",
"def make_top(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the ball and paddle are close enough on the game board for us to say they have collided. | def collides(self, paddle: Paddle) -> bool:
x_ball = self.xcor()
if abs(x_ball - paddle.xcor()) < 12:
y_ball = self.ycor()
if y_ball < paddle.top and y_ball > paddle.bottom:
if x_ball < 0 and x_ball >= paddle.xcor():
return True
... | [
"def collide_paddle(self):\n # just check the bottom side of the ball\n if self.obj3() == self.paddle or self.obj4() == self.paddle:\n return True",
"def has_ball_moved(self, ball_1, ball_2):\r\n dist = dist_between_two_balls(ball_1, ball_2)\r\n if not self.white_is_moving:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function finds the lowest score of two shredded images. It does so by finding the score by aligning them one way and then the other. The lowest one is then returned as a tuple with the score, orientation, and image | def findCurrScore(image1, image2):
scoreleft = Score(calculateScore(image1, image2), True, image2)
scoreright = Score(calculateScore(image2, image1), False, image2)
currminscore = None
if (scoreleft.score < scoreright.score):
currminscore = scoreleft
else:
currminscore = scoreright
return currminscore | [
"def calculateScore(image1, image2):\n\timage1col = image1[-1]\n\timage2col = image2[0]\n\n\ttuples = zip(image1col, image2col)\n\n\tscore = 0\n\tfor pixel1, pixel2 in tuples:\n\t\tscore += comparePixels(pixel1, pixel2)\n\n\treturn score",
"def my_best_align(s1, s2):\n s1, s2, l1, l2 = set_variables(s1, s2) #c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the score of putting image1 on the left of image 2. It does so by going pixel by pixel in the farthest column and summing the differences of each pixels. It returns the score. | def calculateScore(image1, image2):
image1col = image1[-1]
image2col = image2[0]
tuples = zip(image1col, image2col)
score = 0
for pixel1, pixel2 in tuples:
score += comparePixels(pixel1, pixel2)
return score | [
"def findCurrScore(image1, image2):\n\tscoreleft = Score(calculateScore(image1, image2), True, image2)\n\tscoreright = Score(calculateScore(image2, image1), False, image2)\n\n\tcurrminscore = None\n\tif (scoreleft.score < scoreright.score):\n\t\tcurrminscore = scoreleft\n\telse:\n\t\tcurrminscore = scoreright\n\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the difference between two pixels by summing the squares of the differences of the different components, R,G,B, and A. It returns the total difference. | def comparePixels(pixel1, pixel2):
total = 0
total += (pixel1.red - pixel2.red)**2
total += (pixel1.green - pixel2.green)**2
total += (pixel1.blue - pixel2.blue)**2
total += (pixel1.alpha - pixel2.alpha)**2
return total | [
"def __calculate_pixel_difference(self, pixel1, pixel2):\n return sum( [ (math.log(color1 / 255.0 + 1.0 / 255) - \n math.log(color2 / 255.0 + 1.0 / 255)) ** 2 \n for color1, color2 in zip(pixel1, pixel2) ])\n # This algorithm is not working as properly.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes two images and an orientation and returns the two images put together. It does so by manually manipulating the data and appending the data from the right image to the one on the left. Returns the final merged image. | def merge(image1, image2, onleft):
if not onleft:
return merge(image2, image1, True)
finalimage = image1
for col in image2:
finalimage.append(col)
return finalimage | [
"def merge_images_side_by_side(image1, image2):\n (width1, height1) = image1.size\n (width2, height2) = image2.size\n\n result_width = width1 + width2\n result_height = max(height1, height2)\n\n result = Image.new('RGB', (result_width, result_height))\n result.paste(im=image1, box=(0, 0))\n res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a Beautiful Soup object from markup. | def soup(self, markup, **kwargs):
... | [
"def build_soup(url):\n # query the website and return the html to the variable 'page'\n page = requests.get(url)\n # parse the html using beautiful soup and store in variable 'soup'\n return BeautifulSoup(page.content, \"html.parser\")",
"def parse(self, beautiful_html):\n return beautiful_htm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that all HTML4 and HTML5 empty element (aka void element) tags are handled correctly. | def test_empty_element_tags(self):
... | [
"def testBasicTagAbsence(self):\n template = '{{ ifpresent [tag] }} hello {{ endif }}'\n self.assertFalse(self.parse(template))",
"def test_simple_complete_html_start_tag_with_no_attributes():\n\n # Arrange\n input_tag_name = \"a\"\n string_to_parse = \">\"\n parse_index = 0\n expected_is_val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that a given doctype string is handled correctly. | def assertDoctypeHandled(self, doctype_fragment):
... | [
"def doctype(self, irc, msg, args, url):\n size = conf.supybot.protocols.http.peekSize()\n s = utils.web.getUrl(url, size=size)\n m = self._doctypeRe.search(s)\n if m:\n s = utils.str.normalizeWhitespace(m.group(0))\n irc.reply(s)\n else:\n irc.rep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A real XHTML document should come out more or less the same as it went in. | def test_real_xhtml_document(self):
... | [
"def Xtest_strip_doctypehtml(self):\n inp = '''Something\n <body>\n Result\n </body>\n Else\n '''\n doc = self.folder.index_html\n res = doc._strip_doctypehtml(inp)\n assert res.strip() == 'Result'\n \n # a failing piece of HTML\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When a namespaced XML document is parsed as HTML it should be treated as HTML with weird tag names. | def test_namespaced_html(self):
... | [
"def has_html_ns(el: bs4.Tag) -> bool:\n\n ns = getattr(el, 'namespace') if el else None\n return bool(ns and ns == NS_XHTML)",
"def supports_namespaces(self) -> bool:\n\n return self.is_xml or self.has_html_namespace",
"def xmls_to_etree(xml_input):\n return etree.HTML(xml_input)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A tag that's not closed by the end of the document should be closed. This applies to all tags except emptyelement tags. | def test_unclosed_tags_get_closed(self):
... | [
"def close(self, tag):\n return \"</{}>\".format(self.tags[tag].split(\" \", 1)[0])",
"def handle_endtag(self, tag) -> None:\n if tag in self.keeptags:\n self.textdata += f'</{tag}>'",
"def __create_closing_html_tag(self, tag):\n\n tag = tag.replace('<', '</')\n if tag.cou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inline elements can be nested indefinitely. | def test_nested_inline_elements(self):
... | [
"def test_block_in_inline():\r\n box = parse('''\r\n<style>\r\n p { display: inline-block; }\r\n span, i { display: block; }\r\n</style>\r\n<p>Lorem <em>ipsum <strong>dolor <span>sit</span>\r\n <span>amet,</span></strong><span><em>conse<i></i></em></span></em></p>''')\r\n box = build.inline_in_block(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Block elements can be nested. | def test_nested_block_level_elements(self):
... | [
"def is_nested(self, ):\n\t\tpass",
"def wrap_nested(self):\n for i in range(self.n_blocks):\n block = self.GetBlock(i)\n if not is_pyvista_dataset(block):\n self.SetBlock(i, wrap(block))",
"def parseBlock(self, block):\n\t\tcontainer = Container()\n\t\tif container.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One table can go inside another one. | def test_correctly_nested_tables(self):
... | [
"def table_mother_not_concordant():\n pass",
"def table_father_not_concordant():\n pass",
"def visit_table(self, table):\n pass",
"def changeSubTable(self, subtable):\n\t\tself.nt = NetworkTables.getTable(\"SmartDashboard/\" + subtable)",
"def create_as_another_table(self, node=None):\n user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify consistent handling of emptyelement tags, no matter how they come in through the markup. | def test_empty_element_tags(self):
... | [
"def testBasicTagAbsence(self):\n template = '{{ ifpresent [tag] }} hello {{ endif }}'\n self.assertFalse(self.parse(template))",
"def strip_empty_tags(self):\n tag = self.root\n while True:\n next_tag = tag.findNext(True)\n if not next_tag: break\n if next_tag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A real XHTML document should come out exactly the same as it went in. | def test_real_xhtml_document(self):
... | [
"def Xtest_strip_doctypehtml(self):\n inp = '''Something\n <body>\n Result\n </body>\n Else\n '''\n doc = self.folder.index_html\n res = doc._strip_doctypehtml(inp)\n assert res.strip() == 'Result'\n \n # a failing piece of HTML\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A large XML document should come out the same as it went in. | def test_large_xml_document(self):
... | [
"def has_30k_or_fewer_records(medline_xml, parser=None, tree=None):",
"def testParseContent(self):\n # XXX not sure it is good to store parsed document everytime\n self.assertTrue(isinstance(self.oodocument.parsed_content, etree._Element))\n self.assertTrue(self.oodocument.parsed_content.tag.endswith(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Worker function for doing FVA with multiprocessing. For use as a target of multiprocessing.Process. Each entry in job_queue should be a string giving a variable in the model (or None, as a termination signal). The corresponding entry of | def _fva_worker(model, job_queue, result_queue, guess):
done = 0
while True:
try:
key = job_queue.get(timeout=3600)
except Empty:
print 'FVA worker finishing anomalously after completing %d tasks' % done
return
if key is None:
print 'F... | [
"def do_fva(model, variables=None, guess=None,\n n_procs=default_n_parallel_procs, cache={},\n check_failures=True, log_interval=100, log_filename=None):\n if log_filename:\n logger = logging.getLogger(log_filename)\n logger.setLevel(logging.INFO)\n fh = logging.FileHand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Minimize/maximize (serially) variables in model. The model's existing upper/lower bounds are preserved, and the existing objective function will be restored after FVA completes. If variables is None, use all variables in the model. If cache is given, tuples of extrema will be taken from the cache instead of recalculate... | def do_fva(model, variables=None, guess=None,
n_procs=default_n_parallel_procs, cache={},
check_failures=True, log_interval=100, log_filename=None):
if log_filename:
logger = logging.getLogger(log_filename)
logger.setLevel(logging.INFO)
fh = logging.FileHandler(filenam... | [
"def local_search(self, max_variables):\n assignments = self.assignments.copy()\n\n best_var = None\n best_improvement = 0\n\n for _ in range (0, max_variables):\n for var in range(0, self.cnf.num_variables):\n self.assignments[:,var] = 1-self.assignments[:,var]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that initialises a maze with a number of larger rooms, halls. A number of attempts to generate overlapping rooms in the maze are made. If the larger room is fully inside the maze, and all rooms from which it is created are nonflagged, the walls of all rooms, except walls leading out of the larger room, will ... | def initialize(maze, randomizer, attempts = 20, max_width = None,
max_height = None):
max_width = max_width or maze.width // 3
max_height = max_height or maze.height // 3
def rooms(x, y, width, height):
"""Yields all rooms in the given hall.
"""
for i in range(width):
... | [
"def generate_rooms():\n total_rooms_cnt = random.randrange(min_rooms_cnt,max_rooms_cnt) # generate max number of rooms randomly\n for i in range(total_rooms_cnt):\n r,c = random.randrange(0,cell_width), random.randrange(0,cell_length)\n width, length = random.randrange(min_room_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields all rooms in the given hall. | def rooms(x, y, width, height):
for i in range(width):
for j in range(height):
room_pos = (x + i, y + j)
if room_pos in maze:
yield room_pos | [
"def _get_all_rooms(klass, floor):\n unidentified_rooms = floor.get(\"unidentified_rooms\", [])\n unidentified_rooms = (\n (None, room) for room in unidentified_rooms )\n rooms = floor.get(\"rooms\", {})\n room_items = (\n (rid, room) for rid, room in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all walls surrounding a hall. | def walls(x, y, width, height):
def inside(wall):
if wall.room_pos[0] < x or wall.room_pos[0] >= x + width:
return False
if wall.room_pos[1] < y or wall.room_pos[1] >= y + height:
return False
return True
result = []
for i in r... | [
"def getRoomWalls(self):\n return self.tile_holder[0].getTileWalls()",
"def walls(self):",
"def get_walls_positions(self):\n walls_positions = []\n for y, line in enumerate(self.lines_list):\n for x, char in enumerate(line):\n if char == \"W\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove C style comments from input string | def remove_c_comments(string):
string_pattern = r"(?P<string>\".*?\"|\'.*?\')"
comment_pattern = r"(?P<comment>/\*.*?\*/|//[^\r\n]*$)"
pattern = re.compile(string_pattern + r'|' + comment_pattern,
re.MULTILINE | re.DOTALL)
def replacer(match):
if match.lastgroup == 'com... | [
"def clean_comment(comment):\n return comment.strip(\"# \")",
"def _remove_comments(source):\n comment_re = r'(/[*].*?[*]/)|(//[^\\n]*)'\n return re.sub(comment_re, '', source, flags=re.MULTILINE | re.DOTALL)",
"def remove_comments(source):\n return re.sub(r'#[^#\\n]+', '', source)",
"def remo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple preprocessor for C source code. Only processes condition directives without expanding them. Yield object according to the classes input. Most match firstly If the directive pair does not match , raise CondDirectiveNotMatch. Assume source code does not include comments and compile pass. | def preprocess_c_source_code(source, *classes):
pattern = re.compile(r"^[ \t]*#[ \t]*" +
r"(?P<directive>(if[ \t]|ifndef[ \t]|ifdef[ \t]|else|endif))" +
r"[ \t]*(?P<param>(.*\\\n)*.*$)",
re.MULTILINE)
stack = []
def _yield_objects(... | [
"def preprocess( self, source ):\n\n\t\t# open file\n\t\tfiles = []\n\t\tfiles.append( open( source ) )\n\n\t\t# Output\n\t\tlines = []\n\t\t\n\t\t# depth and value of conditional directives\n\t\tskip = [ False ]\n\t\t\n\t\t# whilst there are still files to preprocess\n\t\twhile len( files ) > 0:\n\t\t\t\n\t\t\twhi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function performs scaling on the retrieved CSI data to account for automatic gain control and other factors. Code within this section is largely based on the Linux 802.11n CSI Tool's MATLAB implementation (get_scaled_csi.m). | def scale_csi_entry(csi: np.array, header: list) -> np.array:
n_rx = header[3]
n_tx = header[4]
rssi_a = header[5]
rssi_b = header[6]
rssi_c = header[7]
noise = header[8]
agc = header[9]
#Calculate the scale factor between normalized CSI and RS... | [
"def ikHandleDisplayScale():\n pass",
"def scale_data(data,mins,maxs,targ_mins,targ_maxs,scale_prop):\n channels = data[0].shape[1]\n \n # calculate scale and shift\n if scale_prop==\"global\":\n # scales channel to global min/max\n glob_max = maxs.max()\n glob_min = mins.min()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns extent of gateways (parameter gtws). | def get_extent(gtws):
minx = float("inf")
miny = float("inf")
maxx = float("-inf")
maxy = float("-inf")
for gtw in gtws:
if gtws[gtw][0] < minx:
minx = gtws[gtw][0]
if gtws[gtw][0] > maxx:
maxx = gtws[gtw][0]
if gtws[gtw][1] < miny:
miny ... | [
"def _get_extent(inp):\n d = inp.dimensions\n return [0, d[0]-1, 0, d[1]-1, 0, d[2]-1]",
"def get_extent(y, x):\n dy = y[1] - y[0]\n dx = x[1] - x[0]\n extent = [x[0] - 0.5 * dx, x[-1] + 0.5 * dx, y[-1] + 0.5 * dy, y[0] - 0.5 * dy]\n return extent",
"def extent(self):\n cos = np.cos(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns best suiting pixel according to timestamps (gtts) and positions of gateways (gtws). | def get_position(gtws, gtts):
minx, miny, maxx, maxy = get_extent(gtws)
cellsize = 50
rows = int((maxy - miny) / cellsize) + 1 # +1 to cover whole area
cols = int((maxx - minx) / cellsize) + 1 # +1 to cover whole area
difference = float("inf")
bestx = 0
besty = 0
for row in range(ro... | [
"def find_closest_image(self, img, imtype): \n obstime = datetime.datetime.strptime('%s-%s-%s %s' % ('2015', '01', '23', self.obs_dict[img][3]), '%Y-%m-%d %H:%M:%S')\n if obstime.hour < 12: ot = obstime + datetime.timedelta(days=1)\n keys = self.obs_dict.keys()\n keys.sort()\n bes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will find a solution for the the customer based on a target price and the list of items previously set Intended to use self.target_price but this can be ovveridden | def make_suggestion(self, price_target=None):
if price_target is None:
price_target = self.target_price
elif _check_money(price_target):
price_target = Decimal(str(price_target))
else:
raise UserWarning("Bad price Target: %s!" % (price_target,))
if pr... | [
"def _match_item(self,item):\n\n\t\t#get all items for merchant\n\t\tmerchant_items=yield self._get_merchant_items(item.merchant[\"merchantId\"])\n\t\n\t\t#filter out items that do not have a propoer merchantItemId\n\t\tmerchant_items=[it for it in merchant_items if it.merchantItemId is not None and it.merchantItem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upgrade a (possibly old) state dict for new versions of fairseq. | def upgrade_state_dict(self, state_dict):
return state_dict | [
"def upgrade_state_dict_named(self, state_dict, name):\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n weights_key = \"{}.embed_positions.weights\".format(name)\n if weights_key in state_dict:\n del state_dict[weights_key]\n state_dict[\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates initials for a person's or organization's name. Name can be a string or list. If inputted as a list, input names in desired order of initials, such as [first, last]. If an element of that list has multiple names (e.g. a middle name or multiple last names), those names will also be taken into account. | def generate_initials(name, max_initials=2):
if not name:
return None
if isinstance(name, str):
name_split = name.split(' ', max(max_initials - 1, -1))
name_split.insert(0, '_recursive')
initials = generate_initials(name_split, max_initials)
elif isinstance(name, list):
... | [
"def get_initials(fullname):\r\n # TODO your code here\r\n # Make name uppercase\r\n names = fullname.upper()\r\n # Separate into different words\r\n names = names.split()\r\n initials = \"\"\r\n for name in names:\r\n initials += name[0]\r\n return initials",
"def initials(self) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an even shorter short UUID generated by the shortuuid library. | def shorter_uuid(length=7, starter=None, with_original=False):
original_id = str(shortuuid.uuid()) if starter is None else starter
n = len(original_id)
dx = min(length, len(original_id)) # ID length
if starter is not None and len(starter) < dx * 2:
original_id = str(shortuuid.uuid())
start... | [
"def new_uuid(length=25):\n letters = [random.choice(string.hexdigits) for _ in range(length)]\n return ''.join(letters).lower()",
"def get_uuid():\n return str(UUID(int=random.randint(0, 2**128 - 1))) # nosec",
"def gen_uuid():\n return str(uuid.uuid1().hex)",
"def _gen_uuid(self):\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches the system path looking for pttransport.dll. Returns the name of any directory containing it. Returns "" if none found | def is_pttrans_on_path():
for i in os.environ["PATH"].split(";"):
# Fix up msys style paths
if i[0] == "/":
i = i[1] + ":" + i[2:]
# Ignore the current directory, if people happen to have that on their path
if i == ".":
continue
# Get the c... | [
"def find_path():\n if sys.platform == \"linux2\" or sys.platform == \"linux\":\n extension = \".so\"\n elif sys.platform == \"darwin\":\n extension = \".dylib\"\n elif sys.platform == \"win32\":\n extension = \".dll\"\n else:\n print(\"Unknown system type!\")\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sleeps for the specified amount of time while keeping odometry uptodate | def sleep(self, time_in_sec):
start = self.time.time()
while True:
state = self.create.update()
if state is not None:
self.odometry.update(state.leftEncoderCounts, state.rightEncoderCounts)
# print("[{},{},{}]".format(self.odometry.x, self.od... | [
"def wait_for_time():\n while rospy.Time().now().to_sec() == 1:\n pass",
"def rand_sleep():\n time.sleep(random.uniform(0.75, 1.5))",
"def delay():\n latency = 0.49\n sleep(latency)",
"def wait():\n t = random.triangular(config.WAIT_MIN, config.WAIT_MAX)\n time.sleep(t)",
"def s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the parameters of the model. When called, this function sets the model parameters tha are used to make predictions. Assumes parameters are stored in self.w, self.b. | def set_params(self, w, b):
self.w = w
self.b = b | [
"def set_model_params(self, params):",
"def set_model_params(self, new_model_params: ModelParamsType):\n new_prototypes, new_omega = new_model_params\n\n self.set_prototypes(new_prototypes)\n self.set_omega(new_omega)\n\n if self.relevance_normalization:\n LGMLVQ._normalize_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load page corresponding to self.external_id and update Exoplanet.articles with parsed sources | def retrieve(self):
try:
if (response := requests.get("http://exoplanet.eu/catalog/" + self.external_id)).status_code != 200:
self.trace('http response: {}'.format(response.status_code), 40)
return
except requests.exceptions.RequestException as e:
... | [
"def load_article(self, title):\n wikipedia.set_lang(self.language)\n self.article_name = title\n page = wikipedia.page(title)\n page = self.store_images(page)\n self.content = self.process_html(page)",
"def load_article(self, title):\n self.articleName = title\n u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Standardizes pixels; Facenet expects standardized pixels as input. | def standardize_pixels(pixels):
pixels = pixels.astype('float32')
mean, std = pixels.mean(), pixels.std()
return (pixels - mean) / std | [
"def standardize_pixel_values(pixels):\n mean, std = pixels.mean(), pixels.std()\n pixels = (pixels - mean) / std\n pixels = np.clip(pixels, -1.0, 1.0)\n pixels = (pixels + 1.0) / 2.0\n return pixels",
"def normalize(img,max_=255.0):\n img -= img.min()\n img = (img*max_/img.max()).astype('uint8')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We override the paint event to allow us to draw with nice rounded edges | def paintEvent(self, event):
qp = qute.QPainter()
qp.begin(self)
qp.setRenderHint(
qute.QPainter.Antialiasing,
True,
)
qsize = self.size()
gradient = qute.QLinearGradient(0, 0, 0, qsize.height())
gradient.setColorAt(0, qute.QColor(100, 20... | [
"def paint(self, painter, option, widget):\n painter.setPen(self.pen)\n\n painter.setBrush(self.brush)\n if self.highlighted:\n painter.setBrush(self.highlightBrush)\n\n painter.drawEllipse(self.boundingRect())",
"def paintEvent(self, event):\n\n painter = QPainter()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print dir tree. Input str or Pathlike obj. If print_files is True, print files, limited to num_files. | def tree(
path: Union[str, Path] = ".",
ident: int = 0,
print_files: bool = False,
num_files: int = 3,
) -> None:
path = Path(path)
dirs, files = get_dirs_files(path)
print(" " * ident, f"{path.name} - {len(dirs)} dirs {len(files)} files")
for dir_entry in dirs:
tree(Path(dir_en... | [
"def print_tree(self, maxresults=100, maxdepth=None):\n self.ignore_caller()\n for depth, refid, rep in self.walk(maxresults, maxdepth):\n print (\"%9d\" % refid), (\" \" * depth * 2), rep",
"def print_tree_helper(path, sep, depth):\r\n for item in path_iterator(path): \r\n # Fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the server to initial state, clear out all Onboardingcreated roles Onboardingcreated channels | async def reset_server(ctx):
# Delete onboarding-created roles
removed_roles = []
for role in ctx.guild.roles:
if role.name.startswith("o-"):
try:
await role.delete()
removed_roles.append(role.name)
except discord.Forbidden:
aw... | [
"async def reset(self, ctx):\n # TODO: Add confirmation message\n await sql.deleteserver(ctx.message.guild.id)\n await sql.initserver(ctx.message.guild.id)\n em = discord.Embed(title=\"Reset all data for this server\",\n colour=discord.Colour.dark_green())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the current_version string in .bumpversion.cfg | def read_current_version():
config = RawConfigParser()
config.add_section('bumpversion')
config.read_file(io.open('.bumpversion.cfg', 'rt', encoding='utf-8'))
items = dict(config.items('bumpversion'))
current_version = items.get('current_version')
return current_version | [
"def get_version() -> str:\n config = configparser.ConfigParser()\n path = Path(__file__).parent.parent / \"setup.cfg\"\n config.read(path)\n return str(config[\"metadata\"][\"version\"])",
"def find_current_version():\n with open(VERSION_FILE) as v:\n return v.read()",
"def _get_version()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get usable buffer from datetime | def get_timestamp_buffer(dt: datetime) -> bytes:
filetime = filetimes.dt_to_filetime(dt)
return struct.pack("!Q", filetime) | [
"def get_timestamp_buffer(self, dt: datetime) -> bytes:\n filetime = filetimes.dt_to_filetime(dt)\n return struct.pack('!Q', filetime)",
"def readDate(self):\n ms = self.stream.read_double() / 1000.0\n tz = self.stream.read_short()\n\n # Timezones are ignored\n d = dateti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get big endian uint32 bytesrepresentation from signature version | def get_signature_version_buffer(version: int) -> bytes:
return struct.pack("!I", version) | [
"def abi_signature(self):\n return big_endian_to_int(sha3(str_to_bytes(self.signature))[:4])",
"def get_v_r_s(sig: HexStr) -> Tuple[int, str, str]:\n return Web3.toInt(sig[-1]) + 27, Web3.toHex(sig[:32]), Web3.toHex(sig[32:64])",
"def bytes(self):\n\n if not self._signature:\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify signature against digest | def verify_digest(
self,
signature: bytes,
digest: bytes,
verifying_key: Optional[VerifyingKey] = None,
) -> bool:
verifier = verifying_key or self.signing_key.verifying_key
return verifier.verify_digest(signature, digest) | [
"def verify(hash, signature, key_path=\"~/.ssh/ida_rsa\"):\n key = open(expanduser(key_path), \"r\").read()\n rsakey = RSA.importKey(key) \n pubkey = key.publickey()\n return pubkey.verify(hash, b64decode(signature)) == True",
"def verifies( self, hash, signature ):\n\n # From X9.62 J.3.1.\n\n G... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |