query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Sets some global OpenGL states. | def setOpenGLState(self):
# Enable transparency.
pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
pyglet.gl.glEnable(pyglet.gl.GL_BLEND) | [
"def initializeGL(self):\n pass",
"def initgl(self):\r\n # Set the screen background color. \r\n glClearColor( 0.0, 0.0, 0.0, 1.0 )\r\n \r\n # Enable back face culling. \r\n glEnable( GL_CULL_FACE )\r\n \r\n # Initialize viewport and projection. \r\n self.resize()\r\n \r\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the group to the corresponding index. Return group 0 if it is too small, self. layers if two big and otherwise just take the integer value. A higher value means that it will be drawn on top of the other layers. Very powerful to sort 2D stuff in the OpenGL window. | def getGroup(self, index):
index = int(index)
if index < 0:
return self.top_group1
elif index > (self.layers - 1):
index = (self.layers - 1)
return self.groups[index] | [
"def get_group_index(self, index):\n\n g_index = None\n for group in self.groups:\n if group[0] == index:\n g_index = group[1]\n break\n return g_index",
"def _get_group_index(self, index):\n\n g_index = 0\n for group in self.groups:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using ordered groups enables using sorted vertex list in one single batch which then renders as efficiently as possible. | def _createdOrderedGroups(self):
self.groups = []
for _i in xrange(self.layers):
self.groups.append(pyglet.graphics.OrderedGroup(_i))
# Create one top level group. Useful for dialog boxes and other stuff
# that goes over everything else.
self.top_group1 = pyglet.graph... | [
"def _create_vertex_list(self):\n raise NotImplementedError('_create_vertex_list must be defined in '\n 'order to use group or batch properties')",
"def color_groups(groups, colors, data_color_order):\r\n group_num = -1\r\n for g in natsort(groups):\r\n if g no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the box, the frame and pops the top handlers from the stack. | def delete_and_pop_handlers():
self.zoom_box.delete()
self.zoom_frame.delete()
self.zoom_box = None
# Popping handlers.
# XXX: Are these always the right handlers??
self.win.window.pop_handlers()
# Return to the default cursor.
... | [
"def del_frame(self):\n self.stack.del_frame()",
"def removeFrame(self, frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\n frame.pack_forget()",
"def on_closing(self):\n self.stack.clear()\n print(self.stack)\n del self.stack[:]\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an interactive Altair heatmap of parameter correlations with user defined x and y parameters. The xy selection will be highlighted in pink. | def altair_heatmap(corr_matrix: pd.DataFrame, x_selection: str = None, y_selection: str = None) -> alt.Chart:
pair = alt.selection_single(fields=["x", "y"], clear=False, name="pair")
chart = alt.Chart(corr_matrix.round(2)).mark_rect(tooltip=True).encode(
x=alt.X('x', title=None),
y=alt.Y('y', ti... | [
"def heatmap(self, **kwargs) -> None:\n self.initialization_figure\n self.builder.get_heat_mapplot(**kwargs)",
"def correlation_heatmap(df):\n heatmap = go.Heatmap(\n z=df.corr(method=\"pearson\").as_matrix(),\n x=df.columns,\n y=df.columns,\n colorbar=dict(title=\"Pea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an interactive Altair scatter plot with user defined x and y parameters as well as an optional third parameter used for marker color gradient. | def altair_scatter(dataset: pd.DataFrame, x_selection: str, y_selection: str, color_selection: str) -> alt.Chart:
# use set to handle edge case of duplicated axes or 'Date' selection
tooltip = list(set(['Date', x_selection, y_selection, color_selection]))
if color_selection == '<select>':
tooltip.r... | [
"def scatter(x,y,colorby,xlabel,ylabel,title,new_data):\n trace1 = go.Scatter(\n x = x,\n y = y,\n mode='markers',\n marker=dict(\n size=16,\n color = new_data[colorby], #set color equal to a variable\n colorscale='Viridis',\n showscale=True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a Plotly heatmap of parameter correlations. | def plotly_heatmap(corr_matrix: pd.DataFrame) -> go.Figure:
title = "Metrics Summary: Pearson's Correlation"
data = [go.Heatmap(x=corr_matrix.columns,
y=corr_matrix.index,
z=corr_matrix,
colorscale='Blues',
colorbar=dict... | [
"def correlation_heatmap(df):\n heatmap = go.Heatmap(\n z=df.corr(method=\"pearson\").as_matrix(),\n x=df.columns,\n y=df.columns,\n colorbar=dict(title=\"Pearson Coefficient\"),\n colorscale=\"Reds\",\n )\n\n layout = go.Layout(title=\"Matriz de correlaciones\")\n\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a multiline timeseries Plotly plot. Plot both the x and y selection variables. | def plotly_line(dataset: pd.DataFrame, x_selection: str, y_selection: str, date_col: str = 'Date') -> go.Figure:
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(x=dataset.loc[:, date_col],
y=dataset.loc[:, x_selection],
mode='lines+mar... | [
"def scatter_chart(self):\n plotly.offline.plot(\n [go.Scatter(x=self.pd.hour, y=self.pd.events)],\n auto_open=True,\n filename=\"hourly_line_chart\"\n )",
"def sparkline(plot_df):\n\n figure = {\n \"data\": [\n go.Scatter(\n x=plo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the parameters required to align the shape to the given shape using the weight matrix w. This applies a scaling, transformation and rotation to each point in the shape to align it as closely as possible to the shape. This relies on some linear algebra which we use numpy to solve. [ X2 Y2 W 0][ax] [X1] [ Y2 X2 0 W]... | def get_alignment_params(self, s, w):
X1 = s.__get_X(w)
X2 = self.__get_X(w)
Y1 = s.__get_Y(w)
Y2 = self.__get_Y(w)
Z = self.__get_Z(w)
W = sum(w)
C1 = self.__get_C1(w, s)
C2 = self.__get_C2(w, s)
a = np.array([[ X2, -Y2, W, 0],
... | [
"def get_alignment_params(self, s, w):\n\n X1 = s.__get_X(w)\n X2 = self.__get_X(w)\n Y1 = s.__get_Y(w)\n Y2 = self.__get_Y(w)\n Z = self.__get_Z(w)\n W = sum(w)\n C1 = self.__get_C1(w, s)\n C2 = self.__get_C2(w, s)\n\n a = np.array([[ X2, -Y2, W, 0],\n [ Y2, X2, 0,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if this is the vert in an open edge that should not have a post | def vert_is_open(v, front, left, right, prop):
if prop.open_side == "LEFT":
if v in left.verts and v not in front.verts:
return True
elif prop.open_side == "RIGHT":
if v in right.verts and v not in front.verts:
return True
return False | [
"def check_edge(self):\n if self.rect.right >= self.screen.get_rect().right or self.rect.left <= 0:\n return True",
"def isInactive(edge):\n if edge[2] >= len(edge[4]): return 1\n return 0",
"def onEdge(self, position):\n drawer_collision = self.drawerCollision(position)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain string representation of the Interface Status object. | def __str__(self):
sb = ''
sb += '\nInterfaceStatus [ ' + self.interface_name + ' ]\n'
sb += '\tLinkState : ' + str(self.InterfaceState.enumval(self.link)) + '\n'
sb += '\tLineProtoState : ' + str(self.InterfaceState.enumval(self.lineproto)) + '\n'
return sb | [
"def __str__(self):\n struct_repr = \", \".join([\n \"was_available_once: \" + str(self.was_available_once),\n \"is_available: \" + str(self.is_available),\n \"signal_strength_percent: \" + str(self.signal_strength_percent)\n ])\n\n return f\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the id for the entity if not present and save it to the data store | def save(self):
if not self.id:
self.id = uuid4()
DataStore.add_instance(self) | [
"def _create_entity(self, model_name, entity):\n model_pool = self.pool.get(model_name)\n prepared_entity = self._prepare_entity(model_name, entity)\n if not prepared_entity:\n logger.debug(\"Prepared entity is empty : %s model %s\" % (prepared_entity, model_name))\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use numpy operations to add padding around an image in numpy format (an array of rank 3 so 3 channels) in order to create a square image. Function saves the newly padded image to a new file in the output directory specified. Args | def pad_image(np_img, new_img_file):
h, w, c = np_img.shape
side_len = max(h, w)
# Create our square "palette" or area upon which the image data is placed
# Make it kinda grey (e.g. a palette of all > 1)
new_np_img = np.ones(side_len * side_len * c).reshape(side_len,
side_len, c) * 100
... | [
"def run_padding(self):\n\n image_padded, mask, self.pad_to_right, self.pad_to_bottom = gen_padded_image_and_mask (os.path.join('utils_dfn/temp', self.file_name_with_ext),\n self.new_height, self.new_width)\n cv2.imwrite(os.path.jo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loops through all image in given input directory. Reads each file in a try/except block in the instance the file is not an image (it is then skipped). Calls a function to add padding to square up the image and saves it to a new file. | def main():
# Just grab all files - we'll use try/except to filter
images = glob.glob(os.path.join(args.input_dir, '*.*'))
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
for img_file in images:
print(img_file)
try:
np_img = plt.imread(img_file)
... | [
"def process_images():\n create_dirs()\n for root, dirs, files in os.walk(IN):\n for name in files:\n if name[0] == '.':\n continue\n process_image(name)",
"def pad_images(_input_image_paths : list[str], _output_image_dir : str, \\\n _pad_colour : tuple[int,int,int]) -> None:\n for ima... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tests each password against all dictionary words | def testPassword(cryptPass, dictionaryFile):
#salt = cryptPass[0:2]
salt = crypt.mksalt(crypt.METHOD_SHA512) # Updated for SHA512 encrypted passwords
dictFile = open(dictionaryFile, 'r')
for word in dictFile.readlines():
word = word.strip('\n')
cryptWord = crypt.crypt(word, salt)
... | [
"def testPass(passFile,dictFile):\n\n\t# The passFile contains various ':' separated fields,\n\t# of which the 1st is the username, and the 2nd is\n\t# the hash of the password itself.\n\tpwd = open(passFile,'r').readlines()[0].strip().split(\":\")\n\tuser,hash = pwd[0],pwd[1]\n\n\t# The salt is the combination of ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a coordinate box from a map. | def bounding_box_from_map(map_car):
shape, wcs = map_car.data.geometry
return enmap.box(shape, wcs) | [
"def get_tile_box(zoom, x, y):\n\n minlng, minlat = get_lng_lat_from_tile_pos(zoom, x, y)\n maxlng, maxlat = get_lng_lat_from_tile_pos(zoom, x + 1, y + 1)\n\n return (minlng, maxlng, minlat, maxlat)",
"def get_tile_box(box_latlon, z):\n lat0, lon0, lat1, lon1 = box_latlon\n x0, y0 = deg2num(lat0, l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a ``so_map`` from an enmap (pixell format). | def from_enmap(emap):
new_map = so_map()
hdulist = emap.wcs.to_fits()
header = hdulist[0].header
new_map.pixel = header["CTYPE1"][-3:]
try:
new_map.ncomp = header["NAXIS3"]
except:
new_map.ncomp = 1
new_map.data = emap.copy()
new_map.nside = None
new_map.geometry = n... | [
"def si_this_map_OLD(map):\n # Find out the value units and convert this and data to SI\n units = 1.0 * u.Unit(map.meta['bunit']).to(u.Tesla) * u.Tesla\n data = deepcopy(map.data) * units.value\n\n # ATM I don't convert the x-axis and y-axis to SI\n\n # Modify the map header to reflect all these chan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Project a HEALPIX ``so_map`` into a CAR ``so_map``. The projection will be done in harmonic space, you can specify a lmax to choose a range of multipoles considered in the projection. If the coordinate of the map and the template differ, a rotation will be performed. | def healpix2car(healpix_map, template, lmax=None):
project = template.copy()
if healpix_map.coordinate is None or template.coordinate is None:
rot = None
elif healpix_map.coordinate == template.coordinate:
rot = None
else:
print(
"will rotate from %s to %s coordinat... | [
"def full_sky_car_template(ncomp, res):\n\n if ncomp == 3:\n pre = (3,)\n else:\n pre = ()\n\n res = res * np.pi / (180 * 60)\n temp = so_map()\n shape, wcs = enmap.fullsky_geometry(res=res, dims=pre)\n temp.data = enmap.zeros(shape, wcs=wcs, dtype=None)\n temp.pixel = \"CAR\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ``so_map`` template with healpix pixellisation. | def healpix_template(ncomp, nside, coordinate=None):
temp = so_map()
if ncomp == 3:
temp.data = np.zeros((3, 12 * nside ** 2))
else:
temp.data = np.zeros((12 * nside ** 2))
temp.pixel = "HEALPIX"
temp.ncomp = ncomp
temp.nside = nside
temp.geometry = "healpix geometry"
... | [
"def generate_map(self):\n map = Map.Map(50, 80, 1000, 10, 6)\n\n #here we can map out our larger map structure\n if self.level < 2:\n map.make_greathall()\n elif self.level >= 2 and self.level < 20:\n map.make_map()\n elif self.level >= 20:\n map.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ``so_map`` template with CAR pixellisation in equ coordinates. | def car_template(ncomp, ra0, ra1, dec0, dec1, res):
if ncomp == 3:
pre = (3,)
else:
pre = ()
box = get_box(ra0, ra1, dec0, dec1)
res = res * np.pi / (180 * 60)
temp = so_map()
shape, wcs = enmap.geometry(box, res=res, pre=pre)
temp.data = enmap.zeros(shape, wcs=wcs, dtype=N... | [
"def full_sky_car_template(ncomp, res):\n\n if ncomp == 3:\n pre = (3,)\n else:\n pre = ()\n\n res = res * np.pi / (180 * 60)\n temp = so_map()\n shape, wcs = enmap.fullsky_geometry(res=res, dims=pre)\n temp.data = enmap.zeros(shape, wcs=wcs, dtype=None)\n temp.pixel = \"CAR\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ``so_map`` full sky template with CAR pixellisation in equ coordinates. | def full_sky_car_template(ncomp, res):
if ncomp == 3:
pre = (3,)
else:
pre = ()
res = res * np.pi / (180 * 60)
temp = so_map()
shape, wcs = enmap.fullsky_geometry(res=res, dims=pre)
temp.data = enmap.zeros(shape, wcs=wcs, dtype=None)
temp.pixel = "CAR"
temp.nside = None... | [
"def car_template(ncomp, ra0, ra1, dec0, dec1, res):\n\n if ncomp == 3:\n pre = (3,)\n else:\n pre = ()\n\n box = get_box(ra0, ra1, dec0, dec1)\n res = res * np.pi / (180 * 60)\n temp = so_map()\n shape, wcs = enmap.geometry(box, res=res, pre=pre)\n temp.data = enmap.zeros(shape, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a white noise realisation corresponding to the template pixellisation | def white_noise(template, rms_uKarcmin_T, rms_uKarcmin_pol=None):
noise = template.copy()
rad_to_arcmin = 60 * 180 / np.pi
if noise.pixel == "HEALPIX":
nside = noise.nside
pixArea = hp.pixelfunc.nside2pixarea(nside) * rad_to_arcmin ** 2
if noise.pixel == "CAR":
pixArea = noise.d... | [
"def make_noise_image():\n np.random.seed(seed)\n image = np.random.random(size=imsize)\n # force zero mean and unit variance\n image -= np.mean(image)\n image /= np.std(image)\n # make rms = noise\n image *= noise\n image = gaussian_filter(image, sigma=pix_per_beam*FWHM2CC)\n image = np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a point source mask in a binary template | def generate_source_mask(binary, coordinates, point_source_radius_arcmin):
mask = binary.copy()
if mask.pixel == "HEALPIX":
vectors = hp.ang2vec(np.pi / 2.0 - coordinates[0], 2 * np.pi - coordinates[1])
for vec in vectors:
disc = hp.query_disc(mask.nside, vec, point_source_radius_ar... | [
"def create_source_at_pos(x_pos, y_pos, npix_x, npix_y, PSF_MAP, MASK):\n #\n # Extract information about PSF_MAP\n PSF_MAP_npix_x, PSF_MAP_npix_y = PSF_MAP.shape\n # create the SRC_MAP\n SRC_MAP = npy.zeros([npix_x, npix_y])\n # Create the POS_MAP\n POS_MAP = npy.zeros(PSF_MAP.shape)\n # Co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subtract monopole and dipole from a ``enmap`` object. | def subtract_mono_dipole(emap, mask=None, healpix=True, bunch=24, return_values=False):
map_cleaned = emap.copy()
if healpix:
map_masked = hp.ma(emap)
if mask is not None:
map_masked.mask = mask < 1
mono, dipole = hp.fit_dipole(map_masked)
npix = len(emap)
nsi... | [
"def subtract(self, m):\n pass",
"def subtract(self, other: \"Mapping\"):\n to_remove = []\n for k, v in self.items():\n if k in other:\n v -= (other[k])\n self[k] = v\n if v == 0:\n to_remove.append(k)\n # Can'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the food positions | def calculateFoodPositions(self, state):
foodPos = [9999999] * state.getNumFood()
if(state.getNumFood() > 0):
# minDistance = 900000
# pacmanPosition = state.getPacmanPosition()
counter = 0
for i in range(state.data.layout.width):
for j in ... | [
"def food_pos(self):\n return self._food_pos",
"def food_pos(self) -> Tuple[int, int]:\n return self._food_pos",
"def food_at(self, location_cell: tuple) -> List[Food]:\n if location_cell in self.cells:\n return self.cells[location_cell].food\n return []",
"def getSafeFo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply trained model to forecast the data | def forecast(self, model, idx_rows=None, replace=True):
if idx_rows is None:
idx_rows = range(self.X.shape[0])
forecastedY = model.predict(self.X[idx_rows, :])
if forecastedY.ndim == 1:
forecastedY = forecastedY[:, None]
# ravel forecasts and, if replace=True, i... | [
"def train(self, training_data):\n # load and preprocess\n super(Forecast, self).train(training_data)\n # remove NaNs\n self.historical_data = self.historical_data.loc[~self.historical_data.isnull().any(axis=1)]\n # project timestamps into vector space\n if self.timestamp_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes flat indices of forecasts and optionally replaces old forecast values new ones | def add_forecasts(self, frc, idx_rows, replace):
# Infer ts flat indices from matrix structure
idx_flat = [0] * self.nts
for i in self.y_idx:
idx_flat[i] = _ravel_idx(self.idxY[i][idx_rows, :], len(self.forecasts[i]))#self.n_hist_points[i], self.n_req_points[i], self.X.shape[0])
... | [
"def forecast(self, model, idx_rows=None, replace=True):\n if idx_rows is None:\n idx_rows = range(self.X.shape[0])\n\n forecastedY = model.predict(self.X[idx_rows, :])\n if forecastedY.ndim == 1:\n forecastedY = forecastedY[:, None]\n\n # ravel forecasts and, if re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds indices of the forecast that should be used to calculate errors | def _frc_indices_for_errors(self, idx_frc=None, idx_rows=None, y_idx=None, idx_original=None):
idx = [0] * self.nts
if idx_frc is None:
if idx_rows is None:
for i in y_idx:
idx[i] = range(self.n_hist_points[i], len(self.forecasts[i]))
else:
... | [
"def get_prediction_indices(self):\r\n if self.full_df['Dates'][0] > self.full_df['Dates'][len(self.full_df) - 1]:\r\n self.full_df = self.full_df[::-1]\r\n self.full_df.reset_index(inplace=True)\r\n self.full_df.drop('index', axis=1, inplace=True)\r\n date_condition = ((self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncates time series, leaving n_hist + n_req n_rows points from the beginning | def truncate(ts_struct, n_hist, n_req, n_rows):
ts = ts_struct.s
n_points = n_hist + n_req*n_rows
ts = ts[:n_points]
ts_struct = TsMiniStruct(ts, ts_struct.norm_div, ts_struct.norm_subt, ts_struct.name, ts_struct.index[:n_points])
return ts_struct | [
"def truncate_hist(self, root_hist, truncation):\n mean = root_hist.GetMean()\n # mean_error = root_hist.GetMeanError()\n # rms = root_hist.GetRMS()\n # rms_error = root_hist.GetRMSError()\n integral_total = root_hist.Integral()\n if integral_total != 0.:\n mean_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that all x time entries preceed corresponding y time entries | def check_time(y, x):
check = []
# y stores earliest time for Y in each row, x stores latest time for X in each row. These two must not overlap
for ty, tx in product(y, x):
check.append(np.all(ty > tx))
return np.all(check) | [
"def checkTimes(firstValue, lastValue, units, calendar, deltaValue, deltaUnits, npoints):\n first = reltime(firstValue, units)\n last = reltime(lastValue, units)\n firstAdjusted = first.tocomp(calendar).add(0, deltaUnits)\n lastAdjusted = last.tocomp(calendar).add(0, deltaUnits)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class decorator that makes inherited math ops infectious by reconstructing results (probably horribly inefficient...). | def infectious_math(cls):
for prp in [
"__add__", "__radd__",
"__sub__", "__rsub__",
"__mul__", "__rmul__",
"__matmul__", "__rmatmul__",
"__truediv__", "__rtruediv__",
"__floordiv__", "__rfloordiv__",
"__mod__", "__rmod__",
"__divmod__", "__rdivmod__",
"__pow__", "__rpow__",
"_... | [
"def PythonMathModel(object):\n\n def __init__(self):\n pass\n\n def sum(self, elems):\n return sum(elems)\n\n def product(self, elems):\n v = 1.0\n for elem in elems:\n v *= elem\n return v\n\n def divide(self, a, b):\n return a / b\n\n def plus(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A class decorator that scoops up AbstractValueRange class properties in order to create .validate and .abstract methods for the class. Note that properties added after the class is defined aren't counted. Each AbstractValueRange found is is also replaced with a class instance constructed from it. | def abstractable(cls):
cls._ranges = []
for prp in dir(cls):
a = getattr(cls, prp)
if isinstance(a, AbstractValueRange):
cls._ranges.append((prp, a))
setattr(cls, prp, cls(a.val))
cls._ranges = sorted(cls._ranges, key=lambda nr: nr[1].mn)
@classmethod
def validate(cls, val):
ovn = mi... | [
"def create_range(range_class):\n if not hasattr(range_class, 'name'):\n raise exceptions.ValidationError(\n \"A custom range must have a name attribute\")\n return Range.objects.create(\n name=range_class.name,\n proxy_class=_class_path(range_class))",
"def testRangeFieldCon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reverse hash names and correct types of input params | def prepare_request_params(
request_params: Dict, model_id: Text, model_data: Dict
) -> Dict:
request_params = correct_types(request_params, model_data["columns_data"])
if model_data["hashed_indexes"]:
request_params = reverse_hash_names(model_id, request_params)
return request_params | [
"def _hash_args(args, secret=None, prefix = \"oauth_signature\"):\n # get the parameters for the sig calculation \n # to see if the signature is correct\n\n params = {}\n\n for param in args.keys():\n if param != \"oauth_signature\":\n if param not in params:\n params[pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read preset yaml file | def read_yaml(preset_file: Text) -> Dict:
with open(preset_file, "r") as preset_file:
return yaml.safe_load(preset_file) | [
"def _read(self, preset_type):\n logger.debug('read presets for %s', self._device.name)\n with self._file_open_rlock(preset_type) as f:\n f.seek(0)\n return yaml.full_load(f) or {}",
"def readInPreset(self,fileName):\n try: \n with open(fileName,'rt') as doc: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get preset by id | def get_preset_by_id(preset_id: Text):
presets = get_presets()["presets"]
for preset in presets:
if preset_id == preset["id"]:
return preset | [
"def read_preset(self, id):\n uri = '/2012-09-25/presets/{}'.format(id)\n return self.make_request('GET', uri, expected_status=200)",
"def get_preset(cls, preset_name):\n try:\n return FormatPreset.objects.get(id=preset_name)\n except FormatPreset.DoesNotExist:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get presets data from yml configs from presets folder | def load_presets():
presets = []
if not os.path.isdir(cfg.presets_folder):
if os.path.isfile(cfg.presets_folder):
logger.error(f"Presets folder is file. Must be a path to folder")
logger.info(f"Presets folder not found. Create new folder.")
os.makedirs(cfg.presets_folder)
... | [
"def _read(self, preset_type):\n logger.debug('read presets for %s', self._device.name)\n with self._file_open_rlock(preset_type) as f:\n f.seek(0)\n return yaml.full_load(f) or {}",
"def get_presets(self):\r\n presets = Mca.McaPresets()\r\n pvs = self.pvs['presets']\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create _id dict for row based on several fields | def get_obj_id_from_row(model_data: Dict, row: Dict) -> Dict:
result = {}
if not model_data.get("identity"):
# if our tbale does not have unique or primary keys
key_fields = row
else:
key_fields = model_data["identity"]
if "_id" in key_fields:
del key_fields["_id"]
fo... | [
"def get_incident_id(row):\n additional_fields = row.get('additional_fields')\n generated = row.get('generatedTime') or row.get('generated_time') or row.get('GeneratedTime')\n event_id = row.get('event_id') or row.get('EventId') or row.get('eventId')\n instance_id = row.get('instance_id') or row.get('In... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create query str based on _id | def create_obj_id_for_query(id_dict: Dict) -> Text:
return ",".join([f"{key}={value}" for key, value in id_dict.items()]) | [
"def buildQuery():",
"def _MakeQuery(self, query_type: str) -> str:\n return (\n 'resource.type=\"{query_type:s}\"\\n'\n 'resource.labels.project_id=\"{project_id:s}\"\\n'\n 'resource.labels.cluster_name=\"{cluster_id:s}\"\\n'\n 'resource.labels.location=\"{zone:s}\"\\n'.format(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reverse _id dict from query str | def extract_obj_id_from_query(id_row: Text) -> Dict:
pairs = id_row.split(",")
_id = {}
for pair in pairs:
key, value = pair.split("=")
_id[key] = value
return _id | [
"def create_obj_id_for_query(id_dict: Dict) -> Text:\n return \",\".join([f\"{key}={value}\" for key, value in id_dict.items()])",
"def db_urldecode(qs):\r\n\r\n res = {}\r\n for elem in qs.split('&'):\r\n if not elem:\r\n continue\r\n pair = elem.split('=', 1)\r\n name = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method checks that the message payload keys matches the required (specified) keys | def check_message_payload(dequeued_item):
key_array = ["dateTime",
"payload",
"messageType"]
# Note that the "ttl" key (and others) may be present but its not checked here!
for key in key_array:
if key not in dequeued_item.keys():
... | [
"def _validate_keys(self):\n if type(self.keys) != dict:\n raise securesystemslib.exceptions.FormatError(\n \"keys dictionary is malformed!\")\n\n securesystemslib.formats.KEYDICT_SCHEMA.check_match(self.keys)\n\n for keyid, key in six.iteritems(self.keys):\n securesystemslib.formats.PUB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The spatial filter does a filtering of the ont collection based on the asset called this_asset. | def spatial_filter(self, cell):
if self.cell_time_event:
# Only append outages on assets for the cells that have events
if not g_config.IS_DEPLOYED:
print "An interesting time event has occurred in this cell..."
for this_ont in cell['onts']:
ev... | [
"def test_spatial_filter():\n nx, ny, nt = 10, 10, 50\n time = np.arange(nt)\n sta = utils.create_spatiotemporal_filter(nx, ny, nt)[-1]\n viz.spatial(sta)\n filename = os.path.join(IMG_DIR, 'test-spatial-filter.png')\n plt.savefig(filename)\n assert not compare_images(\n os.path.join... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a GUID based on the lat lon and time value | def compute_cell_guid(payload, resolution):
# query_guid = payload["query_guid"]
this_lat = payload["latitude"]
this_lon = payload["longitude"]
# utility = payload["company"]
outage_test_time = payload["outageTime"]
# circuit_id = payload["circuitID"]
# asset_id =... | [
"def create_id(uid, begintime, endtime):\n allowed_chars = string.ascii_lowercase[:22] + string.digits\n temp = re.sub('[^{}]'.format(allowed_chars), '', uid.lower())\n return re.sub('[^{}]'.format(allowed_chars), '', uid.lower()) + str(arrow.get(begintime).timestamp) + str(arrow.get(endtime).timestamp)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a cell and stores it in local shared memory | def build_new_cell(self, this_cell_guid, this_items_payload, ttl):
self.my_local_logger.debug("BUILDING_CELL %d, %s" % (self.cell_count, this_cell_guid))
t0 = time.time()
# Step 3) Query the API and find all utility assets within the region of interest
cell = self.get_data_in_cell_area(t... | [
"def create_cells(self):\n if self.do_run:\n \n self.del_cells()\n \n if self.id == 0: print \"creating cells\"\n \n for n in range(self.n_celltypes): \n self.cells.append([]) # create list in list \n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method grooms the outages by looking at the internal shared queue and pulling off the items that are ready to be processed. The shared queue is passed between processes contains the cell data along with processing state for each cell. | def groom_outages(self):
#######################################################
# This is the general flow for the groom process
# When the queue is hit then it will have the start and end times along with the various parameters
# needed for the outage event calculation.
# When ... | [
"def populatereadyqueue():\n readyQueue.put(Process(\"P1\", time(0, 0, 1), time(0, 0, 4)))\n readyQueue.put(Process(\"P2\", time(0, 0, 2), time(0, 0, 6)))\n readyQueue.put(Process(\"P3\", time(0, 0, 3), time(0, 0, 2)))",
"def process_entire_queue(self):\r\n\t\twhile self.queue:\r\n\t\t\tself._dequeue()",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triggers a Utility wide grooming process by setting up a ttl of 1 and injecting it into the Rabbit MQ bus. When called, the outage test location is calculated by starting in the center of the geographic location using the current time for outage detection. All utilities in the utility dictionary will be groomed when th... | def utility_groom(self, utility_name="ALL", location=None, ttl=g_config.TTL_MAX):
# TODO: The best approach here is to trigger the outage groom at the center of the last alarm.
# trigger_time = arrow.get("2015-01-09T19:42:33.689-0400").timestamp*1000
trigger_date = arrow.utcnow().to('US/Eastern'... | [
"def groom_outages(self):\n #######################################################\n # This is the general flow for the groom process\n # When the queue is hit then it will have the start and end times along with the various parameters\n # needed for the outage event calculation.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the camera 2 calibration matrix from a text file | def read_kitti_calib(filename):
with open(filename) as f:
for line in f:
data = line.split(' ')
if data[0] == 'P2:':
calib_P2 = np.array([float(x) for x in data[1:13]])
calib_P2 = calib_P2.reshape(3, 4)
return _extend_matrix(calib_P2)
... | [
"def read_kitti_Tr_velo_to_cam(filename):\n\n with open(filename) as f:\n for line in f:\n data = line.split(' ')\n if data[0] == 'Tr_velo_to_cam:':\n calib = np.array([float(x) for x in data[1:13]])\n calib = calib.reshape(3, 4)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the camera 2 calibration matrix from a text file | def read_kitti_Tr_velo_to_cam(filename):
with open(filename) as f:
for line in f:
data = line.split(' ')
if data[0] == 'Tr_velo_to_cam:':
calib = np.array([float(x) for x in data[1:13]])
calib = calib.reshape(3, 4)
return _extend_matri... | [
"def read_kitti_calib(filename):\n\n with open(filename) as f:\n for line in f:\n data = line.split(' ')\n if data[0] == 'P2:':\n calib_P2 = np.array([float(x) for x in data[1:13]])\n calib_P2 = calib_P2.reshape(3, 4)\n return _extend_matr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the sum of all deployed scripts' exit_status | def sum_exit_status(self):
return sum([sd.exit_status for sd in self.node.script_deployments]) | [
"def determine_exit_code(self) -> int:",
"def exit_status(self):\n return self._exit_status",
"def exitcode(self):\n ## If exitcode is not set yet, run status evaluation\n if self._exitcode is None:\n self.status()\n \n return self._exitcode",
"def test_deploy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for presence of template indicator and if found, perform variable substition on script based on template type, returning script. | def substitute(script, submap):
match = config.TEMPLATE_RE.search(script)
if match:
template_type = match.groupdict()['type']
try:
return config.TEMPLATE_TYPEMAP[template_type](script, submap)
except KeyError:
logger.error('Unsupported template type: %s' % templa... | [
"def script_template(template_name):\n result=script_template_content(template_name)\n return script_template_save_temporary(result)",
"def materialize(template, substitutions):\n\n script_str = template\n for param, value in substitutions.items():\n script_str = re.sub(param, str(value), script_st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a ScriptDeployment from script with possible template substitutions. | def script_deployment(path, script, submap=None):
if submap is None:
submap = {}
script = substitute(script, submap)
return libcloud.compute.deployment.ScriptDeployment(script, path) | [
"def _ImportDeployTemplate():\r\n deploy_template = \"viewfinder.backend.prod.deploy.{0}\".format(sys.argv[1])\r\n __import__(deploy_template)\r\n servers = sys.modules[deploy_template].__dict__[\"servers\"][0]\r\n setup_script = sys.modules[deploy_template].__dict__[\"setup_script\"][0]\r\n return servers, se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge list of tuples into dict amap, and optionally load source as value | def merge(items, amap, load=False):
for target, source in items:
if amap.get(target):
logger.warn('overwriting {0}'.format(target))
if load:
amap[target] = open(source).read()
else:
amap[target] = source | [
"def _initialize() -> t.Tuple[PopulationMap, PopulationMap]:\n country_list = _load_file()\n\n alpha_2: PopulationMap = {}\n alpha_3: PopulationMap = {}\n\n for country in country_list:\n a2, a3, pop = country[\"Alpha_2\"], country[\"Alpha_3\"], country[\"Population\"]\n alpha_2[a2] = pop\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge list of 'key=val' strings into dict amap, warning of duplicate keys | def merge_keyvals_into_map(keyvals, amap):
for kv in keyvals:
k,v = kv.split('=')
if k in amap:
logger.warn('overwriting {0} with {1}'.format(k, v))
amap[k] = v | [
"def parse_mappings(mapping_list, unique_values=True, unique_keys=True):\n mappings = {}\n for mapping in mapping_list:\n mapping = mapping.strip()\n if not mapping:\n continue\n split_result = mapping.split(':')\n if len(split_result) != 2:\n raise ValueError... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a node deployment. If name is not given, it will generate a random name using prefix. The node name is added to the global substitution map, which is used to parameterize templates in scripts containing the form {variable_name}. The list of bundle names is concatenated with any globally common bundle names f... | def __init__(self, name=None, bundles=[], pubkey=config.DEFAULT_PUBKEY,
prefix=config.DEFAULT_NAME_PREFIX, image_name=config.DEFAULT_IMAGE_NAME,
subvars=[]):
self.name = name or prefix + config.random_str()
config.SUBMAP['node_name'] = self.name
config.SUBMAP['... | [
"def deploy_node(self, name, size, image, script, location=None,\n ex_network='default', ex_tags=None):\n with open(script, 'r') as f:\n script_data = f.read()\n metadata = {'items': [{'key': 'startup-script',\n 'value': script_data}]}\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy. | def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID,
size=config.DEFAULT_SIZE):
logger.debug('deploying node %s using driver %s' % (self.name, driver))
args = {'name': self.name}
if hasattr(config, 'SSH_KEY_NAME'):
args['ex_keyname'] = config.SSH_KEY_NAM... | [
"def deploy_node(self, name, size, image, script, location=None,\n ex_network='default', ex_tags=None):\n with open(script, 'r') as f:\n script_data = f.read()\n metadata = {'items': [{'key': 'startup-script',\n 'value': script_data}]}\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an image from a list of images. If the name is an exact match, return the last exactly matching image. Otherwise, sort images by 'natural' order, using decoratesortundecorate, and return the largest. | def image_from_name(name, images):
prefixed_images = [i for i in images if i.name.startswith(name)]
if name in [i.name for i in prefixed_images]:
return [i for i in prefixed_images if i.name == name][-1]
decorated = sorted(
[(int(re.search('\d+', i.name).group(0)), i) for i in prefixed_im... | [
"def get_best_images(images):\n for image in images:\n score = 0\n score += image[\"vote_count\"]\n score += image[\"vote_average\"] * 10\n score += image[\"height\"]\n if \"iso_639_1\" in image:\n if image[\"iso_639_1\"] == KODI_LANGUAGE:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Destroy all nodes matching specified name | def destroy_by_name(name, driver):
matches = [node for node in list_nodes(driver) if node.name == name]
if len(matches) == 0:
logger.warn('no node named %s' % name)
return False
else:
return all([node.destroy() for node in matches]) | [
"def destroy_nodes(\n self,\n name,\n ):\n pass",
"def destroy_all(self):\n self.log.info(\"Destroying the %s cluster\" % self.cluster_name)\n for n in self.all_nodes:\n n.destroy()\n remove(self.save_file)",
"def __del__(self):\n for node in se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract image from page | def extract_image(page_html, family_url, folder):
image_extractor = Extractor(page_html, family_url)
for url in image_extractor.get_image_table():
image_page_url = urljoin(family_url, url)
# print(image_page_url)
imres = requests.get(image_page_url)
image_page_extractor = Extract... | [
"def _extract_poster(html: str) -> str:\n\n soup = BeautifulSoup(html, features='html.parser')\n a_link = soup.html.body.findAll('a', {'class': 'image'})[0]\n url = a_link.findAll('img')[0]['src']\n\n return url[2:] # because it begins like '//upload.wikimedia.org/..'",
"def page():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add name in text (string) into defaultdict self.adj; Two consecutive words starting with capital letters is considered as a name | def count_name(text, adj):
for x in re.finditer(r'[A-Z][a-z]*[\s][A-Z][a-z]*',text):
adj[x.group()] += 1
return | [
"def add(self, name):\n\n # no need to add first_name while adding full_name\n name_list = name.strip().split()[1:]\n name_list.append(name)\n for item in set(name_list):\n node = self.root\n # check for every char in word, i.e. check whether is it in trie\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build query filter json object from the list of filter tuples. | def _build_query_filters(self, query: dict, filters: list) -> dict:
for filter_tuple in filters:
if not isinstance(filter_tuple, tuple) or len(filter_tuple) != 3:
LOG.error("polling_filters tuple %s : invalid format or does not contain 3 elements - skipping this filter", filter_tupl... | [
"def _make_filter(self, filters=[]):\n dict_filter = {}\n\n if isinstance(filters, list) and filters:\n for elem in filters:\n if not isinstance(elem, tuple):\n # TODO: to create Exceptions\n raise TypeError(u'All elements must be tuple')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a url to link back to the endpoint entity | def make_linkback_url(self, entity_id: str, linkback_url : str = LINKBACK_URL) -> str:
return urljoin(self.endpoint_url, linkback_url.format(organization_name=self.organization_name,
target_id=entity_id)) | [
"def _create_url(self, endpoint: str) -> str:\n return f\"{self._api_server}/rest/v2{endpoint}\"",
"def create_instance_url(self, *args):\n return urljoin(ENDPOINT, self.url, self['id'], *args)",
"def url(self):\n return self.url_builder(\n self.ENDPOINT,\n root=getatt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a base URL string for Randori | def get_randori_base_url(self) -> str:
return urljoin(self.endpoint_url, self.organization_name) | [
"def _create_random_url(self):\n return self._base_url % random.randrange(self._random_create_start, \n self._random_create_end)",
"def create_url(self):\n self.base_url = self.base + self.strs[jpn.path_latest]",
"def buildurl(base, *args, **kwargs):\n\n if not args:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the Randori target impact_score field in Randori | def update_target_impact_score(self, target_id: str, impact_score: str) -> dict:
data = {
"data": {"impact_score": impact_score},
"q": {
"condition": "OR",
"rules": [
{
"id": "table.id",
... | [
"def alter_score(feature, action, val):\n if action == 'r':\n feature.score = str(val)\n elif action == 'a':\n new_score = int(feature.score) + val\n feature.score = new_score\n return feature",
"def update_target(self):\n # raise NotImplementedError\n self.target.set_w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the Randori target status field in Randori | def update_target_status(self, target_id: str, status: str) -> dict:
status_data = {
"data": {"status": status},
"q": {
"condition": "OR",
"rules": [
{
"id": "table.id",
... | [
"def _updateStatus(self, result):\n\n if result.status is not None:\n # status was explicitly set\n self.target.localStatus = result.status\n if self.target.present and self.target.created is None:\n self.target.created = self.configSpec.operation not in [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call Randori endpoint to get the paths data for target from Randori. | def get_paths(self, target_id: str) -> dict:
params = {
'terminal': target_id
}
url = self._get_uri(GET_PATHS_URI.format(api_version=self.api_version))
response = self.rc.execute("GET",
url=url,
params=par... | [
"def get_paths(circuit):\n endpoint = settings.PATHFINDER_URL\n request_data = {\"source\": circuit.uni_a.interface.id,\n \"destination\": circuit.uni_z.interface.id}\n api_reply = requests.post(endpoint, json=request_data)\n\n if api_reply.status_code != getattr(r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ``verify`` parameter from app config. Value can be set in the [fn_my_app] section | def _get_verify_ssl(app_configs: dict):
# start checking the app specific settings
verify = app_configs.get("verify")
# because verify can be either a boolean or a path,
# we need to check if it is a string with a boolean
# value first then, and only then, we convert it to a bool
# NOTE: that ... | [
"def get_verify(self):\n verify = None\n\n # look in app's config section first\n if self.function_opts:\n verify = self.function_opts.get(\"verify\", True)\n\n # if not found in config, then [integration] wide section can be used;\n # NOTE: this is pretty much limited ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create tomb from modules If modules install add topmost package containing this module. | def FromModules (cls, modules = None):
tomb = cls ()
if modules:
for module in modules:
tomb.Add (module)
else:
tomb.Add (__package__ or __name__.partition ('.') [0])
return tomb | [
"def setup_module(module):",
"def addTopModules(modules, sourceDir='.'):\n \n NULLMODULE = 'null'\n topModules = os.listdir(sourceDir)\n for dir in ['CVS', 'sites']:\n if dir in topModules: topModules.remove(dir)\n \n for module in topModules:\n if module not in modules:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Install tomb to meta_path | def Install (self):
if self in sys.meta_path:
return
sys.meta_path.insert (0, self) | [
"def install(self, egg, dir_path):",
"def set_meta_path(self, meta_path):\n logging.debug('Setting meta path: {0}'.format(meta_path))\n if not os.path.exists(meta_path):\n os.makedirs(meta_path)\n self.meta_path = meta_path",
"def install(name, root):",
"def push_setup():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create bootstrap source for this tomb Initialization function (init) and its arguments (args, keys) must be pickleable objects and required modules must added to tomb. | def Bootstrap (self, init = None, *args, **keys):
if init and inspect.getmodule (init).__name__ not in self.containments:
raise ValueError ('Initialization function must reside in added modules')
wrap = lambda source: '\\\n'.join (textwrap.wrap (source, 78))
return ''.join ((
... | [
"def __init__(self, *args, **kwargs):\n # Init the parent classes\n super(TestBootstrapperDouble, self).__init__(*args, **kwargs)\n # Create the data array\n self.NVars = 128 * 2 * 2\n self.data = core.np.random.normal(\n self.mu, self.var, [128, 2, 2, self.NConfigs]\n )\n # Init the cpp c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is module identified by name a package | def is_package (self, name):
containment = self.containments.get (name)
if containment is None:
raise ImportError ('No such module: \'{}\''.format (name))
return containment [2] | [
"def _package_available(package_name: str) -> bool:\n try:\n return find_spec(package_name) is not None\n except ModuleNotFoundError:\n return False",
"def is_package(self, fullmodname):\n submodname, is_package, relpath = self._get_info(fullmodname)\n return is_package",
"def is_packa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get code for module identified by name | def get_code (self, name):
containment = self.containments.get (name)
if containment is None:
raise ImportError ('No such module: \'{}\''.format (name))
return compile (containment [0], containment [1], 'exec') | [
"def get_code(name: str) -> Code:\n module = get_module(name)\n return Code(module)",
"def get_code_by_name(self, name):\n raise NotImplementedError()",
"def get_code(self, fullmodname):\n submodname, is_package, fullpath, source = self._get_source(fullmodname)\n return compile(source, fullpa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get source for module identified by name | def get_source (self, name):
containment = self.containments.get (name)
if containment is None:
raise ImportError ('No such module: \'{}\''.format (name))
return (containment [0] if sys.version_info [0] > 2 else
containment [0].encode ('utf-8')) | [
"def get_source(self, name):\n return self._sources[name]",
"def testsource(module, name):\n module = _normalize_module(module)\n tests = DocTestFinder().find(module)\n test = [t for t in tests if t.name == name]\n if not test:\n raise ValueError(name, \"not found in tests\")\n test =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstrap this module Returns python source, witch when executed allows to import this module by specified "name". | def BootstrapBootstrap (name):
module = sys.modules [__name__]
return BootstrapSource (name, inspect.getsource (module), inspect.getsourcefile (module)) | [
"def NP_LoadModuleFromBootstrap(winghome, modname):\n \n # Limited to simple module loads\n assert '.' not in modname\n \n orig_sys_path = sys.path[:]\n orig_modules = set(sys.modules)\n \n dirname = winghome + '/bootstrap'\n sys.path.insert(0, dirname)\n \n code = 'import %s' % modname\n exec(code)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a normal distribution conditioned on the inputs. | def __call__(self, *args, **kwargs):
mu, sigma = self.condition(args, **kwargs)
return tf.contrib.distributions.Normal(loc=mu, scale=sigma) | [
"def get_standard_normal_distribution():\n return np.random.normal(0, 1)",
"def normal_prior(prior_std):\n\n def prior_fn(dtype, shape, name, trainable, add_variable_fn):\n tfd = tfp.distributions\n dist = tfd.Normal(loc=tf.zeros(shape, dtype),\n scale=dtype.as_numpy_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a timeseries of inputs with a time independent encoder. | def encode_all(self, inputs, encoder):
input_shape = tf.shape(inputs)
num_timesteps, batch_size = input_shape[0], input_shape[1]
reshaped_inputs = tf.reshape(inputs, [-1, inputs.shape[-1]])
inputs_encoded = encoder(reshaped_inputs)
inputs_encoded = tf.reshape(inputs_encoded, [num... | [
"def _encode(timestamps: List[int], encoder: Encoder, encoding: Encoding) -> Encoding:\n enc = encoder(timestamps[0])\n tss = [enc.encode(ts) for ts in timestamps[1:]]\n return encoding(timestamps[0], tss)",
"def generator(input, batch_size, timesteps, encoder):\n while True:\n imb = np.random.randin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evalute the cosine similarity between provided 'text_vectors' and trained X (articles trained and stored as a vecotr of topics). Return dataframe with index as trained articles and columns as text_vector indices with values as similarity scores | def get_similarity_score(text_vectors, X, factor=None):
similarity_scores = cosine_similarity(X, text_vectors, dense_output=True)
return similarity_scores * factor | [
"def vectorize_text(df: pd.DataFrame):\n # Creating a stop_words list set that are common to many questions.\n common_phrases = [\n 'read the sentence from the passage',\n 'which of the following best describes',\n 'which is the best one sentence * for the section',\n 'which senten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an Identifiers.org namespace | def get_identifiers_org_namespace(prefix):
try:
return get_identifiers_org_namespaces()[prefix]
except KeyError:
raise InvalidIdentifiersOrgUri('`{}` is not a valid prefix of a Identifiers.org namespace.'.format(prefix)) | [
"def namespace_id(self) -> str:\n return pulumi.get(self, \"namespace_id\")",
"def namespace_id(self) -> Optional[str]:\n return pulumi.get(self, \"namespace_id\")",
"def namespace(self) -> str:\n return pulumi.get(self, \"namespace\")",
"def __get_namespaces():\n n = Namespaces()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether a URI is a validate for one of the namespaces registered with Identifiers.org | def validate_identifiers_org_uri(uri):
match = re.match(r'^https?://identifiers\.org/((([^/:]+)/([^/:]+)|[^/:]+)([/:])(.+))$', uri)
try:
namespace = get_identifiers_org_namespace(match.group(2).lower())
except InvalidIdentifiersOrgUri:
if match.group(3):
namespace = get_identifie... | [
"def hasURI(self, *args):\n return _libsbml.XMLNamespaces_hasURI(self, *args)",
"def containsUri(self, *args):\n return _libsbml.XMLNamespaces_containsUri(self, *args)",
"def is_urn(val):\n res = urlparse(val)\n return bool(res.scheme == \"urn\" and res.netloc == \"\" and res.path != \"\")",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> rotate_one_left([1, 2, 3, 4, 5]) [2, 3, 4, 5, 1] | def rotate_one_left(a):
first = a[0]
for i in range(1, len(a)):
a[i-1] = a[i]
a[len(a)-1] = first
return a | [
"def left_rotate(arr):\n return arr[1:] + [arr[0]]",
"def rotate_left_list(liste):\n \n rotate_cube_right_list(liste)\n rotate_front_list(liste)\n rotate_cube_left_list(liste)\n \n return liste",
"def rotate_left3(nums):\n rotated_list = nums[1:len(nums)]\n rotated_list.append(nums[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Always O(n), but uses dynamic list creating (not pure array) >>> rot_left_pythonic([1, 2, 3, 4, 5], 4) [5, 1, 2, 3, 4] >>> rot_left_pythonic([1, 2, 3, 4, 5], 5) [1, 2, 3, 4, 5] >>> rot_left_pythonic([1, 2, 3, 4, 5], 3) [4, 5, 1, 2, 3] >>> rot_left_pythonic([41, 73, 89, 7, 10, 1, 59, 58, 84, 77, 77, 97, 58, 1, 86, 58, 2... | def rot_left_pythonic(a, d):
n = len(a)
if (n == d):
return a
result = []
i = d%n
for _ in range(n):
result.append(a[i])
i = (i+1)%n
return result | [
"def rotLeft(a, d):\n for i in range(d):\n arr = left_rotate(arr)\n return arr",
"def rotate(rlist: List[int], rn: int = 1, left_rotate: bool = True) -> List[int]:\n\n def _left_rotate(l, n=1):\n \"\"\"\n\n :param l:\n :param n: (Default value = 1)\n\n \"\"\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test consistency for names to bits to masks | def test_names(self):
for m in self.masks:
for name in m.names():
self.assertEqual(m.mask(name), 2**m.bitnum(name), 'Failed matching mask to bitnum for '+name)
self.assertEqual(m.mask(name), m.mask(m.bitnum(name)), 'Failed matching mask to name for '+name)
... | [
"def testBits(self):\n\n fullPlaneNameList = list(MaskPlaneNameIDDict.keys())\n totNumBits = countBits(MaxBitMask)\n for i in range(len(fullPlaneNameList)):\n numPlanes = i + 1\n setPlaneNameList = fullPlaneNameList[0:numPlanes]\n\n bitMask = coaddUtils.makeBitM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of groups for the user ``user_name``. | def _get_user_groups(user_name):
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups | [
"def userGetGroups(self, userName):\n\t\tuserId = self.getIdFromUserName(userName)\n\n\t\tif userId == None:\n\t\t\tself.log('Error: Requested groups for non existing user ' + userName)\n\t\t\treturn []\n\n\t\tcursor = self.__getCursor()\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT `groups`.`name` as `name` \n\t\t\tFRO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the current user belongs to the required groups to both run S2E and build S2E images. | def _check_groups_docker():
if not _user_belongs_to('docker'):
_raise_group_error('docker') | [
"def checkRequirements(self):\n\n # check if user is in docker group\n user = pwd.getpwuid(os.getuid()).pw_name\n user_in_group = False\n\n for group in grp.getgrall():\n if group.gr_name == \"docker\":\n if user in group.gr_mem:\n user_in_gro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must not be running together with S2E. | def _check_virtualbox():
# Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017679
# to avoid race conditions
for proc in psutil.process_iter():
try:
if proc.name() == 'VBoxHeadless':
raise CommandError('S2E uses KVM to build images. VirtualBox '... | [
"def _is_running_in_vm():\n\n try:\n drv_name = \"/proc/scsi/scsi\"\n if os.path.exists(drv_name):\n contents = open(drv_name).read()\n if \"VBOX\" in contents or \"VMware\" in contents:\n return True\n except (OSError, IOError):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must not be running together with S2E. | def _check_vmware():
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError('S2E uses KVM to build images. VMware '
'is currently running, which is not '
'compatible with KVM... | [
"def _is_running_in_vm():\n\n try:\n drv_name = \"/proc/scsi/scsi\"\n if os.path.exists(drv_name):\n contents = open(drv_name).read()\n if \"VBOX\" in contents or \"VMware\" in contents:\n return True\n except (OSError, IOError):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU. | def _check_kvm():
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError('KVM interface not found - check that /dev/kvm '
'exists. Alternatively, you can disable KVM (-n '
'option) or download pre-built images (-d option)') | [
"def CheckKVM():\n return os.path.exists('/dev/kvm')",
"def kvm_verify():\n if not os.path.exists('/dev/kvm'):\n logging.error(\"kvm is not loaded in this machine\")\n return False",
"def _check_virtualbox():\n # Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that /boot/vmlinux files are readable. This is important for guestfish. | def _check_vmlinux():
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError('Make sure that the kernels in /boot are readable. '
'This is required for guestfish. Please ... | [
"def checkFileSystem(self, elements):\n result = True\n for vm in elements:\n if vm.fileSystem.name and \\\n not os.access(vm.fileSystem.name, os.R_OK):\n print vm.name + \": \" + vm.fileSystem.name + \" is not readable\"\n result = False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the file system that stores guest images supports copyonwrite. | def _check_cow(image_dir):
try:
src = f'{image_dir}/.cowcheck'
dst = f'{image_dir}/.cowcheck1'
sh.touch(src)
sh.cp('--reflink=always', src, dst)
return True
except Exception:
warn_msg = f"""
Copy-on-write check failed.
The file system where images ... | [
"def copy_file_check(self):\n pass",
"def _can_create_tmb(self, path, stat):\n return self._tmb_path_writable and not path.startswith(self._options['tmbPath']) and stat['mime'].startswith('image')",
"def check_availability(self):\n if self.num_copies > 0:\n return True\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a new partner | def partner_create(self):
try:
mongo_module.mongo_insert(self.partner)
output = 'sucesfully created'
code = 201
except Exception as err:
output = str(err)
code = 409
return output, code | [
"def create_partner(name):\n\n return Partner.objects.create(name=name)",
"def _create_partner(self, cr, uid, ids, context=None):\n #TODO this method in only called by crm_lead2opportunity_partner\n #wizard and would probably diserve to be refactored or at least\n #moved to a better place\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set point from lnt, lat. iter over documents from partners_data and get distancec fron point. finally get min distance fron partners_data and return lower value | def partner_find_closest(self, partners_data):
distance = {}
point = Point(self.lng, self.lat)
for partner in partners_data:
if 'coverageArea' in partner and 'coordinates' in partner['coverageArea']:
for coordinates_array in partner['coverageArea']['coordinates']:
... | [
"def closest(data, v):\n min_dist = float('inf')\n location = None\n for _, row in v.iterrows():\n # dist = distance(data['Latitude'], data['Longitude'], row['Latitude'], row['Longitude'])\n dist = distance.distance((data['Latitude'], data['Longitude']), (row['Latitude'], row['Longitude'])).k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a pyyaml serializer to handle xmlrpclib.Binary objects | def represent_xml_binary(loader, data):
data = base64.b64encode(data.data)
return loader.represent_scalar(u'tag:yaml.org,2002:binary', data, style='|') | [
"def register_yaml():\r\n try:\r\n import yaml\r\n registry.register('yaml', yaml.safe_dump, yaml.safe_load,\r\n content_type='application/x-yaml',\r\n content_encoding='utf-8')\r\n except ImportError:\r\n\r\n def not_available(*args, **kw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download a parameter tree from the Parameter Server and store in a yaml file | def dump_params(filename, param, verbose=False):
tree = get_param(param)
if verbose:
print_params(tree, param)
if not filename:
f = sys.stdout
yaml.dump(tree, f)
else:
f = open(filename, 'w')
try:
yaml.dump(tree, f)
finally:
f.close... | [
"def get_params(parfile):\n with open(parfile, 'r') as stream:\n\n try:\n data = safe_load(stream) ## read yaml file\n except YAMLError as exc:\n print(exc)\n pass\n return data",
"def loadParam(YAML):\n\n # Initial parameter file\n try:\n param = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set param on the ROS parameter server using a YAML value. | def set_param(param, value, verbose=False):
set_param_raw(param, yaml.load(value), verbose=verbose) | [
"def setParameter(self, name, value):",
"def setParam(self,param,value):\n if param in self.params.keys():\n self.params[param] = value",
"def set_parameter_value(self, parameter_name, new_value):\n self.description[\"config\"][\"values\"][parameter_name][\"value\"] = new_value\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload params to the Parameter Server | def upload_params(ns, values, verbose=False):
if ns == '/' and not type(values) == dict:
raise RosParamException("global / can only be set to a dictionary")
if verbose:
print_params(values, ns)
set_param_raw(ns, values) | [
"def upload_params(self):\n return {}",
"def update_params(self):",
"def post_parameter_update(self) -> None:",
"def uploadData(self):",
"def test_put_parameter(self):\n pass",
"def _update_params(self):\n pass",
"def handleParameterRequest(self,data):\n req = RequestParamReq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of parameters in ns | def list_params(ns):
try:
ns = make_global_ns(ns)
names = get_param_server().getParamNames()
names.sort()
return [n for n in names if n.startswith(ns)]
except socket.error:
raise RosParamIOException("Unable to communicate with master!") | [
"def param_names(self) -> List[str]:",
"def get_parameters_list(self):\n return self.description[\"config\"][\"values\"].keys()",
"def param(self):\n parameters = []\n for layer in self.layers:\n parameters.extend(layer.param)\n return parameters",
"def get_resource_para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all line endings in the file. | def line_endings(fname):
_endings = {line[-2:] for line in open(fname, 'rb').readlines()}
res = set()
for e in _endings:
if e.endswith(b'\r'):
res.add(b'\r')
elif e.endswith(b'\r\n'):
res.add(b'\r\n')
elif e.endswith(b'\n'):
res.add(b'\n')
retu... | [
"def line_endings(self):\n pass",
"def _DetectLineEndings(filename):\n\n # Find out which file ending is used first. The\n # first lines indicate the line ending for the whole file\n # so pathological files with mixed endings aren't handled properly!\n f = open(filename, 'U')\n try:\n while f.newli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the log likelihood of 'points' arising from the distribution described by density() | def log_likelihood(self, points):
point_set = list(points)
log_probabilities = [np.log(self.density(point)) for point in point_set]
return sum(log_probabilities) | [
"def start_dist_log_prob_fn(x):\n # Make it a gaussian in top left of the 2D space\n gaussian_pdf = scipy.stats.multivariate_normal(\n mean=target_point,\n cov=[1.0, 1.0]\n ).pdf(x)\n\n return np.log(gaussian_pdf)",
"def log_gaussian_density(x, mu, L):\n\n D = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For use during building only. Indicate "__annotations__" need. | def markAsNeedsAnnotationsDictionary(self):
self.needs_annotations_dict = True | [
"def ensure_merged_annotations(self):\n pass",
"def hasPythonFlagNoAnnotations():\n\n return \"no_annotations\" in _getPythonFlags()",
"def needsAnnotationsDictionary(self):\n return self.needs_annotations_dict",
"def has_annotations(cls, __fn):\n try:\n cls.get_annotations(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For use during building only. Indicate "__annotations__" need. | def needsAnnotationsDictionary(self):
return self.needs_annotations_dict | [
"def ensure_merged_annotations(self):\n pass",
"def hasPythonFlagNoAnnotations():\n\n return \"no_annotations\" in _getPythonFlags()",
"def has_annotations(cls, __fn):\n try:\n cls.get_annotations(__fn)\n except AttributeError:\n return False\n return True",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a hadoop streaming job using mrjob. | def RunMRJobStreamingJob(self, input_path, hdfs_output_path, mrjob_file,
archive_file, job_name, python_path,
num_reduce_tasks_override=None,
jar_paths=None, partitioner_class=None,
output_protocol_override=None,... | [
"def _RunMR(fail_on_missing_input=None):\n self._ClearMapperData()\n\n input_reader_dict = {\n \"bucket_name\": \"los_buckets\",\n \"objects\": gcs_files,\n }\n if fail_on_missing_input is not None:\n input_reader_dict[\"fail_on_missing_input\"] = fail_on_missing_input\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test encoding and decoding JWT tokens | def test_encode_decode_token(create_user):
user = create_user
user_data = {
"email": user.email,
"username": user.username
}
jwt = JWTAuthentication()
# encode token
encoded_token = jwt.generate_token(user_data)
assert type(encoded_token) is str # test encoding is 'utf-8'
... | [
"def test_encode_auth_token(self):",
"def test_jwt_example(self):\n data = r'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'\n expected = json.loads(r'''{\"header\":{\"alg\":\"HS256\",\"typ\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |