query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Collects and merges all instances of NavigationEntry | def combine_navigation_entries() -> navigation.NavigationEntry:
navigation_root = config.navigation_root()
def all_children(navigation_entry: navigation.NavigationEntry) -> {navigation.NavigationEntry}:
return functools.reduce(set.union, [all_children(child) for child in navigation_entry.children],
... | [
"def navigations(self):\n return Navigation.objects.filter(page=self)",
"def by_navigations(self):\n\t\t\n\t\turl_format = r'^\\s*(?:(?P<protocol>\\w+)://)?(?P<domain>[\\w\\d\\-\\.]+)(?::(?P<port>\\d+))?/?(?P<everything_else>.*)$'\n\t\tnavigations = {}\n\t\tfor line in self.source.lines:\n\t\t\ttry:\n\t\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply a processing method (in "filtering", "removal", and "reconstruction" module) to multiple sinograms or multiple slices in parallel. | def apply_method_to_multiple_sinograms(data, method, para, ncore=None,
prefer="threads"):
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
if not isinstance(para, list):
para = tuple(list([para... | [
"def _process(cls, spectrum, filter_spectrum, *args):\n if filter_spectrum:\n resampled_filter_spectrum = filter_spectrum.resample(spectrum)\n resampled_filter_lines = resampled_filter_spectrum.lines\n else:\n resampled_filter_lines = repeat(None, len(spectrum.lines))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort grayscales of an image using an index array provided. e.g. axis=0 is to sort each column. | def sort_backward(mat, mat_index, axis=0):
if axis == 0:
mat = np.transpose(mat)
mat_index = np.transpose(mat_index)
mat_comb = np.asarray(np.dstack((mat_index, mat)))
mat_comb_sort = np.asarray(
[row[row[:, 0].argsort()] for row in mat_comb])
mat_sort = mat_comb_sort[:, :, 1]
... | [
"def sort_indices(unsorted_indices, filter_size, image, image_array):\n print()\n sorted_indices = [None]*int(len(unsorted_indices))\n counter = 0\n biais = 0\n add_horizontal = 0 # Adds to index position every time position moves horizontally\n # moving vertically:\n for i in range(int(len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a 2d window from the 1D Butterworth window. | def make_2d_butterworth_window(width, height, u, v, n):
xcenter = np.ceil(width / 2.0) - 1.0
ycenter = np.int16(np.ceil(height / 2.0) - 1)
xlist = np.arange(width) - xcenter
window = 1.0 / (1.0 + np.power(xlist / u, 2 * n))
row1 = ycenter - np.int16(v)
row2 = ycenter + np.int16(v) + 1
window... | [
"def dwindow(window):\r\n \r\n h=window\r\n nh=len(h)\r\n lh=(nh-1)/2\r\n stepheight=(h[0]+h[-1])/2.\r\n ramp=float((h[-1]-h[0]))/nh\r\n h2=np.zeros(nh+2)\r\n h2[1:nh+1]=h-stepheight-ramp*np.arange(start=-lh,stop=lh+1,step=1)\r\n \r\n dwin=(h2[2:nh+2]-h2[0:nh])/2.+ramp\r\n dwin[0]=d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply 2D wavelet decomposition. | def apply_wavelet_decomposition(mat, wavelet_name, level=None):
(nrow, ncol) = mat.shape
max_level = int(
min(np.floor(np.log2(nrow / 16.0)), np.floor(np.log2(ncol / 16.0))))
if (level is None) or (level > max_level) or (level < 1):
level = max_level
return pywt.wavedec2(mat, wavelet_nam... | [
"def gen_wavelet():\n \n \n # Define the coefficients for the CDF9/7 filters\n factor=1\n\n # FORWARD FILTER COEFFICIENTS\n # Forward Decomposition filter: lowpass\n cdf97_an_lo = factor * np.array([0, 0.026748757411, -0.016864118443, -0.078223266529, 0.266864118443,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply 2D wavelet reconstruction. | def apply_wavelet_reconstruction(data, wavelet_name, ignore_level=None):
if ignore_level is not None:
level = len(data[1:])
if level >= ignore_level > 0:
data[-ignore_level] = tuple(
[np.zeros_like(v) for v in data[-ignore_level]])
return pywt.waverec2(data, wavelet_n... | [
"def gen_wavelet():\n \n \n # Define the coefficients for the CDF9/7 filters\n factor=1\n\n # FORWARD FILTER COEFFICIENTS\n # Forward Decomposition filter: lowpass\n cdf97_an_lo = factor * np.array([0, 0.026748757411, -0.016864118443, -0.078223266529, 0.266864118443,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a 2D Gaussian window. | def make_2d_gaussian_window(height, width, sigma_x, sigma_y):
xcenter = (width - 1.0) / 2.0
ycenter = (height - 1.0) / 2.0
y, x = np.ogrid[-ycenter:height - ycenter, -xcenter:width - xcenter]
window = np.exp(
-(x ** 2 / (2 * sigma_x ** 2) + y ** 2 / (2 * sigma_y ** 2)))
return window | [
"def gaussian_window(n1, n2, sig=1, mu=0):\r\n x, y = np.meshgrid(np.linspace(-1, 1, n1), np.linspace(-1, 1, n2))\r\n d = np.sqrt(x * x + y * y)\r\n g = np.exp(-((d - mu) ** 2 / (2.0 * sig ** 2)))\r\n return g",
"def _gaussian_window(self, mean: int, std: float) -> np.ndarray:\n n = np.arange(0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply a regularization filter using the method in Ref. [1]. Note that it's computationally costly. | def apply_regularization_filter(mat, alpha, axis=1, ncore=None):
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
if axis == 0:
mat = np.transpose(mat)
(nrow, ncol) = mat.shape
sijmat = calculate_regularization_coefficient(ncol, alpha)
mat = np.asarray(Parallel(n_jobs=n... | [
"def regularize(self):\n if not self.regularizer:\n return\n func_map = {\n 'l1': lambda v: tf.abs(v),\n 'l2': lambda v: tf.square(v),\n 'moe': lambda v: self._mixture(v, [0, 1, 2]),\n 'moi': lambda v: self._mixture(v, [1, 2, 3]),\n }\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a 1dwindow to 2dwindow. Useful for designing a Fourier filter. | def transform_1d_window_to_2d(win_1d):
width0 = len(win_1d)
if width0 % 2 == 0:
width = width0 + 1
else:
width = width0
center = width // 2
xlist = (1.0 * np.flipud(np.arange(width)) - center)
ylist = (1.0 * np.arange(width) - center)
x_mat, y_mat = np.meshgrid(xlist, ylist)
... | [
"def make_2d_butterworth_window(width, height, u, v, n):\n xcenter = np.ceil(width / 2.0) - 1.0\n ycenter = np.int16(np.ceil(height / 2.0) - 1)\n xlist = np.arange(width) - xcenter\n window = 1.0 / (1.0 + np.power(xlist / u, 2 * n))\n row1 = ycenter - np.int16(v)\n row2 = ycenter + np.int16(v) + 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To check if there is a sample in a sinogram using the "doublewedge" property of the Fourier transform of the sinogram (Ref. [1]). | def detect_sample(sinogram, sino_type="180"):
check = True
if not (sino_type == "180" or sino_type == "360"):
raise ValueError("!!! Use only one of two options: '180' or '360'!!!")
if sino_type == "180":
sinogram = 1.0 * np.vstack((sinogram, np.fliplr(sinogram)))
sino_fft = np.abs(fft.ff... | [
"def test_double_sinusoid():\n generator = SignalGenerator(sr=100)\n data1 = generator.sinusoid(noise_stds=[0.1, 0.1, 0.1])\n data2 = generator.sinusoid(dom_freqs=[0.1, 0.2, 0.3], amps=[0.1, 0.2, 0.3])\n data = data1 + data2\n freq_features = FrequencyFeature(data, sr=100)\n freq_features.fft().pe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Locate slice indices in gridrows given a slice index of the reconstruction data as a whole. | def locate_slice(slice_idx, height, overlap_metadata):
g_nrow = overlap_metadata.shape[0] + 1
side = overlap_metadata[0, 0, 1]
overlap_list = overlap_metadata[:, 0, 0]
if side == 1:
list_slices = [(np.arange(i * height, i * height + height) -
np.sum(overlap_list[0: i])) f... | [
"def compute_index_grid(self):\n vecs = [np.arange(n) for n in self.shape]\n grid_locs = np.stack([v.flatten() for v in np.meshgrid(*vecs, indexing='ij')], axis=0).reshape(\n (-1,) + self.shape)\n return grid_locs.astype(int)",
"def get_grid_index(init_grid_size, map_size, device):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For visually finding the centerofrotation (COR) using converted 360degree sinograms from a 180degree sinogram at different CORs (Ref. [1]). | def find_center_visual_sinograms(sino_180, output, start, stop, step=1,
zoom=1.0):
(nrow, ncol) = sino_180.shape
output_name = losa.make_folder_name(output, name_prefix="Find_center",
zero_prefix=3)
output_base = output + "/" + output_... | [
"def correct_lon_2(cor):\n VarCor = 0\n rr = cor % 360\n if rr == 0:\n VarCor = 1;\n \n elif rr == 180:\n VarCor = -1;\n\n\n\n return VarCor",
"def poc_transforms(self):\n az = self.azimuths()\n da = self.deflection_angles()\n l = az - da / 2\n t = l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For visually finding the centerofrotation (COR) using reconstructed slices at different CORs. | def find_center_visual_slices(sinogram, output, start, stop, step=1, zoom=1.0,
method="dfi", gpu=False, angles=None,
ratio=1.0, filter_name="hann", apply_log=True,
ncore=None):
output_name = losa.make_folder_name(output, name_... | [
"def resetCoronalSegment(self):\r\n #research\r\n profprint()\r\n sGreen = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeGreen\")\r\n if sGreen == None :\r\n sGreen = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNode3\")\r\n reformatLogic = slicer.vtkSlicerReformatLogic()\r\n #sGreen.SetSliceV... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The handshake process matches the user and the socketio session Through this process the message queues for that user are declared and the consumption of messages is started | def handshake_handler(json):
# json object contains the session cookie, thus identifying the sender
# Handshake the request sid with the user identifier, through the json[data] cookie
# get_cache(cookie) -> if there is proceed and get userid from the cache
userid = get_t... | [
"def connect_handler():\n print(\"---------------- CONNECTED ----------------\")\n\n user = User.query.get(get_jwt_identity())\n\n \"\"\"\n Save phone numbers with corresponding sid, so that server\n can push updates to clients that are connected\n \"\"\"\n redis.set(user.phone_num, request.sid)\n redis.set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a DataFrame given a list of high resolution segments from the Swiftly Speed Maps API. | def speed_map_segs_to_df(seg_list):
# Put segment list into DataFrame
df = pd.DataFrame(seg_list)
# Seperate the start and end coords from pathLocs
temp_df = pd.DataFrame(df['pathLocs'].to_list())
temp_df.rename({0: 'start', 1: 'end'}, axis=1, inplace=True)
# Put start coords into a dataframe
... | [
"def get_meter_data_for_time_slice(apt_no, start_time, end_time):\n if apt_no in ['102A', 102]:\n apt_no = '102A'\n\n logger.debug(\"sMap: Getting meter data for %s between %s and %s\", apt_no, start_time, end_time)\n\n query = (\"select data in ('\" + str(start_time) + \"','\" + str(end_time) + \"'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a GeoJSON given a list of high resolution segments from the Swiftly Speed Maps API. | def speed_map_segs_to_geojson(seg_list):
# Initialize a new GeoJSON object
new_geojson = {
'type': 'FeatureCollection',
'features': []
}
# Dont work on the input list
seg_list_copy = copy.deepcopy(seg_list)
# Iterativley build the features of the new GeoJSON object
for i, s... | [
"def advsOverview(request,userId):\n \n if request.method==\"GET\":\n allAdvs = []\n #this is awful\n advs = Adventure.objects.filter(owner_id=userId).all()\n for adv in advs:\n advCoordinates = []\n distance = 0\n startTime = None\n endT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures indicies on the substrates, materials, and elastic collections | def ensure_indicies(self):
# Search indicies for materials
self.materials.ensure_index(self.materials.key)
self.materials.ensure_index(self.materials.last_updated_field)
# Search indicies for elasticity
self.elasticity.ensure_index(self.elasticity.key)
self.elasticity.en... | [
"def ensure_indicies(self):\n # Search indicies for materials\n self.materials.ensure_index(self.materials.key, unique=True)\n self.materials.ensure_index(self.materials.lu_field)\n self.materials.ensure_index(\"chemsys\")\n self.materials.ensure_index(\"_sbxn\")\n\n # Sear... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a conventional standard structure from doc["structure"]. | def conventional_standard_structure(doc):
s = Structure.from_dict(doc["structure"])
spga = SpacegroupAnalyzer(s, symprec=0.1)
return spga.get_conventional_standard_structure() | [
"def structure_objet(objet):\n return objet.get_structure()",
"def getStructure(sname):\n x = resolve(vs_defs, sname.split(\".\"))\n if x is not None:\n return x()\n\n return None",
"def structure_salle(salle):\n return salle.get_structure()",
"def structure(self):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of milliseconds to run this search function on this list. | def time_search(search_fn, mylist, key):
start = time.time()
search_fn(mylist, key)
end = time.time()
return (end - start) * 1000 | [
"def sec(search: \"Search\"):\n return (time.time() - search.stopwatch) // 1",
"def elapsed_time_in_seconds_for_search_problem(self):\n return self._elapsed_time_in_seconds_for_search_problem",
"def count_time(self, search):\n self.prune()\n return self.times.count(search)",
"def s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare the running time of linear_search and binary_search for input sizes as given. The key for each search should be 1. The list to search for each size contains the numbers from 0 to n1, sorted in ascending order. You'll use the time_search function to time each call. | def compare_search(sizes=[1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7]):
print(sizes)
return [(size,
time_search(linear_search, list(range(int(size))), -1),
time_search(binary_search, list(range(int(size))), -1)) for size in sizes] | [
"def nsearch_time(Nsize=11,Msize=11,Psize=11):\n import numpy as np\n import matplotlib.pyplot as plt\n from time import time\n\n #Vary N, M,P fixed--------------\n Narray = np.logspace(1,4,Nsize,dtype=int)\n M=1000\n P=500\n dtarray_N = np.zeros(Nsize)\n for i,N in enumerate(Narray):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decide whether to keep or discard an ngram. | def filter_ngram(gram, mode='any'):
filtered = [filter_word(w) for w in gram]
if mode == 'any':
return any(filtered)
elif mode == 'all':
return all(filtered)
elif mode == 'ends':
return filtered[0] or filtered[-1]
else:
raise ValueError('Invalid mode: %s' % mode) | [
"def has_ngrams(self):\n return self.ngram_sizes and self.ngram_levels",
"def get_ngram(self):\n self.n_gram = int(input(\"\\nWhat n-gram length would you like to use? \"))\n print(\"\\tYou have chosen to use n_grams of length \" + str(self.n_gram) + \".\")\n if self.n_gram > 10:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load examples from preprocessed file. One example per line, JSON encoded. | def load_data(filename):
# Load JSON lines
with open(filename, encoding='utf-8') as f:
examples = [json.loads(line) for line in f]
return examples | [
"def _load(examples, f):\n\n for l in f:\n json_example = json.loads(l)\n if FLAGS.mode == 'long_answers' and not has_long_answer(json_example):\n continue\n\n elif FLAGS.mode == 'short_answers' and not has_short_answer(json_example):\n continue\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put all the words in embedding_file into a set. | def index_embedding_words(embedding_file):
words = set()
with open(embedding_file, encoding='utf-8') as f:
for line in f:
w = Dictionary.normalize(line.rstrip().split(' ')[0])
words.add(w)
return words | [
"def index_embedding_words(self, embedding_file):\n words = set()\n with open(embedding_file) as f:\n for line in f:\n w = TokenDictionary.normalize(line.rstrip().split(' ')[0])\n words.add(w)\n return words",
"def index_embedding_words(embedding_file)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count and return the most common question words in provided examples. | def top_question_words(args, examples, word_dict):
word_count = Counter()
for ex in examples:
for w in ex['question']:
w = Dictionary.normalize(w)
if args.uncased_question:
w = w.lower()
if w in word_dict:
word_count.update([w])
ret... | [
"def plurality_value(examples):\n outputs = get_outputs(examples)\n\n max_count = 0\n most_common_output = None\n for x in set(outputs):\n count = examples.count(x)\n if count > max_count:\n max_count = count\n most_common_output = x\n return most_common_output",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if a regex pattern is contained within a text. | def regex_match(text, pattern):
try:
pattern = re.compile(
pattern,
flags=re.IGNORECASE + re.UNICODE + re.MULTILINE,
)
except BaseException:
return False
return pattern.search(text) is not None | [
"def regex_match(text, pattern):\n try:\n pattern = re.compile(pattern, flags=re.IGNORECASE + re.UNICODE + re.MULTILINE)\n except BaseException:\n return False\n return pattern.search(text) is not None",
"def regex_match(text, pattern):\n try:\n pattern = re.compile(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read all data from filename and use split to create a list. | def read_data(filename):
with open(filename, 'r') as f:
return f.read().split() | [
"def get_data(filename) -> list:\n filename += \".txt\" if not filename.endswith(\".txt\") else \"\"\n data = [val.replace(\"\\n\",\"\") for val in open(filename, \"r\").readlines()]\n return data",
"def open_and_read_file(filename):\n \n file_class = open(filename)\n file_list = file_class.read... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for the Authorization header should be case insensitive. | def test_from_request_is_case_insensitive_checking_for_auth(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",... | [
"def check_headers(self, cont_type=False):\n if not super().check_headers(cont_type):\n return False\n\n uchan_auth = self.headers['Authorization']\n return uchan_auth is not None and 'Basic ' in uchan_auth",
"def _match_header(self):\n header = self.args[\"header\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test getting an access token via GET. | def test_access_token_get(self):
client = oauth.Client(self.consumer, None)
resp, content = client.request(self._uri('request_token'), "GET")
self.assertEqual(int(resp['status']), 200) | [
"def test_get_access_token(self):\n pass",
"def test_read_o_auth_access_token(self):\n pass",
"def test_get_token_request(self):\n query_string = [('grant_type', 'grant_type_example'),\n ('client_id', 'client_id_example'),\n ('client_secret', 'c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test getting an access token via POST. | def test_access_token_post(self):
client = oauth.Client(self.consumer, None)
resp, content = client.request(self._uri('request_token'), "POST")
self.assertEqual(int(resp['status']), 200)
res = dict(parse_qsl(content))
self.assertTrue(b'oauth_token' in res)
self.assertTr... | [
"def test_access_token_valid(self, mock_post):\n\n global mock_rules\n\n username = 'user123'\n password = 'password123'\n\n mock_rules = {'http://fake-host/auth': lambda *args, **\n kwargs: mocked_keycloak_auth_respone(args, data=kwargs.get('data', {}), username=use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A test of a twolegged OAuth POST request. | def test_two_legged_post(self):
resp, content = self._two_legged("POST")
self.assertEqual(int(resp['status']), 200) | [
"def test_access_token_post(self):\n client = oauth.Client(self.consumer, None)\n resp, content = client.request(self._uri('request_token'), \"POST\")\n\n self.assertEqual(int(resp['status']), 200)\n\n res = dict(parse_qsl(content))\n self.assertTrue(b'oauth_token' in res)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A test of a twolegged OAuth GET request. | def test_two_legged_get(self):
resp, content = self._two_legged("GET")
self.assertEqual(int(resp['status']), 200) | [
"def test_get_without_oauth(self):\n self.client = trovebox.Trovebox(host=self.test_host)\n self._register_uri(httpretty.GET)\n response = self.client.get(self.test_endpoint)\n self.assertNotIn(\"authorization\", self._last_request().headers)\n self.assertEqual(response, self.test... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot dendrogram using specific input parameters. | def plot_dendrogram(*args, **kwargs):
max_d = kwargs.pop('max_d', None)
if max_d and ('color_threshold' not in kwargs): kwargs['color_threshold'] = max_d
annotate_above = kwargs.pop('annotate_above', 0)
# Compute the dendrogram
ddata = dendrogram(*args, **kwargs)
# Plot the dendrogram
if n... | [
"def dendrogram(self, **kwargs):\n plt.figure()\n dn = hierarchy.dendrogram(self.linkage_table, **kwargs)",
"def dendogram(self):\r\n \r\n plt.figure(figsize=(20, 7))\r\n dendrogram = sch.dendrogram(sch.linkage(self.X, method='ward'))\r\n plt.title(\"Dendograms\")\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a query that resolves to entity's equipment slots and their equipped items. | def get_slots_query(scene: GameScene, entity: int):
def query():
paper_doll: PaperDoll = scene.cm.get_one(PaperDoll, entity)
equipment = paper_doll.get_equipment()
return [
(k, scene.cm.get_one(Entity, v))
for k, v in equipment.items()
]
return query | [
"def equipments(self):\n selection = self.object.equipment_set\n return {\n 'selection': selection.all(),\n 'count': selection.count()\n }",
"def equipments(self):\n selection = Equipment.objects.filter(responsible__location_id=self.object.id)\n return {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scale pandas series so that it starts at one. | def scale_to_start(x):
x = (x + eps) / (x[0] + eps)
return x | [
"def rescale(series, new_min=0, new_max=1):\n old_min = series.min()\n old_max = series.max()\n series = series.apply(\n lambda x: (x - old_min) / (old_max - old_min) * \\\n (new_max - new_min) + new_min\n )\n return series",
"def scale(x: pd.Series, a: int = 1) -> pd.Series... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a set of returns, calculates naive (rfr=0) sharpe (eq 28). | def sharpe(returns, freq=30, rfr=0):
return (np.sqrt(freq) * np.mean(returns - rfr + eps)) / np.std(returns - rfr + eps) | [
"def true_sharpe(ret):\n r = pd.Series()\n df = pd.DataFrame({\"returns\": ret})\n df[\"cummulative_return\"] = (df[\"returns\"] + 1).cumprod()\n df[\"log_returns\"] = np.log(df[\"returns\"] + 1)\n r[\"cummulative_return\"] = df[\"cummulative_return\"][-1] - 1\n r[\"annual_return\"] = ((r[\"cummul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step. w1 new action of portfolio weights e.g. [0.1,0.9,0.0] y1 price relative vector also called return e.g. [1.0, 0.9, 1.1] | def _step(self, w1, y1,y1_short):
#reajust the return y1 using the sign of w1
#if is negative means we shorted so the return is the inverse
y1_aux=y1.copy()
for i in range(len(w1)):
if(w1[i]<0):
y1_aux[i]=y1_short[i]
y1=y1_aux.copy()
#pri... | [
"def _step(self, action):\n\n np.testing.assert_almost_equal(\n action.shape,\n (len(self.sim.asset_names) + 1,)\n )\n\n # normalise just in case\n action = np.clip(action, -1, 1)\n\n weights = action # np.array([cash_bias] + list(action)) # [w0, w1...]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step the env. Actions should be portfolio [w0...] Where wn is a portfolio weight from 0 to 1. The first is cash_bias cn is the portfolio conversion weights see PortioSim._step for description | def _step(self, action):
np.testing.assert_almost_equal(
action.shape,
(len(self.sim.asset_names) + 1,)
)
# normalise just in case
action = np.clip(action, -1, 1)
weights = action # np.array([cash_bias] + list(action)) # [w0, w1...]
weights /=... | [
"def step_cash_flow(self, action):\n\n # do it consistently as in the profit & loss case\n # current prices (at t)\n current_price = self.state[0]\n\n # current position\n current_position = self.state[1]\n\n # update time/period\n self.t = self.t + 1\n\n # ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a block to the game board | def addBlock(self, aBlock: gp.Block):
if self.blocks[aBlock.y][aBlock.x] != None:
raise MovementError('game board space not empty')
self.blocks[aBlock.y][aBlock.x] = aBlock
self.groundSprites.append(aBlock.sprite) | [
"def add(self, block):\n self.blocks.append(block)",
"def add_block(self):\n\n new_snake = SerpentBlock(self.blocks[len(self.blocks) - 1])\n self.blocks.append(new_snake)",
"def add(self, block: Block):\n raise NotImplementedError()",
"def add_new_block(self):\n old_block = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove a block from the game board | def removeBlock(self, aBlock: gp.Block):
for y, row in iter(self.blocks):
for x, block in iter(row):
if block is aBlock:
self.blocks[y][x] = None
self.playerSprites.remove(aBlock.sprite)
return | [
"def remove_block(self, block):\n raise NotImplementedError()",
"def remove_block(self,blockname):\n\t\tdel self.blocks[blockname]",
"def removeBlock(self, block: ghidra.program.model.mem.MemoryBlock, monitor: ghidra.util.task.TaskMonitor) -> None:\n ...",
"def remove_block(self, position, immed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get any credentials this network will require to call `self.connect()` return True if we should connect, False if we're missing credentials | def credentials(self):
return True | [
"def has_credentials(self):\n return self.username and self.password and self.url and self.xml_rpc",
"def are_credentials_valid(self):\n try:\n conn = self.conn\n return True\n except (libcloud.types.InvalidCredsError, AttributeError):\n return False",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_dist_hash(m, ndigits = 2, dist = euclidean) | def get_dist_hash(m, ndigits=2,dist=euclidean):
# defaultdict is awesome :D
# http://docs.python.org/library/collections.html#collections.defaultdict
h = defaultdict(set)
# Also, itertools.combinations is sweet:
# http://docs.python.org/library/itertools.html#itertools.combinations
# Sets of sets in python are t... | [
"def calHash(n, m):\n return int(m*BloomFilter.ln2/n)",
"def get_hash_count(cls, m: int, n: int):\n k = (m / n) * math.log(2)\n return int(k)",
"def hash(self, m):\n\t\tg,p,z,in_size,out_size = self.s\n\t\tx = m>>(in_size/2)\n\t\ty = m - (x << (in_size/2))\n\n\t\treturn (pow(g,x,p) * pow(z,y,p)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert two dates into FITS form. | def dates_to_fits(date_begin: astropy.time.Time, date_end: astropy.time.Time) -> dict[str, Any]:
cards: dict[str, Any] = {}
if date_begin is None and date_end is None:
# no date headers can be written
return cards
cards["TIMESYS"] = "TAI"
date_avg = None
if date_begin is not None a... | [
"def create_date_features(df = None, date = None):\n #TODO",
"def make_one_fits():\n\tbase_path = Path(\"/Users/lahayes/ssw/hessi/dbase/\")\n\ttstart = parse_time(\"2002-02-01\").datetime\n\ttend = parse_time(\"2018-03-01\").datetime\n\tmonth_list = [tstart.strftime(\"hessi_flare_list_%Y%m.fits\")]\n\twhile te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an `ObservationInfo` to something suitable for writing to a FITS file. | def info_to_fits(obs_info: ObservationInfo) -> tuple[dict[str, Any], dict[str, str]]:
cards = {}
comments = {}
if obs_info.instrument is not None:
cards["INSTRUME"] = obs_info.instrument
comments["INSTRUME"] = "Name of instrument"
cards.update(dates_to_fits(obs_info.datetime_begin, obs... | [
"def save_as_fits(self, filename):",
"def export_fits(self, filename):",
"def NRMtoOifits2(dic, filename=None, saveoifdir=None, verbose=False):\n\n if dic is not None:\n pass\n else:\n cprint('\\nError NRMtoOifits2 : Wrong data format!', on_color='on_red')\n return None\n\n datadir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an `ObservationGroup` to something suitable for writing to a FITS file. | def group_to_fits(obs_group: ObservationGroup) -> tuple[dict[str, Any], dict[str, str]]:
cards = {}
comments = {}
oldest, newest = obs_group.extremes()
instruments = obs_group.property_values("instrument")
if len(instruments) == 1:
cards["INSTRUME"] = list(instruments)[0]
comments[... | [
"def dump2file ( group_name , json_group ):\n\n # Set name of logger with calling details.\n ls = \"%s by %s\" % ( __name__ , '__dump2file__' )\n logger = logging.getLogger( ls )\n\n oufig = \"%s/grp_dmz_%s.json\" % ( cf.output_dir, group_name )\n\n # Open it for writing.\n fd_oufi = open(oufig, '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for uploadcustomerpurchasefile Upload a datafile to the database | def test_uploadcustomerpurchasefile(self):
testfile = os.path.join(os.getcwd(), '..', 'test_input_file.dat')
in_file = open(testfile, 'rb')
filec = in_file.read()
in_file.close()
data = dict(upfile=(BytesIO(filec), testfile))
response = self.client.open(
'/v1/... | [
"def test_upload_file(self):\n pass",
"def test_upload_file1(self):\n pass",
"def test_file_upload(self):\n\n with tempfile.NamedTemporaryFile() as test_file:\n test_file.write(\n u'date,category,employee name,employee address,expense description,pre-tax amount,tax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the contact pairs using rayshooting the finally returned number of contact pairs may be smaller than the given max_samples due to the min_dist constraint | def plan_contact_pairs(objcm,
max_samples=100,
min_dist_between_sampled_contact_points=.005,
angle_between_contact_normals=math.radians(160),
toggle_sampled_points=False):
contact_points, face_ids = objcm.sample_surface(nsam... | [
"def forward(ctx, pcs, centroids, radius, max_samples):\n pc_length = pcs.pow(2).sum(dim=1, keepdim=True)\n c_length = centroids.pow(2).sum(dim=1).unsqueeze(-1)\n # (batch_size, num_centroids, num_points)\n dists = centroids.permute(0, 2, 1).bmm(pcs).mul(-2).add(pc_length).add(c_length)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return atomic positions flattened to a single long vector. | def position(self):
return self.atoms.reshape((1,-1)) | [
"def pos_to_array(lmp_):\n num_atoms = lmp_.extract_global(\"natoms\", 0)\n positions = lmp_.extract_atom(\"x\", 3)\n array = np.zeros(3*num_atoms)\n for i in xrange(num_atoms):\n array[3*i] = positions[i][0] \n array[3*i+1] = positions[i][1]\n array[3*i+2] = positions [i][2]\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a supercell of the given shape | def supercell(self, shape):
l,m,n = shape
mult = l*m*n
supercell = atomic_set()
supercell.name = "SUPERCELL %dx%dx%d %s"%(l,m,n,self.name)
supercell.unit_cell = multiply(self.unit_cell,array([[l,l,l],[m,m,m],[n,n,n]]))
supercell.recip_cell = linalg.inv(supercell.unit_cell)
supercell.num_at... | [
"def make_super_cell(structure, sc):\n assert isinstance(structure,SimulationCell)\n\n supercell = SimulationCell()\n supercell.structure_comment = \"{}x{}x{}\".format(sc[0],sc[1],sc[2])\n\n # set lattice parameter\n supercell.a0 = structure.a0\n\n # set h_matrix\n H = np.zeros(shape=[3,3])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs Gaussian mutation operation on single individual in floating point gene representation, Mutation works by drawing N samples from random normal distribution add adding in to individual | def gaussian_standard_mutation(individual: np.array, mutation_strength: float = 0.1) -> np.array:
offset = np.random.randn(individual.shape[0])
return mutation_strength * offset + individual | [
"def mutate_gaussian(next_individual: Iterator,\n std: float,\n expected_num_mutations: float = None,\n hard_bounds: Tuple[float, float] =\n (-math.inf, math.inf)) -> Iterator:\n while True:\n individual = next(next_individual)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set a MPL 2D line with the current properties | def refresh_mpl_line(self, line=None):
if line:
self.set_label(self.label,line=line)
self.set_color(self.color,line=line)
self.set_style(self.style,line=line)
self.set_marker(self.marker,line=line)
self.set_markersize(self.markersize,line=line)
... | [
"def _init_line(self):\n tran = (self._axis_artist_helper.get_line_transform(self.axes)\n + self.offset_transform)\n\n axisline_style = self.get_axisline_style()\n if axisline_style is None:\n self.line = PathPatch(\n self._axis_artist_helper.get_line(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize this hash table with the given initial size | def __init__(self, init_size=8):
self.size = 0
self.buckets = [LinkedList() for i in range(init_size)] | [
"def __init__(self, initial_size):\n self.comparisons_used = 0\n self.number_of_slots = initial_size\n self._number_of_items = 0\n\n # setup the given number of slots, each containing None\n # Note: self._data[i] will be the head of a linked list\n self._data = [None] * ini... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a string representation of this hash table | def __repr__(self):
# return 'HashTable({})'.format(self.length())
return 'HashTable({})'.format(str(self.buckets)) | [
"def __repr__(self):\n return 'HashTable({!r})'.format(self.items())",
"def __repr__(self):\n return 'HashTable({})'.format(repr(self.items()))",
"def __str__(self):\n sorted_table = InferenceUtils.get_n_best(self._table, max(len(self._table), 1))\n\n result = []\n for key, va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the length of this hash table by traversing its buckets | def length(self):
# TODO: Count number of key-value entries in each of the buckets
return self.size
# for bucket in self.buckets(): | [
"def length(self):\n # Loop through all buckets\n # Count number of key-value entries in each bucket\n\n # could be done with 1 line with comprehension\n # return sum(bucket.length() for bucket in self.buckets)\n\n total_entries = 0\n\n for linked_list in self.buckets:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the number of speaker. | def get_speaker_number(self):
return len(self.metadata) | [
"def speaker_volume(self):\n volume = self._attrs.get('speaker_volume')\n try:\n return int(volume)\n except ValueError:\n return volume",
"def audio_count(self):\n return self._status[StatusInfo.AUDIO_COUNT]",
"def get_speaker(self):\n return self._speak... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract features on the fly from the recording given a list of peaks. | def compute_features_from_peaks(
recording,
peaks,
feature_list=["ptp", ],
feature_params={},
ms_before=1.,
ms_after=1.,
**job_kwargs,
):
job_kwargs = fix_job_kwargs(job_kwargs)
extract_dense_waveforms = ExtractDenseWaveforms(recording, ms_before=ms_before, ms_after=ms_after, retur... | [
"def features_from_points(self):\n\n filtered_data = self.load_filtered_data()\n logger.info(f'extracting features from {len(filtered_data)} animals')\n \n pbar = tqdm(total=len(filtered_data))\n feats = {}\n for strain, fdata in filtered_data.items():\n feats[st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform a web search using the Google search engine | def google(self, input):
args = input.args or ""
parser = self.OptionParser()
parser.add_option("-d", "-r", "--results", dest="results", default=1, type="int")
(options, args) = parser.parse_args(args.split())
if not args:
raise self.BadInputError()
query = " ".join(args).encode('utf-8'... | [
"def _do_google_search(self):\n pass",
"def googlesearch(query=\"\",g=\"com\",k=\"\",r=\"\"):\n print(\"\\n\")\n\n query = input(\"Search: \")\n\n r = input(\"Number of results: \")\n if r == \"\":\n print(\"No results set. Defaulting to 10.\")\n r = 10\n\n k = input(\"Keywords... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove any attributes that are attached to this node. | def clear_attrs(self):
self._attributes.clear() | [
"def clear_attributes(self):\n self.attrs = etad.AttributeContainer()",
"def clearAttributes(self):\n return _libsbml.XMLToken_clearAttributes(self)",
"def clear(self):\n return _libsbml.XMLAttributes_clear(self)",
"def pop_attributes(self):\n attrs = self.attrs\n self.clear... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all outputs at once, removing anything that was there previously. Note that information about outputs is not stored in the serialized graph. When instantiating a serialized graph, TensorFlow will use its own shape inference to infer the number, type, and shape of the operator's outputs. | def set_outputs_from_pairs(self, new_outputs: Iterable[Tuple[tf.DType,
tf.shape]]):
self._outputs = []
i = 0
for (dtype, shape) in new_outputs:
self._outputs.append(tensor.Tensor(self, i, dtype, shape))
i += 1
self._graph.increme... | [
"def clear_outputs(self):\n self.outputs = []",
"def _transform_outputs(self) -> None:\n self.outputs = None if self.outputs == {} else self.outputs",
"def remove_all_outputs(self):\n self._outs.clear()",
"def infer_outputs(self):\n # TF lack a supported API for invoking shape inferenc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use TensorFlow's shape and dtype inference to determine the number of outputs as well as their shapes and dtypes, based on the node's op type string, its attribute values, and what inputs are connected to it. Inference will only function properly if the currentlyloaded version of TensorFlow knows about the specified op... | def infer_outputs(self):
# TF lack a supported API for invoking shape inference directly,
# so we instantiate a dummy graph and create a dummy Operation object
temp_graph = tf.Graph()
with temp_graph.as_default():
input_placeholders = [tf.placeholder(shape=t.shape, dtype=t.dtype) for
... | [
"def call_node_infer_type(node):\n infer_out = infer_type(node)\n out_type = infer_out._checked_type_\n if isinstance(out_type, TensorType):\n types = [out_type]\n elif isinstance(out_type, TupleType):\n types = list(out_type.fields)\n else:\n raise RuntimeError(f\"Unsupported ou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all input at once, converting TensorFlow stringformat inputs into `Tensor` objects. All nodes referenced in the input strings must be present in the parent graph. | def set_inputs_from_strings(self, new_inputs: Iterable[str],
set_control_inputs: bool = True):
self._inputs = _decode_inputs(new_inputs, self._graph)
if set_control_inputs:
self._control_inputs = _decode_control_inputs(new_inputs, self._graph)
self._graph.increment_versio... | [
"def parse(self, str_input: str, **kwargs) -> 'torch.tensor':",
"def encode_tensorflow(\n self, input_strings: tf.Tensor\n ) -> tuple[tf.Tensor, tf.Tensor]:",
"def _create_string_input_trainable_model():\n\n class BlockWithStringInputs(onnxblock.ForwardBlock):\n def __init__(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract and decode the inputs in a list of TensorFlow input specification strings. Skips over control inputs. | def _decode_inputs(inputs: Iterable[str], g: 'graph.Graph') -> List[
tensor.Tensor]:
# Input names in the protobuf take three forms:
# "^node_name" --> Control input from indicated node
# "node_name" --> Input from output number 0 of indicated node
# "node_name:ix" --> Input from output number <ix> of i... | [
"def _decode_control_inputs(inputs: Iterable[str], g: 'graph.Graph') -> List[\n Node]:\n # Control inputs start with \"^\". Skip everything else and strip off the\n # leading caret character\n control_input_names = [n[1:] for n in inputs if n.startswith(\"^\")]\n return [g[name] for name in control_input_names... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract and decode the control inputs in a list of TensorFlow input specification strings. Skips data inputs. | def _decode_control_inputs(inputs: Iterable[str], g: 'graph.Graph') -> List[
Node]:
# Control inputs start with "^". Skip everything else and strip off the
# leading caret character
control_input_names = [n[1:] for n in inputs if n.startswith("^")]
return [g[name] for name in control_input_names] | [
"def _decode_inputs(inputs: Iterable[str], g: 'graph.Graph') -> List[\n tensor.Tensor]:\n # Input names in the protobuf take three forms:\n # \"^node_name\" --> Control input from indicated node\n # \"node_name\" --> Input from output number 0 of indicated node\n # \"node_name:ix\" --> Input from output ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a Python object or scalar value to a TensorFlow `tf.AttrValue` protocol buffer message. | def _python_type_to_attr_value(value: Any) -> tf.AttrValue:
# TODO(frreiss): Handle AttrValues that are lists
if isinstance(value, tf.AttrValue):
# TODO(frreiss): Should this case result in an error?
return value
# Scalar types, in the order they appear in the .proto file
elif isinstance(value, str):
... | [
"def set_value(value):\n proto_value = proto.Value()\n if isinstance(value, int):\n proto_value.integer_value = value\n elif isinstance(value, float):\n proto_value.real_value = value\n elif isinstance(value, str):\n proto_value.string_value = value\n else:\n raise ProtoEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the headers to use for the API invocation. Attemps to use a Query API key, if it exists, then falls back to a User API if no query API key is returned. | def _build_headers(self, params: Dict) -> None:
api_key = self._get_query_api_key(params) or self.user_api_key
if api_key is None:
raise RedashApiKeyNotProvidedException('No API key provided')
self.headers = {"Authorization": "Key {}".format(api_key)} | [
"def _api_headers(self, username=None):\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n if username:\n auth = jwt.encode({\"identity\": {\"username\": username},\n \"nbf\": 1493862425,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function can be overridden by sub classes to look up the specific API key to use for a given database / cluster / schema / table combination. | def _get_query_api_key(self, params: Dict) -> Optional[str]:
return None | [
"def get_api_key(api_key):\n api.get(api_key)",
"def api_key(self) -> Any:\n return pulumi.get(self, \"api_key\")",
"def get_api_key(instance):\n\n # TODO make this work with environment variables or else\n # by getting the api-key from ~/.config/flywheel/user.json\n # if the KEY_FILE is not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows customization of the 'WHERE' clause to be provided for each set of parameters by the client implementation. Defaults to an empty string. | def get_where_clause(self, params: Dict) -> str:
return '' | [
"def where_clause(self, kwargs):\n where_clause = super(AnalyticalTools, self).where_clause(kwargs)\n if '_id' in kwargs:\n where_clause &= Expression(AnalyticalTools.id, OP.EQ, kwargs['_id'])\n if 'name' in kwargs:\n name_oper = OP.EQ\n if 'name_operator' in kw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a dictionary of parameters that will be injected into the Redash query template. The keys in this dictionary MUST be a casesensitive match to the template names in the Redash query and you MUST have the exact same parameters, no more, no less. Override this function to provide custom values. | def build_redash_query_params(self, params: Dict) -> Dict:
return {
'parameters': {
'SELECT_FIELDS': self.get_select_fields(params),
'SCHEMA_NAME': params.get('schema'),
'TABLE_NAME': params.get('tableName'),
'WHERE_CLAUSE': self.get_wh... | [
"def get_parameters_dictionary(request):\n parameters_dict = {PARAMETER_MESSAGE: request.GET.get('message'),\n PARAMETER_ENTITY_NAME: request.GET.get('entity_name'),\n PARAMETER_STRUCTURED_VALUE: request.GET.get('structured_value'),\n PARAMETER_FA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts a query in Redash. Returns a job ID that can be used to poll for the job status. | def _start_redash_query(self, query_id: int, query_params: Dict) -> Tuple[Any, bool]:
url_inputs = {'redash_host': self.redash_host, 'query_id': query_id}
query_url = REDASH_SUBMIT_QUERY_ENDPOINT.format(**url_inputs)
resp = r.post(query_url, json=query_params, headers=self.headers)
resp... | [
"def launch_query(self):\r\n self.query_launched = True\r\n self.query = self.build_query()\r\n self.result = self.query.execute()\r\n if self.result == True:\r\n log(self.log, _(\"## Displaying results...\"), progress=20, function=\"AppQuery.launch_query\", close=True)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a FlaskResponse object, where the response data represents a json object with the preview data accessible on 'preview_data' key. The preview data should match amundsen_application.models.preview_data.PreviewDataSchema | def get_preview_data(self, params: Dict, optionalHeaders: Dict = None) -> FlaskResponse:
LOGGER.debug('Retrieving preview data from Redash with params: %s', params)
try:
query_id = self.get_redash_query_id(params)
if query_id is None:
raise RedashQueryTemplateDoes... | [
"def preview(self, **kwargs):\n return self.get(\"results_preview\", **kwargs).body",
"def preview(self):\n if self._preview is None:\n from twilio.rest.preview import Preview\n self._preview = Preview(self)\n return self._preview",
"def preview(self):\n if self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run 100 episodes, then report results | def test():
env = gym.make('CartPole-v1')
results = []
for _ in range(100):
results.append(episode(env, render=False, verbose=False))
print(f'average={sum(results) / len(results)} '
f'max={max(results)} '
f'min={min(results)}') | [
"def run(self) -> None:\n for episode in range(1, self.episodes + 1):\n print('Episode:', episode)\n steps, state_action_history = self.run_one_episode()\n self.steps_per_episode.append(steps)\n if episode % parameters.CACHING_INTERVAL == 0 or steps < 1000:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update target parameters to be closer to those of source parameters using an exponential moving average. | def update_ema(target_params, source_params, rate=0.99):
for targ, src in zip(target_params, source_params):
targ.detach().mul_(rate).add_(src, alpha=1 - rate) | [
"def move_average(source, target, tau=0.005):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(\n target_param.data * (1.0 - tau) + param.data * tau\n )",
"def _updateParameters(self):\n pass #future tool\n #update A <-- should... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Zero out the parameters of a module and return it. | def zero_module(module):
for p in module.parameters():
p.detach().zero_()
return module | [
"def reset_parameters(self):\n self.module.reset_parameters()",
"def emptyModule():\n return(Module(\"\",[]))",
"def resetParameter(pname):\n dislin.reset(pname)",
"def reset_parameters(model: torch.nn.Module) -> None:\n logging.info(\"Resetting model parameters.\")\n for _, module in model... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scale the parameters of a module and return it. | def scale_module(module, scale):
for p in module.parameters():
p.detach().mul_(scale)
return module | [
"def remove_weight_scale(module: Module, name: str = 'weight') -> Module:\n return remove_weight_lambda(module, 'scale', name)",
"def scale(self):",
"def GetScale(self):\n ...",
"def scale_parameters(cls, parameters, parameters_min, parameters_max):\n if isinstance(parameters, dict):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create sinusoidal timestep embeddings. | def timestep_embedding(timesteps, dim, max_period=10000):
half = dim // 2
freqs = paddle.exp(-math.log(max_period) * paddle.arange(start=0, end=half, dtype=paddle.float32) / half)
args = paddle.cast(timesteps[:, None], 'float32') * freqs[None]
embedding = paddle.concat([paddle.cos(args), paddle.sin(args... | [
"def timestep_embedding(timesteps, dim, max_period=10000):\n half = dim // 2\n freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half)\n args = timesteps[:, None].float() * freqs[None]\n embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts the DataFrame to the database and table provided. Creates an insert query for each row in dataframe and send to db. | def insert_data(df, database, table, db_uri):
try:
engine = sqlalchemy.create_engine(db_uri)
df = create_hash_id(df)
def create_insert_sql(x):
cols = "`" + "`,`".join(list(df.columns)) + "`"
values = "\'" + "\',\'".join(list(x)) + "\'"
... | [
"def execute_sql_insert(self, df, table_name):\n sql_request = create_sql_request_header(df, table_name)\n sql_content = [create_sql_request_row(row) for index, row in df.iterrows()]\n self.cur.executemany(sql_request, sql_content)\n self.conn.commit()\n print('> {} : dataframe co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the data in table using the provided key and values | def update_data(self, update_key, update_values):
engine = sqlalchemy.create_engine(self.db_uri)
final_where_cond = create_cond_string(update_key, flag='where')
read_sql = f"SELECT * FROM {self.database_params['database']}.{self.database_params['table']} WHERE {final_where_cond};"
upda... | [
"def update(self, key, *columns):\n self.table.update_record(key, columns)",
"def update(self, table, key, value, values):\n\n self._check_values(values)\n self._check_connection()\n alls = []\n for k, v in values.items():\n if k != key:\n if isinstance... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that q_hat_cov has the right shape and accepts keys in correct format. Also validate with arbitrary number of delays. | def test_cov_q(self, ndlys=13):
for d in self.d:
d.flag_array[:] = False #ensure that there are no flags!
d.select(times=np.unique(d.time_array)[:10], frequencies=d.freq_array[:16])
for d_std in self.d_std:
d_std.flag_array[:] = False
d_std.select(times=np... | [
"def test_q_hat(self):\n # Set weights and pack data into PSpecData\n self.ds = pspecdata.PSpecData(dsets=self.d, wgts=self.w)\n Nfreq = self.ds.Nfreqs\n Ntime = self.ds.Ntimes\n Ndlys = Nfreq - 3\n self.ds.spw_Ndlys = Ndlys\n\n\n # Set baselines to use for tests\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test cov_p_hat, verify on identity. | def test_cov_p_hat(self):
self.ds = pspecdata.PSpecData(dsets=self.d, wgts=self.w, dsets_std=self.d_std)
cov_p = self.ds.cov_p_hat(np.sqrt(6.)*np.identity(10),np.array([5.*np.identity(10)]))
for p in range(10):
for q in range(10):
if p == q:
self.a... | [
"def test_identity_mean():\n n_trials, n_channels = 100, 3\n covmats, _, _ = generate_cov(n_trials, n_channels)\n C = mean_identity(covmats)\n assert np.all(C == np.eye(n_channels))",
"def test_estimate_pmv():\n env = TropicalPrecooling()\n assert(env.estimate_pmv(22.0, 23.0, 25) == -1)\n ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test truncation of Rmatrices. These should give a q_hat that is all zeros outside of the with fstart and fend. | def test_R_truncation(self):
self.ds = pspecdata.PSpecData(dsets=self.d, wgts=self.w)
Nfreq = self.ds.spw_Nfreqs
Ntime = self.ds.Ntimes
Ndlys = Nfreq - 3
self.ds.spw_Ndlys = Ndlys
# Set baselines to use for tests
key1 = (0, 24, 38)
key2 = (1, 25, 38)
... | [
"def test_truncate_seqs(self):\r\n\r\n base_pos = 5\r\n\r\n fasta_seqs = {'seq1': 'GAAATCAAGAATAC',\r\n 'seq2': 'ATAAACAAGAT'}\r\n qual_scores = {'seq1': array(map(str, [20, 10, 15, 25, 24, 25, 27])),\r\n 'seq2': array(map(str, [22, 21, 15, 12, 22, 25,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that q_hat has right shape and accepts keys in the right format. | def test_q_hat(self):
# Set weights and pack data into PSpecData
self.ds = pspecdata.PSpecData(dsets=self.d, wgts=self.w)
Nfreq = self.ds.Nfreqs
Ntime = self.ds.Ntimes
Ndlys = Nfreq - 3
self.ds.spw_Ndlys = Ndlys
# Set baselines to use for tests
key1 = (0... | [
"def test_H_hat(self):\n\t\tposition = [0.0, 1.57079, 3.14159, 4.71238, 6.28318, 7.85398, 9.42477]\n\t\tpotential = [0.0, 6.0, 0.0, -6.0, 0.0, 6.0, 0.0]\n\t\tc = 1\n\t\tposition = tf.constant(position, shape = [1, len(position)], dtype = tf.float32)\n\t\tpotential = tf.constant(potential, shape = [1, len(potential)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test window function computation in ds.pspec() This is complementary to test_get_MW above. | def test_window_funcs():
# get a PSpecData
uvd = UVData()
uvd.read_miriad(
os.path.join(DATA_PATH, 'zen.even.xx.LST.1.28828.uvOCRSA'),
use_future_array_shapes=True
)
beam = pspecbeam.PSpecBeamUV(os.path.join(DATA_PATH, "HERA_NF_dipole_power.beamfits"))
ds = pspecdata.PSpecData(ds... | [
"def test_window_filter(self):\n test_window_scheme = WindowingScheme(self.window_test_filter, 5)\n filtered_value = test_window_scheme.filter(self.middle_value)\n self.assertEquals(filtered_value, self.middle_value)",
"def test_windows_df():\r\n heat_gamelog = create_gamelog('miami', '201... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Let's add a price modifier to the settings, then load it, then call a method on it to make sure it works. | def test_01_cart_modifier_pool_loads_modifiers_properly(self):
MODIFIERS = [
'shop.cart.modifiers.tax_modifiers.TenPercentGlobalTaxModifier']
with SettingsOverride(SHOP_CART_MODIFIERS=MODIFIERS):
thelist = modifiers_pool.cart_modifiers_pool.get_modifiers_list()
self.a... | [
"def test_add_price_strategy(self):\n pass",
"def testSetPrice(self):\n self.my_book.setPrice(\"8888888888888\")\n self.assertEqual(\"8888888888888\",self.my_book.price)",
"def test_update_price_strategy(self):\n pass",
"def test_get_price_strategy(self):\n pass",
"def set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans and memoizes all nontrivial entity hooks. | def refresh_entity_hooks(self):
for hook_name in HOOK_NAMES:
hooks = []
for entity in self._task.root_entity.iter_entities():
entity_hook = getattr(entity, hook_name)
# Ignore any hook that is a no-op to avoid function call overhead.
if not _callable_is_trivial(entity_hook):
... | [
"def __call__(self):\n for hook in self.hooks:\n hook()",
"def build_hooks(self):\n cfg = self.cfg.clone()\n cfg.defrost()\n cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN\n\n ret = \\\n [\n hooks.IterationTimer(),\n hooks.LRScheduler(self.opti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new Physics using the latest MJCF model from the task. | def _recompile_physics(self):
if getattr(self, '_physics', None):
self._physics.free()
self._physics = mjcf.Physics.from_mjcf_model(
self._task.root_entity.mjcf_model) | [
"def _create_model(self, cfg, ckpt_file): \n\n # specify models hyperparameters - loaded from config yaml\n model_params = cfg['MODEL']\n filter_widths = model_params['filter_widths'] #[3,3,3,3,3]\n dropout = model_params['dropout'] #0.25\n channels = model_params['channels'] #1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a `weakref.ProxyType` pointing to the current `mjcf.Physics`. Note that the underlying `mjcf.Physics` will be destroyed whenever the MJCF model is recompiled. It is therefore unsafe for external objects to hold a reference to `environment.physics`. Attempting to access attributes of a dead `Physics` instance wi... | def physics(self):
return self._physics_proxy | [
"def physics_type(self):\n return self._get_physics_type()",
"def _recompile_physics(self):\n if getattr(self, '_physics', None):\n self._physics.free()\n self._physics = mjcf.Physics.from_mjcf_model(\n self._task.root_entity.mjcf_model)",
"def net_alchemical_force(self):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes the reward returned by this environment. This will be the output of `self.task.reward_spec()` if it is not None, otherwise it will be the default spec returned by `dm_env.Environment.reward_spec()`. | def reward_spec(self):
task_reward_spec = self._task.get_reward_spec()
if task_reward_spec is not None:
return task_reward_spec
else:
return super(Environment, self).reward_spec() | [
"def reward(self):\n return self._reward",
"def reward_status(self):\n return self._reward_status",
"def _reward(self):\n return self._goal_reward - 0.9 * (self.step_count / self.max_steps)",
"def _compute_reward(self): \n reward = -1\n return reward",
"def _compute... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes the discount returned by this environment. This will be the output of `self.task.discount_spec()` if it is not None, otherwise it will be the default spec returned by `dm_env.Environment.discount_spec()`. | def discount_spec(self):
task_discount_spec = self._task.get_discount_spec()
if task_discount_spec is not None:
return task_discount_spec
else:
return super(Environment, self).discount_spec() | [
"def discount(self):\n return self._discount",
"def discount_message(self):\n discount_amount_str = '-£{:.2f}'.format(self.discount_amount/100)\n if self.discount_amount < 100:\n discount_amount_str = '-{}p'.format(self.discount_amount)\n if self._promotion:\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the observation specification for this environment. | def observation_spec(self):
return self._observation_updater.observation_spec() | [
"def observation_spec(self):\n observation = self.viewer._get_observations() if self.viewer_get_obs else self._get_observations()\n return observation",
"def observation_spec(self):\n # Get the inner observation spec, which is a dictionary.\n inner_obs_spec = super().observation_spec()\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dataframe called dfDates by passing a start_date and end_date | def create_dates_dataframe(start_date,end_date):
DateList = [start_date]
while max(DateList) < end_date:
DateKey = max(DateList) + timedelta(days=1)
DateList.append(DateKey)
DateList.sort()
dfDates = pd.DataFrame(pd.to_datetime(DateList), columns = ['DateKey'])
return dfDates | [
"def to_stock_dataframe_range(self, start_date=None, end_date=None):\n if end_date is None:\n end_date = self.dates[-2]\n if type(end_date) is pd.tslib.Timestamp:\n end_date = end_date.strftime(\"%Y-%m-%d\")\n if type(end_date) is not datetime.datetime and type(end_date) i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a cross join (cartesian product) between two dataframes by using a constant temporary key. Also sets a MultiIndex which is the cartesian product of the indices of the input dataframes. | def dataframe_crossjoin(df1, df2, **kwargs):
df1['_tmpkey'] = 1
df2['_tmpkey'] = 1
res = pd.merge(df1, df2, on='_tmpkey', **kwargs).drop('_tmpkey', axis=1)
res.index = pd.MultiIndex.from_product((df1.index, df2.index))
df1.drop('_tmpkey', axis=1, inplace=True)
df2.drop('_tmpkey', axis=1, inpla... | [
"def cross(df1, df2, **kwargs):\r\n df1['_tmpkey'] = 1\r\n df2['_tmpkey'] = 1\r\n\r\n res = pd.merge(df1, df2, on='_tmpkey', **kwargs).drop('_tmpkey', axis=1)\r\n res.index = pd.MultiIndex.from_product((df1.index, df2.index))\r\n\r\n df1.drop('_tmpkey', axis=1, inplace=True)\r\n df2.drop('_tmpkey'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes an audio file into an Example proto. | def create_example(filename, hparams):
wav_data = audio_io.samples_to_wav_data( # class bytes
librosa.util.normalize(librosa.core.load(
filename, sr=hparams.sample_rate)[0]), hparams.sample_rate)
example = tf.train.Example(features=tf.train.Features(feature={
'id':
tf... | [
"def audio_file_load():\n raise NotImplementedError()",
"def test_process_mono_file(self):\n test_path = pathlib.Path(__file__).parent.absolute() / 'data/mono.wav'\n self.default_kwargs['input_file'] = test_path\n self.default_kwargs['output_file'] = pathlib.Path(self.temp_file.name)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Convenience function) Return the norm of the baseline between antennae and | def baselength(ant_ID1, ant_ID2):
return np.linalg.norm(baseline(ant_ID1, ant_ID2)) | [
"def avgBaseline():\n return aBaseline",
"def avgLongBaseline():\n return aLongBaseline",
"def avgShortBaseline():\n return aShortBaseline",
"def _norm(base_point):\n return space.metric.squared_norm(next_to_next_next, base_point)",
"def baseline(ant_ID1, ant_ID2):\n return an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the baseline between antennae and by a simple difference of their coordinates. | def baseline(ant_ID1, ant_ID2):
return ant_pos[ant_ID2] - ant_pos[ant_ID1] | [
"def avgBaseline():\n return aBaseline",
"def _get_baseline(self):\n return Point(self.x, self.y)",
"def get_baseline(self):\n register = self.__read_register(self.__BASELINE_REG, 2)\n HB = register[0]\n LB = register[1]\n return (HB << 8) | LB",
"def baseline(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the phase factor in the direction (l, m) (we assume that n is of insignificant magnitude) and at the frequency between two antennae whose ID s are and . When we calculate the baseline (u, v, w), we assume that w is of insignificant magnitude. | def phase_factor(ant1, ant2, r, nu=151e6):
b = baseline(ant1, ant2)[0:2] # kill w
br = np.dot(b, r)
return np.exp(-2j * np.pi * nu * br / c) | [
"def calc_phase_resids(self):\n rs = self.model.phase(self.toas.table)\n rs -= Phase(rs.int[0],rs.frac[0])\n rs -= Phase(0.0,rs.frac.mean())\n return rs.frac",
"def get_phase(a,ta, b, tb):\n a = get_xmin(a,ta)\n b = get_xmin(b,tb)\n a = a[:10]\n b = b[:10]\n c = a-b\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of the field rendered for df. | def render_df(self, field: str) -> str:
value = self.__getattribute__(field)
if field in ["date", "workers"]:
return str(value)
elif field in ["locations", "struggles", "companies", "tags", "sources"]:
return str(value).strip("[").strip("]").replace("'", "").replace('"', ... | [
"def field_value(self):\n return self._field_value",
"def get_value_field(self):\n\n return self.value_field",
"def _raw_value(self, fieldname):\n field = self.fields[fieldname]\n prefix = self.add_prefix(fieldname)\n return field.widget.value_from_datadict(self.data, self.fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert field for markdown Takes a td BeautifulSoup object and updates it according to the field type so that it renders correctly in markdown. | def to_md(self, field: str, td: bs4.element.Tag) -> str:
assert (
field in self.__dataclass_fields__
), f"Cannot serialize {field}. Not a valid field in Action."
value = self.__getattribute__(field)
if field in ["date", "workers"]:
td.string = str(value)
... | [
"def render_markdown(sender, instance, *args, **kwargs):\n md = markdown.Markdown(safe_mode='escape')\n\n for fieldname, _ in instance.__dict__.items():\n if fieldname.endswith(\"_html\"):\n fieldname_raw = fieldname[:fieldname.find('_html')]\n field_raw = getattr(instance, fieldn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an Action instance from a md table. | def create_from_md(cls, table: bs4.element.Tag) -> "Action":
a = {}
trs = table.find_all("tr")
for key, val in table.attrs.items():
if key != "class":
a[key] = val
for i, tr in enumerate(trs):
td_key = tr.find("td", class_="field-key")
... | [
"def read_from_md(cls, md_doc: MarkdownDocument) -> \"Actions\":\n md_data = re.findall(fr'<div id=\"{cls.action_id}\">+[\\s\\S]+<\\/div>', md_doc)\n assert len(md_data) == 1, f\"multiple divs with id={cls.action_id} were found\"\n md_data = md_data[0]\n soup = BeautifulSoup(md_data, \"h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an Action instance from a dataframe row. | def create_from_row(cls, row: pd.Series) -> "Action":
fields = [
key
for key, value in cls.__dataclass_fields__.items()
if value.type != ClassVar
]
d = {key: value for key, value in row.to_dict().items() if key in fields}
return cls(**d) | [
"def read_from_df(df: pd.DataFrame) -> \"Actions\":\n actions = Actions()\n for i, row in df.iterrows():\n action = Action.create_from_row(row)\n actions.append(action)\n return actions",
"def from_rdd(cls, row):\n return cls(**row.asDict())",
"def from_data_row... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the list of actions. | def sort(self, *args, **kwargs) -> "Actions":
self.actions.sort(*args, **kwargs)
return self | [
"def sort(self):\n self.tasks = sorted(self.tasks, key=lambda k: k.priority, reverse=True)",
"def getActions(self):\n actions = self.context.aq_inner.getActions(None, False)\n actions = [a[0] for a in actions]\n actions.sort(key=lambda elt: elt.id.lower())\n return actions",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append an action onto this instance of Actions. | def append(self, action: Action):
self.actions.append(action) | [
"def addAction(self, action):\n self.actions.append(action)",
"def add_action(self, action):\n self._actions.append(action)",
"def add_action(self,action):\n self.actions.append(action)",
"def append_action(self, action = 'r'):\n self.actions += [action]",
"def add_action(self, a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |