query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
verifica se tem o link para voltar para a listagem de animais | def test_animais_list_link(self):
PropriedadeUser.objects.create(propriedade=self.propriedade1,
user=self.user1,
owner=True)
login = self.client.login(username='user1', password='12345')
response = self.client.get(reve... | [
"def update_link(self, link):",
"async def tabelavacina(ctx):\n await ctx.send(\"\"\"Link to gsheets\"\"\")",
"def getLink(self):",
"def get_list_link(self):",
"def choose_next_link(self):",
"def _get_links(self, from_year):\n self.links = []\n self.titles = []\n self.speakers = []... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verifica os textos no html | def test_textos_no_html(self):
PropriedadeUser.objects.create(propriedade=self.propriedade1,
user=self.user1,
owner=True)
login = self.client.login(username='user1', password='12345')
response = self.client.get(reverse... | [
"def isHTML(text: unicode) -> bool:\n ...",
"def get_text():",
"def is_text( self ):\n return self.get_main_type() == 'text'",
"def __is_text_format_tag(self, html, pos):\n return self.__extract_html_tag(html, pos) in cf.TAGS_FORMAT_TEXT",
"def hasRawText(self, text):\n r = re.co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the elementwise minimum of some matrices. | def sim_min(sim_mats):
return np.array(sim_mats).min(axis=0) | [
"def aggregate(self, matrices):\n return np.min(matrices, axis=0)",
"def matrix_min(data):\n if is_SparseDataFrame(data):\n data = [np.min(data[col]) for col in data.columns]\n elif is_sparse_dataframe(data):\n data = [sparse_series_min(data[col]) for col in data.columns]\n elif isin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the elementwise maximum of some matrices. | def sim_max(sim_mats):
return np.array(sim_mats).max(axis=0) | [
"def MatrixMax(input_matrix):\r\n return np.max(input_matrix)",
"def aggregate(self, matrices):\n return np.max(matrices, axis=0)",
"def __matrix_max(m):\n max_e = -1\n max_i = 0\n max_j = 0\n for i in range(len(m)):\n for j in range(len(m[0])):\n if m[i][j] > max_e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in an Image message and identifies the locations of the three dumbbells | def identify_dbs(image):
locations = {"red": Point(), "green": Point(), "blue": Point()}
masks = {"red": [], "green": [], "blue": []}
bridge = cv_bridge.CvBridge()
image = bridge.imgmsg_to_cv2(image, "bgr8")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# upper and lower bounds for red
# us... | [
"def identify(lily_im):",
"def belt(image):\n\n # Belt Detector\n x, y = circular_detector(image, 70, 80)\n\n return x, y",
"def identify_blocks(images):\n locations = {1: Point(), 2: Point(), 3: Point()}\n blocks = {\"left\": 0, \"middle\": 0, \"right\": 0}\n pipeline = keras_ocr.pipeline.Pip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a list of Image messages and identifies the block number in each image | def identify_blocks(images):
locations = {1: Point(), 2: Point(), 3: Point()}
blocks = {"left": 0, "middle": 0, "right": 0}
pipeline = keras_ocr.pipeline.Pipeline()
cv2_images = []
for image in images:
bridge = cv_bridge.CvBridge()
cv2_images.append(bridge.imgmsg_to_cv2(image, "bgr8... | [
"def detectBlocksInDepthImage(self):\n pass",
"def detectBlocksInDepthImage(self):\n depth_range_dict = {'1':[173,178],'2':[169,172],'3':[165,169],'4':[159,163],'5':[156,158],'6':[147,155],'7':[139,146],'8':[132,138]}\n depth_frame = self.DepthFrameRaw\n rgb_frame = self.VideoFrame\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return inputted mouse position. | def get_mouse_pos(self):
return self.mouse_pos | [
"def getPosition():\r\n return mouse.position",
"def get_mouse_position(self):\n raise NotImplementedError",
"def mousePos():\n data = display.Display().screen().root.query_pointer()._data\n return data[\"root_x\"], data[\"root_y\"]",
"def read_current_mouse_position():\n import pyautogui\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize type and button. | def __init__(self, event_type, button):
self.type = event_type
self.button = button | [
"def __init__(self, button):\n self.__button = button",
"def __init__(self):\n super(ReverbEffectButton, self).__init__()\n self.set_label(\"Reverb controls\")",
"def __init_prompt(self):\n self.__init_prompt_label()\n self.__init_url_frame()\n self.__init_clear_frame()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get final coach for each session coach with more than half the season will be the credited coach for eventual playoff and championship won | def get_final_coach_for_each_season(self):
self.final_coach_for_season = (
self.num_days_coach_for_season
.groupby(['Season','TeamID'])
.agg({"CoachName":"count"})
.reset_index()
.rename(columns={"CoachName":"coach_counts"})
.merge(self.num... | [
"def get_championship_won_for_each_coach(self):\n self.championship_team = (\n self.raw_data_postseason\n .merge(self.season_max_days,how='left',on=['Season'])\n .query(\"DayNum == season_max_days\")\n .groupby(['Season','WTeamID'])\n .agg({\"NumOT\":\"c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get teams who won the championship for each year | def get_championship_won_for_each_coach(self):
self.championship_team = (
self.raw_data_postseason
.merge(self.season_max_days,how='left',on=['Season'])
.query("DayNum == season_max_days")
.groupby(['Season','WTeamID'])
.agg({"NumOT":"count"})
... | [
"def get_player_games(self, year, use_local=True):",
"def _find_players_with_coach(self, year):\n if not year:\n year = utils._find_year_for_season('nba')\n # Given the delays to the NBA season in 2020, the default season\n # selection logic is no longer valid after the ori... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get win rate for regular season for each coach | def get_win_rate_regular_season_for_each_coach(self):
self.games_won_for_coaches = (
self.raw_data_regularseason
[['Season','DayNum','WTeamID']]
# merge for winning team
.merge(self.num_days_coach_for_season[['Season','TeamID','FirstDayNum','LastDayNum','CoachName... | [
"def get_win_rate_post_season_for_each_coach(self):\n # get winning games for coaches\n self.post_games_won_for_coaches = (\n self.raw_data_postseason\n [['Season','DayNum','WTeamID']]\n # merge for winning team\n .merge(self.num_days_coach_for_season[['Seas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get win rate for post season for each coach | def get_win_rate_post_season_for_each_coach(self):
# get winning games for coaches
self.post_games_won_for_coaches = (
self.raw_data_postseason
[['Season','DayNum','WTeamID']]
# merge for winning team
.merge(self.num_days_coach_for_season[['Season','TeamID... | [
"def get_win_rate_regular_season_for_each_coach(self):\n self.games_won_for_coaches = (\n self.raw_data_regularseason\n [['Season','DayNum','WTeamID']]\n # merge for winning team\n .merge(self.num_days_coach_for_season[['Season','TeamID','FirstDayNum','LastDayNum',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that upload Logger Type file without microsite_id will not be inserted to database | def test_logger_type_upload_MicrositeId_None(self):
test_filename = 'server/tests/test_data_files/Test/Test_New_Logger_Type_MicrositeId_None.csv'
with self.app.test_client() as client:
with client.session_transaction() as sess:
sess['logged_in'] = True
response = ... | [
"def test_upload_file(self):\n pass",
"def test_upload_version_no_file(\n db, clients, tmp_uploads_local, upload_file, upload_version\n):\n client = clients.get(\"Administrators\")\n studies = StudyFactory.create_batch(1)\n study_id = studies[-1].kf_id\n\n # Upload a version with a file_id t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that Logger Temperature file with duplicate entry cannot be uploaded | def test_logger_temperature_upload_duplicate(self):
test_type_filename = 'server/tests/test_data_files/Test/Test_New_Logger_Type_Positive.csv'
test_temp_filename = 'server/tests/test_data_files/Test/temp_files/DUMMYID_2000_pgsql_Duplicate.txt'
with self.app.test_client() as client:
w... | [
"def test_upload_duplicate(client: FlaskClient):\n file = get_example_file(ExampleFileType.Png)\n response1 = util.upload_file(client, DEFAULT_USER, file)\n response2 = util.upload_file(client, DEFAULT_USER, file)\n\n assert response1.status == \"201 CREATED\"\n assert response2.status == \"200 OK\"\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the value of an entry by running its task. Requires that all the task's dependencies are already computed. | def compute(self, context):
# TODO There are a few cases here where we acccess private members on
# self.state; should we clean this up?
state = self.state
task = state.task
protocol = state.desc_metadata.protocol
assert state.is_initialized
assert not state.is... | [
"def _compute(self, task_key_logger):\n\n task = self.task\n\n dep_results = [\n dep_state.get_results_assuming_complete(task_key_logger)[\n dep_key.dnode.to_entity_name()\n ]\n for dep_state, dep_key in zip(self.dep_states, task.dep_keys)\n ]\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicates whether the task state's result is cached. | def is_cached(self):
if self.should_persist:
# If our value is persistable, it can be saved either on disk or in memory,
# but only the former counts as being officially "cached".
return self._result_value_hash is not None
else:
return self._result is not ... | [
"def is_cached(self):\n return False",
"def hasCache(self):\n return bool(self.cached == self.__class__.CACHED)",
"def cache_enabled(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"cache_enabled\")",
"def IsCacheable(self):\n return self.CacheKey() is not None",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the hash of the persisted value for this task, if it exists. If the persisted value is available in the cache, this object's `is_cached` property will become True. Otherwise, nothing will happen. | def attempt_to_access_persistent_cached_value(self):
assert self.is_initialized
assert not self.is_cached
if not self.should_persist:
return
if not self._cache_accessor.can_load():
return
self._load_value_hash() | [
"def _load_value_hash(self):\n\n artifact = self._cache_accessor.load_artifact()\n if artifact is None or artifact.content_hash is None:\n raise AssertionError(\n oneline(\n f\"\"\"\n Failed to load cached value (hash) for descriptor\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refreshes all state that depends on the persistent cache. This is useful if the external cache state might have changed since we last worked with this task. | def refresh_all_persistent_cache_state(self, context):
# If this task state is not initialized or not persisted, there's nothing to
# refresh.
if not self.is_initialized or not self.should_persist:
return
self.refresh_cache_accessor(context)
# If we haven't loaded ... | [
"def freshen_build_caches(self):",
"def reload_cache(self):\n self.data = self.read_data_cache()",
"def _invalidate_local_get_event_cache_all(self) -> None:\n self._get_event_cache.clear()\n self._event_ref.clear()\n self._current_event_fetches.clear()",
"def refresh(self):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for any versioning errors i.e., any cases where a task's function code was updated but its version annotation was not. | def _check_accessor_for_version_problems(self):
old_prov = self._cache_accessor.load_provenance()
if old_prov is None:
return
new_prov = self._cache_accessor.provenance
if old_prov.exactly_matches(new_prov):
return
if old_prov.nominally_matches(new_prov... | [
"def _check_version(self, root):\n raise NotImplementedError()",
"def rpn_version_check(self):",
"def _validate_continuous_versioning(module):\n version_table = getattr(module, '__version_table__', {})\n\n # Loop all functions or classes with their given version mappings.\n for member_name, vers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads (from disk or cloud) and saves (in memory) this task's value hash. | def _load_value_hash(self):
artifact = self._cache_accessor.load_artifact()
if artifact is None or artifact.content_hash is None:
raise AssertionError(
oneline(
f"""
Failed to load cached value (hash) for descriptor
{self._... | [
"def task_data(self):\n return PersistentDict(hash_name=self.identifier)",
"def get(self, file_path: str) -> str:\n file_b = _read(file_path)\n file_pb = self._pb_serialize_file(file_b)\n ipfs_hash = self._generate_multihash(file_pb)\n return ipfs_hash",
"def hash(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns copies of the provided TaskStates with any unnecessary state and ancestors "stripped" off; these copies can be safely transmitted to another process for computation. | def strip_states(self, states):
stripped_states_by_task_key = {}
def strip_state(original_state):
"""Returns a stripped copy of a TaskState."""
task_key = original_state.task_key
if task_key in stripped_states_by_task_key:
return stripped_states_by_... | [
"def strip_state(original_state):\n\n task_key = original_state.task_key\n if task_key in stripped_states_by_task_key:\n return stripped_states_by_task_key[task_key]\n\n assert original_state in self.all_states\n assert original_state not in self.non_serial... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a stripped copy of a TaskState. | def strip_state(original_state):
task_key = original_state.task_key
if task_key in stripped_states_by_task_key:
return stripped_states_by_task_key[task_key]
assert original_state in self.all_states
assert original_state not in self.non_serializable_state... | [
"def strip_states(self, states):\n\n stripped_states_by_task_key = {}\n\n def strip_state(original_state):\n \"\"\"Returns a stripped copy of a TaskState.\"\"\"\n\n task_key = original_state.task_key\n if task_key in stripped_states_by_task_key:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View to return all information needed to display the cart, by converting what has been saved to the session into key variables. Protection in place in case a product, size or nic has been deleted while still in the cart, removing from the list before saving back to the cart session variable. | def cart_contents(request):
cart_items = []
total = 0
savings = 0
product_count = 0
points_available = 0
points_earned = 0
discount_applied = request.session.get('discount_applied')
cart = request.session.get('cart', {})
# Create a new dict so that items can be removed if needed
... | [
"def detail(request):\n # del request.session['cart_id']\n # del request.session['total_in_cart']\n data = {}\n if (cart_id := request.session.get('cart_id', None)):\n cart = Cart.objects.get(pk=cart_id)\n data['products_in_cart'] = cart.cartitems.all()\n data['total_price'] = cart.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Outputs magnetic field given lat, lon, alt. | def magnetic_field(date: datetime.datetime, lat, lon, alt, output_format='cartesian'):
g = GeoMag()
return g.GeoMag(np.array([lat, lon, alt]), date, location_format='geodetic', output_format=output_format) | [
"def magnetization(h):\n if h.has_eh: raise\n if h.has_spin: \n mx = extract.mx(h.intra)\n my = extract.my(h.intra)\n mz = extract.mz(h.intra)\n else: raise\n np.savetxt(\"MAGNETIZATION_X.OUT\",np.matrix([h.geometry.x,h.geometry.y,mx]).T)\n np.savetxt(\"MAGNETIZATION_Y.OUT\",np.matrix([h.geometry.x,h.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate a checksum for num using the Luhn algorithm. | def luhn_checksum(num: str) -> str:
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
if i % 2 == 0:
sx *= 2
if sx > 9:
sx -= 9
check += sx
return str(check * 9 % 10) | [
"def luhn_checksum(n):\n thesum = 0\n n = str(n)\n for i,num in enumerate(n):\n if (len(n)%2==0 and i%2==0) or (len(n)%2!=0 and i%2!=0):\n thesum += lookup_tab[int(num)]\n else:\n thesum += int(num) \n return thesum%10",
"def __calculate_checksum(cls, num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Romanize a given string. | def romanize(string: str, locale: t.Union[Locale, str]) -> str:
locale = validate_locale(locale)
if locale not in (Locale.RU, Locale.UK, Locale.KK):
raise ValueError(f"Romanization is not available for: {locale}")
table = _get_translation_table(locale)
return string.translate(table) | [
"def toRoman(n):\n pass",
"def fromRoman(s):\n if not s:\n raise InvalidRomanNumeralError, 'Input can not be blank'\n if not romanNumeralPattern.search(s):\n raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s\n\n result = 0\n index = 0\n for numeral, integer in romanNu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configure the logging system. If a logpath is provided, entries will also be written to that logfile. | def configure_logger(logpath, loglevel=logging.DEBUG):
handlers = [logging.StreamHandler()]
if logpath:
handlers.append(logging.FileHandler(logpath))
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%d-%m-%y %H:%M:%S', level=loglevel, handlers=han... | [
"def configure_logger():\n log_dir = os.path.join(_workspace_dir(), \"logs\")\n if os.path.exists(log_dir):\n shutil.rmtree(log_dir)\n os.makedirs(log_dir)\n\n global_log = logging.getLogger()\n global_log.setLevel(logging.DEBUG)\n\n verbose_format = \"%(asctime)s(%(levelname)s->%(module)s)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connect two nodes with a channel. Connects node a to node b using the given channel. | def connect(self, channel, a, b):
a.sender.channels.append(channel)
channel.receivers.append(b) | [
"def connectNodes(self, node1, node2):\r\n # connect up Node\r\n node1.connect(node2)",
"def connect_channel(channel):\r\n return factory.connect_channel(channel, SlaveService)",
"def connect(self, node1, node2):\n\t\tnode1.set_neighbor(node2)\n\t\tnode2.set_neighbor(node1)",
"def connect(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
crawl objct and return the result | def crawl_start(crawl_obj):
res = None
if crawl_obj.type in ['user', 'song'] :
res = eval('crawl_' + crawl_obj.type)(crawl_obj)
elif crawl_obj.type in ['artist', 'album'] :
web_data = requests.get(crawl_obj.url, headers = cheat_headers)
soup = bs4.BeautifulSoup(web_data.text, '... | [
"def crawl(self, *args, **kwargs):\n raise NotImplementedError",
"def baidu_parse(page):\n result_list = []\n a = []\n '''\n # 匹配中文,数字和英文的形式。。\n xx = u\"[\\u4e00-\\u9fa5a-zA-Z0-9]+\"\n pattern = re.compile(xx)\n '''\n \"\"\"\n class_list = []\n related_list = []\n a = []\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
iterates over points on the board | def points_generator(self):
rows, cols = self.game.board.board_size
points = [Point(i, j) for i, j in product(range(rows), range(cols))]
for point in points:
yield point | [
"def iter_points(self):\n for x in range(self.left, self.right + 1):\n for y in range(self.top, self.bottom + 1):\n yield Point(x, y)",
"def grid_points(self):\n for i in range(self.rows):\n for j in range(self.cols):\n min_lat,max_lat,min_lon,max_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the minimum value of a and b ignoring any negative values. | def _get_min_positive_value(self, a, b):
if a < 0 and b >= 0:
return b
if a >= 0 and b < 0:
return a
return min(a, b) | [
"def min(self, a, b):\n a = _convert_other(a, raiseit=True)\n return a.min(b, context=self)",
"def minimum ( a, b ):\n if a <= b : return a\n else : return b",
"def _no_none_min(a, b):\n\n if a is None:\n return b\n elif b is None:\n return a\n else:\n return mi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves all flashcards in ascending order (max 250 at a time) or using basic pagination returns `qty` flashcards occuring after `start`. | def retrieve_all_flashcards(start: int=0, qty:int=None):
qty = 250 if qty == None else qty
with sqlite3.connect(current_app.config['DB']) as db:
c = db.cursor()
c.execute("""
SELECT
id,
title,
description,
source,
... | [
"def deck_list(request):\n \n decks = Deck.objects.all()\n \n # Pull the suits for each deck and put them in a tuple with each deck\n deck_list = []\n for deck in decks:\n \n suits = Suit.objects.filter(deck=deck.id)\n deck_list += [ (deck, suits) ]\n \n pages = Paginato... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
rightpad a string with zeros to the given length | def _rzfill(string, to_len):
if len(string) > to_len:
raise ValueError("string is already longer than to_len")
return string + '0' * (to_len - len(string)) | [
"def add_zero_at_right(my_string, length):\n return my_string.ljust(length, \"0\")",
"def pad_right(s, target_len):\n return s + ' ' * (target_len - len(s))",
"def add_zero_at_left(my_string, length):\n return str(my_string).zfill(length)",
"def padding_zeroes(number, length_string):\n return str(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
callback for the edit>Program YubiKey pulldown Opens a new configuration window, blocking until exit. | def _program_key(self):
prg_dialogue = _ProgrammingWindow(self)
self.root.wait_window(prg_dialogue.top) | [
"def open_configuration(self,event):\n configDevFrame = Single_deviceconf(parent=self, ID=996)\n configDevFrame.Centre()\n configDevFrame.Show()\n configDevFrame.ShowModal()\n configDevFrame.Destroy()",
"def launch_configtool():\r\n from PyQt4 import QtGui\r\n from freesee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to detect a pluggedin YubiKey else alerts user | def detect_yubikey(self):
try:
self.yk = yubico.find_yubikey()
self.version.set("Version:%s" % self.yk.version())
self.serial.set("Serial:%s" % self.yk.serial())
except yubico.yubikey.YubiKeyError:
self.version.set("No YubiKey detected")
self.s... | [
"def search_for_yubico_usb():\n # Issues queries and call osquery Thrift APIs.\n usb_devices = instance.client.query(\"select * from usb_devices;\")\n\n # search for a Yubikey\n for device in usb_devices.response:\n for usb_attributes in device:\n if usb_devices.response[usb_devices.re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quelle est la différence entre =, copy.deepcopy et copy.copy? = crée une référence au même objet. Si l'un est modifié, l'autre aussi. copy.deepcopy crée un objet différent. copy.copy, la shallow copie, fait une copie sur le premier id donc copie la liste mais pas ce qu'il y a à l'intérieur (contrairement à deepcopy). A... | def shallow_vs_deep_copy():
l0 = [0, 1, 2, 3, [4, 5], 6]
l1 = l0 # l1 is l0 >>> True
l2 = copy.copy(l1) # l2 is l0 >>> False
l3 = copy.deepcopy(l1) # l3 is l0 >>> False
print('Initial:\nl0 = l1 = l2 = l3 = %s' % l0)
l0[0] = "Change l0" # Change l0 and l1
l1[1] = "Change l1" # Change l0... | [
"def deepcopy(x):\n\tpass",
"def test_ProxySet_copy(self):\n newProxyList = self.proxyList.copy()\n self.assertEquals(newProxyList, self.proxyList)",
"def copy_list(self,list_):\r\n return list_[:]",
"def test_deep_copy_does_copy(self):\n assert id(self.orig) != id(self.copy), 'The... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the Entry text value. | def displayText(self):
if self.entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Enter a text value")
else:
self.file_com.write(self.entryWidget.get().strip()+'\n') | [
"def get_entry_text(self):\n return self.entry.get_text()",
"def get_text(self):\n return self.entry.get_text()",
"def get_value(self):\n # Get the value of the text in the line edit.\n print \"The value of the line edit is %s\" % self.some_le.text()",
"def formatter(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and configure connexion app. | def create_app(env):
connexion_app = connexion.App(__name__, specification_dir='openapi/',
options={'swagger_url': '/swagger'})
app = connexion_app.app
env_config_class_map = {
'prod': 'config.Prod',
'testing': 'config.Testing',
'dev': 'config.Dev'
... | [
"def create_app(self):\r\n self.app = Flask(__name__, instance_relative_config=True)\r\n\r\n # Init the secret key of the app -it is a must for flask to run\r\n self.app.config.from_mapping(\r\n SECRET_KEY='!ZNeverSayNever116Z!',\r\n MONGODB_SETTINGS= {'host': 'mongodb://l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the commit to the commits array if it doesn't already exist, and returns the commit's index in the array. | def add_commit(self, commit):
sha1 = commit.hex
if sha1 in self._commits:
return self._commits[sha1]
title, separator, body = commit.message.partition("\n")
commit = {
'explored': False,
'sha1': sha1,
'name': GitUtils.abbreviate_sha1(sha1),... | [
"def lookup(self, commit):\n return self._commits[self._idx_of(commit)]",
"def add_commit(self, commit):\r\n\t\tself[\"commits\"][commit[\"sha\"]] = commit",
"def commit_id(self):\n return self._commit_id",
"def get_commit_id():\n return about.get_commit_id()",
"def git_commit(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uniquely abbreviates the given SHA1. | def abbreviate_sha1(cls, sha1):
# For now we invoke git-rev-parse(1), but hopefully eventually
# we will be able to do this via pygit2.
cmd = ['git', 'rev-parse', '--short', sha1]
# cls.logger.debug(" ".join(cmd))
out = subprocess.check_output(cmd).strip()
# cls.logger.d... | [
"def uniquely_shorten(string, length):\n\n if len(string) <= length and not (len(string) == length and\n string.startswith(SHORTENED_PREFIX)):\n return string\n\n h = hashlib.sha256()\n h.update(\"%s \" % length)\n h.update(string)\n hash_text = h.hexdigest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all refs pointing to the given SHA1. | def refs_to(cls, sha1, repo):
matching = []
for refname in repo.listall_references():
symref = repo.lookup_reference(refname)
dref = symref.resolve()
oid = dref.target
commit = repo.get(oid)
if commit.hex == sha1:
matching.appen... | [
"def list_refs(refname = None):\r\n argv = ['git', 'show-ref', '--']\r\n if refname:\r\n argv += [refname]\r\n p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)\r\n out = p.stdout.read().strip()\r\n rv = p.wait() # not fatal\r\n if rv:\r\n assert(not out)\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all dependencies of the given revision, recursively traversing the dependency tree if requested. | def find_dependencies(self, dependent_rev, recurse=None):
if recurse is None:
recurse = self.options.recurse
try:
dependent = self.get_commit(dependent_rev)
except InvalidCommitish as e:
abort(e.message())
self.todo.append(dependent)
self.tod... | [
"def get_dependencies(self, revision: Dict) -> List[Dict]:\n dependency_ids = revision['auxiliary']['phabricator:depends-on']\n revisions = self.get_revisions(phids=dependency_ids)\n result = []\n for r in revisions:\n result.append(r)\n sub = self.get_dependencies(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all dependencies of the given revision caused by the given parent commit. This will be called multiple times for merge commits which have multiple parents. | def find_dependencies_with_parent(self, dependent, parent):
self.logger.debug(" Finding dependencies of %s via parent %s" %
(dependent.hex[:8], parent.hex[:8]))
diff = self.repo.diff(parent, dependent,
context_lines=self.options.context_lines)
... | [
"def get_dependencies(self, revision: Dict) -> List[Dict]:\n dependency_ids = revision['auxiliary']['phabricator:depends-on']\n revisions = self.get_revisions(phids=dependency_ids)\n result = []\n for r in revisions:\n result.append(r)\n sub = self.get_dependencies(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run git blame on the parts of the hunk which exist in the older commit in the diff. The commits generated by git blame are the commits which the newer commit in the diff depends on, because without the lines from those commits, the hunk would not apply correctly. | def blame_hunk(self, dependent, parent, path, hunk):
first_line_num = hunk.old_start
line_range_before = "-%d,%d" % (hunk.old_start, hunk.old_lines)
line_range_after = "+%d,%d" % (hunk.new_start, hunk.new_lines)
self.logger.debug(" Blaming hunk %s @ %s" %
... | [
"def git_blame(commit, filepath):\n output = subprocess.check_output(['git', 'blame', '-p',\n commit, filepath])\n commit, old_line, new_line = None, None, None\n blames = []\n COMMIT_LINE_PREFIX = re.compile(b'^[0-9a-f]* ')\n for line in output.split(b'\\n'):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigate to the tree or blob object pointed to by the given target path for the given commit. This is necessary because each git tree only contains entries for the directory it refers to, not recursively for all subdirectories. | def tree_lookup(self, target_path, commit):
segments = target_path.split("/")
tree_or_blob = commit.tree
path = ''
while segments:
dirent = segments.pop(0)
if isinstance(tree_or_blob, pygit2.Tree):
if dirent in tree_or_blob:
tre... | [
"def read_git_blob(commit_ref, path, repo_dir='.'):\n repo = git.Repo(repo_dir)\n tree = repo.tree(commit_ref)\n dirname, fname = os.path.split(path)\n text = None\n if dirname == '':\n text = _read_blob(tree, fname)\n else:\n components = path.split(os.sep)\n text = _read_blo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the matrix square root of a hermitian or symmetric matrix Uses scipy.linalg.eigh() to diagonalize the input efficiently. | def sqrtmh(A, ret_evd=False, evd=None):
if not evd is None:
(ev, EV) = evd
else:
ev, EV = la.eigh(A) #uses LAPACK ***EVR
ev = sp.sqrt(ev) #we don't require positive (semi) definiteness, so we need the scipy sqrt here
#Carry out multiplication with the diagonal matrix of eigenva... | [
"def sqrtmh(x: th.Tensor) -> th.Tensor:\n dtype = x.dtype\n\n # This is actually precision-sensitive\n L, Q = th.linalg.eigh(x.double())\n res = Q * L.clamp(0.0).sqrt() @ Q.mH\n return res.to(dtype)",
"def _symmetric_matrix_square_root(mat, eps=1e-10):\n u, s, vt = np.linalg.svd(mat)\n # sqrt is ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a category for that party. | def create_category(party_id: PartyID, title: str) -> TourneyCategory:
party = DbParty.query.get(party_id)
if party is None:
raise ValueError('Unknown party ID "{}"'.format(party_id))
category = TourneyCategory(party.id, title)
party.tourney_categories.append(category)
db.session.commit()
... | [
"def create(party_id):\n party = _get_party_or_404(party_id)\n\n form = CreateOrUpdateForm(request.form)\n if not form.validate():\n return create_form(party.id, form)\n\n title = form.title.data.strip()\n\n category = category_service.create_category(party.id, title)\n\n flash_success(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move a category upwards by one position. | def move_category_up(category: TourneyCategory) -> None:
category_list = category.party.tourney_categories
if category.position == 1:
raise ValueError('Category already is at the top.')
popped_category = category_list.pop(category.position - 1)
category_list.insert(popped_category.position - 2... | [
"def move_category_down(category: TourneyCategory) -> None:\n category_list = category.party.tourney_categories\n\n if category.position == len(category_list):\n raise ValueError('Category already is at the bottom.')\n\n popped_category = category_list.pop(category.position - 1)\n category_list.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move a category downwards by one position. | def move_category_down(category: TourneyCategory) -> None:
category_list = category.party.tourney_categories
if category.position == len(category_list):
raise ValueError('Category already is at the bottom.')
popped_category = category_list.pop(category.position - 1)
category_list.insert(popped... | [
"def move_category_up(category: TourneyCategory) -> None:\n category_list = category.party.tourney_categories\n\n if category.position == 1:\n raise ValueError('Category already is at the top.')\n\n popped_category = category_list.pop(category.position - 1)\n category_list.insert(popped_category.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up an interceptor so all grpc calls will have the apikey added on the header, in order to authenticate. | def set_interceptor(self, apikey):
self.header_interceptor = \
interceptor.header_adder_interceptor(
'lc-api-key', apikey
)
try:
self.intercept_channel = grpc.intercept_channel(
self.channel, self.header_interceptor)
except ValueError as e:
raise Exception("Attempted to connect on termninated cli... | [
"def authenticate(self, api_key):\n self.headers['x-rapidapi-key'] = api_key",
"def __init__(self, api_key):\n self._api_key = api_key\n self.headers = {\n \"hibp-api-key\": api_key,\n \"user-agent\": \"haveibeenpywned.py\",\n }\n \"\"\"Dict of additional h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returning all elements names from ``ImmunizationRecommendation`` according specification, with preserving original sequence order. | def elements_sequence(cls):
return [
"id",
"meta",
"implicitRules",
"language",
"text",
"contained",
"extension",
"modifierExtension",
"identifier",
"patient",
"date",
... | [
"def get_item_names(spec):\n names = [item.getAttribute('dotname')\n for group in spec.getElementsByTagName('group')\n for item in group.getElementsByTagName('item')]\n return names",
"def itemnames():\n g = ['KIS_NA_39', 'VII_57', 'MX_48', 'MX_56', 'KIS_NA_42', 'VII_54',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Callback when front server is connected. | def OnFrontConnected(self) -> None:
self.gateway.write_log("行情服务器连接成功")
self.login() | [
"def on_connect(self):\n print(\"< Connected to Green Apple Server >\")\n shared_db.green_server_connected = True\n self.on_listening()",
"def on_connect():\n print(\"Someone connected!\")",
"def _on_connect(self) -> None:\n self.status(\"Fully connected to Whisker server\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory to make list of HeadingProduct objects from a list of Product objs. Works the same way as award.awards_list.make_list() | def make_list(products):
heading_products = []
genres = set([p.genre for p in products])
for genre in genres:
this_heading_product = HeadingProduct(genre, products)
if len(this_heading_product.products):
heading_products.append(this_heading_product)
return heading_products | [
"def test_createGlossaryByList(self):\n li = []\n li.append(['term', 'tags', 'value'])\n li.append(['foo', 'a', '1'])\n li.append(['bar', 'a, b', '2'])\n li.append(['gnark', 'a, c', '3'])\n self.g = glossary.Glossary(li)",
"def makeList(*args):\n return _yarp.Value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
same approach as the to_markup_dict() method on Product | def to_markup_dict(self, markup):
ret = self.to_dict()
ret["markup"] = markup.make(self.to_dict())
return ret | [
"def __repr__(self):\n\n return \"<Product: {}>\".format(self.name)",
"def gen_product_template(product):\n element = {}\n element['title'] = convert_to_iso(product[2])\n element['subtitle'] = convert_to_iso(product[3])\n element['subtitle']+= convert_to_iso(u'\\nPor apenas R$ {:.2f}'.format(pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the number of frames o file | def __calculate_number_of_frames(self):
# Save current position
current_pos = self.__file_object.tell()
# Go to start of first frame
self.__file_object.seek(self.__first_frame_raw_data_position)
self.number_of_frames = 0
while True:
if not self.__file_object... | [
"def totalFrames(self):\n # does this by scanning the whole file\n currentPos = self.file.tell()\n self.setNext(0)\n frameCount = 0\n data = self.file.read(self.frameSize)\n while (len(data) == self.frameSize):\n frameCount += 1\n self.file.seek(self.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interprets the header of the YUV file | def __read_header(self):
header = self.__file_object.readline()
header_string = header.decode('utf-8')
print(header_string)
# Ignore first letter
self.frame_width = int(re.findall('W\d+', header_string)[0][1:])
self.frame_height = int(re.findall('H\d+', header_string)[0][... | [
"def parse_header(self):\n self._get_decompressor()\n whs = jpeg.ffi.new(\"int[]\", 3)\n whs_base = int(jpeg.ffi.cast(\"size_t\", whs))\n whs_itemsize = int(jpeg.ffi.sizeof(\"int\"))\n n = self.lib_.tjDecompressHeader2(\n self.decompressor.handle_,\n jpeg.ffi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a buffer containing the next frame in the file | def __get_next_yuv_frame(self):
raw_frame_buffer = self.__file_object.read(self.__frame_raw_data_size)
# Ignore FRAME header
self.__file_object.readline()
return raw_frame_buffer | [
"def nextFrame(self):\n if self.currentFrame is None:\n self.currentFrame = 0\n self.file = open(self.filename, 'r')\n else:\n self.currentFrame += 1\n frameLst = [self.file.readline()]\n if frameLst[0] == '':\n self.file.close()\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a YUV frame from the 3 planes | def __concatenate_planes_to_444yuv_frame(self, y_plane, u_plane, v_plane):
np.set_printoptions(formatter={'int': hex})
y_plane.shape = (self.frame_height, self.frame_width, 1)
u_plane.shape = (self.frame_height, self.frame_width, 1)
v_plane.shape = (self.frame_height, self.frame_width, ... | [
"def YUV_change_mode(y, u, v, direction='420to444'):\n if direction == '420to444':\n u = np.array([cv2.resize(ch, (u.shape[2] * 2, u.shape[1] * 2), interpolation=cv2.INTER_CUBIC) for ch in u])\n v = np.array([cv2.resize(ch, (v.shape[2] * 2, v.shape[1] * 2), interpolation=cv2.INTER_CUBIC) for ch in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class to train and evaluate a Base Cluster Class with Number of Clusters Specified evaluate_by = column name to use to compare across the clusters eventually | def __init__(self,
X,
n_clusters=2,
evaluate_by=None,
scaled=True,
random_state=101,
space=None,
const_params=None,
loss_fun=None):
self.evaluate_by = evaluate_by
if (... | [
"def _eval_classifier(self):\n\n y_pred_baseline = self.df_baseline[self.score_column]\n y_pred_sample = self.df_sample[self.score_column]\n\n y_label_baseline = self.df_baseline[self.label_column]\n y_label_sample = self.df_sample[self.label_column]\n\n precision_baseline = preci... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the number of observations in each cluster | def cluster_obs_count(self):
return(self.merged_data.groupby(
'labels').count().transpose().iloc[0, :]) | [
"def get_cluster_count(self) -> int:\n return len(self.get_all_cluster_ids())",
"def cluster_count(self) -> int:\n cluster_count = max(1, round(16**3 * (self.vein.purity / 100.0) / self.cluster_size))\n return self.distribution.scale_cluster_count(cluster_count)",
"def get_n_clusters(self) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides the means of the cluster features for each cluster If evaluate_by is set, then clusters will be sorted by the mean value of the "evaluate_by" column | def cluster_means(self):
if self.evaluate_by is not None:
return(self.merged_data.groupby(
'labels').mean().sort_values(self.evaluate_by).transpose())
else:
return(self.merged_data.groupby('labels').mean().transpose()) | [
"def cluster_means_scaled(self):\n if self.evaluate_by is not None:\n return(self.merged_scaled_data.groupby(\n 'labels').mean().sort_values(self.evaluate_by).transpose())\n else:\n return(self.merged_scaled_data.groupby(\n 'labels').mean().transpose... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides the means (scaled) of the cluster features for each cluster If evaluate_by is set, then clusters will be sorted by the mean value of the "evaluate_by" column | def cluster_means_scaled(self):
if self.evaluate_by is not None:
return(self.merged_scaled_data.groupby(
'labels').mean().sort_values(self.evaluate_by).transpose())
else:
return(self.merged_scaled_data.groupby(
'labels').mean().transpose()) | [
"def cluster_means(self):\n if self.evaluate_by is not None:\n return(self.merged_data.groupby(\n 'labels').mean().sort_values(self.evaluate_by).transpose())\n else:\n return(self.merged_data.groupby('labels').mean().transpose())",
"def _summarize_clusters(sample... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concatenates all arrays with duplicated IDs. Arrays with the same ids are stacked in chronological order. Caveat This method is not guaranteed to preserve the order of the list. | def concat_duplicate_ids(self) -> None:
# Rebuilt list instead of removing duplicated one at a time at the cost of O(n).
self.data.clear()
# This implementation takes advantage of the ordering of the duplicated in the __init__ method
has_external_ids = set()
for ext_id, items i... | [
"def combine_ids(ids):\r\n return hash_all(sorted(ids)) # We sort so that the id isn't sensitive to order.\r",
"def array_of_duplicates():\n return [1, 2, 3, 3, 4, 5]",
"def flat_unique(ls):\n return list(unique(chain.from_iterable(ls), key=id))",
"def unique_based_on_id(data):\n result, seen = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a specific DatapointsArray from this list by id or exernal_id. | def get( # type: ignore [override]
self,
id: Optional[int] = None,
external_id: Optional[str] = None,
) -> Union[None, DatapointsArray, List[DatapointsArray]]:
# TODO: Question, can we type annotate without specifying the function?
return super().get(id, external_id) # type... | [
"def get( # type: ignore [override]\n self,\n id: Optional[int] = None,\n external_id: Optional[str] = None,\n ) -> Union[None, Datapoints, List[Datapoints]]:\n # TODO: Question, can we type annotate without specifying the function?\n return super().get(id, external_id) # typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a specific Datapoints from this list by id or exernal_id. | def get( # type: ignore [override]
self,
id: Optional[int] = None,
external_id: Optional[str] = None,
) -> Union[None, Datapoints, List[Datapoints]]:
# TODO: Question, can we type annotate without specifying the function?
return super().get(id, external_id) # type: ignore [... | [
"def get( # type: ignore [override]\n self,\n id: Optional[int] = None,\n external_id: Optional[str] = None,\n ) -> Union[None, DatapointsArray, List[DatapointsArray]]:\n # TODO: Question, can we type annotate without specifying the function?\n return super().get(id, external_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Paillier encryption of an Int64 plaintext. Paillier homomorphic addition only directly adds positive values, however, we would like to add both positive and negative values (i.e. int64 is signed). To achieve this, we will represent negative values with twos complement representation. Also, in order to detect overflow a... | def EncryptInt64(self, plaintext, r_value=None):
if not isinstance(plaintext, int) and not isinstance(plaintext, long):
raise ValueError('Expected int or long plaintext but got: %s' %
type(plaintext))
if plaintext < MIN_INT64 or plaintext > MAX_INT64:
raise ValueError('Int64 v... | [
"def encrypt_int(message, ekey, n):\n\n if type(message) is types.IntType:\n return encrypt_int(long(message), ekey, n)\n\n if not type(message) is types.LongType:\n raise TypeError(\"You must pass a long or an int\")\n\n if message > 0 and \\\n math.floor(math.log(message, 2)) > m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Paillier encryption of multiple 64 bit integers into a single payload. | def EncryptMultipleInt64s(self, numberlist, r_value=None):
plaintext = 0
number_counter = 0
if len(numberlist) > PACKING_LIMIT:
raise ValueError('The number of entries in the input list cannot be'
+ ' more than %d' % (PACKING_LIMIT))
for entry in numberlist:
if not isi... | [
"def pack_uint64s(data: List[int]) -> bytes:\n result = b\"\"\n for i in data:\n result += pack_uint64(i)\n return result",
"def encrypt64(data, key, output_type=\"bytes\"): \n padding = new_key(2, 4) # generate 2 32-bit words\n inputs = tuple(bytes_to_words(bytearray(data), 4... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Paillier decryption of ciphertext into multiple int64 values. | def DecryptMultipleInt64s(self, ciphertext):
if not isinstance(ciphertext, int) and not isinstance(ciphertext, long):
raise ValueError('Expected int or long type ciphertext but got: %s' %
type(ciphertext))
plaintext = self.Decrypt(ciphertext)
decrypted_numbers = []
for unuse... | [
"def DecryptInt64(self, ciphertext):\n if not isinstance(ciphertext, int) and not isinstance(ciphertext, long):\n raise ValueError('Expected int or long type ciphertext but got: %s' %\n type(ciphertext))\n plaintext = self.Decrypt(ciphertext)\n return self._Unwrap96bitTo64bit(pla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Paillier decryption of ciphertext into a int64 value. | def DecryptInt64(self, ciphertext):
if not isinstance(ciphertext, int) and not isinstance(ciphertext, long):
raise ValueError('Expected int or long type ciphertext but got: %s' %
type(ciphertext))
plaintext = self.Decrypt(ciphertext)
return self._Unwrap96bitTo64bit(plaintext) | [
"def decrypt(ciphertext):\n return ciphertext",
"def decrypt64(data, key, output_type=\"bytes\"): \n output = invert_bit_permutation128(bytes_to_words(data, 4), key) \n if output_type == \"bytes\": \n return words_to_bytes(output, 4)[:8]\n else:\n if output_type ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encrypt float (IEEE754 binary64bit) values with limited exponents. Paillier homomorphic addition only directly adds positive binary values, however, we would like to add both positive and negative float values | def EncryptFloat(self, plaintext, r_value=None):
if not isinstance(plaintext, float):
raise ValueError('Expected float plaintext but got: %s' % type(plaintext))
input_as_long = struct.unpack('Q', struct.pack('d', plaintext))[0]
mantissa = (input_as_long & 0xfffffffffffff) | 0x10000000000000
expon... | [
"def _enc(x: int) -> float:\n return 2 + x + (29 / (x ** 2 + (1 - x) ** 2))",
"def GFAddition(in1, in2):\n return XOR(in1, in2)",
"def _raw_add(self, e_a, e_b):\n return e_a * e_b % self.public_key.nsquare",
"def DecryptFloat(self, ciphertext):\n original_plaintext = self.Decrypt(ciphertext)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Paillier decryption of ciphertext into a IEEE754 binary64 float value. | def DecryptFloat(self, ciphertext):
original_plaintext = self.Decrypt(ciphertext)
plaintext = original_plaintext
mantissa_and_exponent = plaintext & _ONES_FLOAT_SIGN_LOW_LSB
plaintext >>= FLOAT_SIGN_LOW_LSB # >>= 831
sign_low32 = plaintext & 0xffffffff
plaintext >>= 32
sign_high32 = plainte... | [
"def EncryptFloat(self, plaintext, r_value=None):\n if not isinstance(plaintext, float):\n raise ValueError('Expected float plaintext but got: %s' % type(plaintext))\n\n input_as_long = struct.unpack('Q', struct.pack('d', plaintext))[0]\n mantissa = (input_as_long & 0xfffffffffffff) | 0x10000000000000... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of bytes in the Bignum. | def _NumBytesBn(bn):
if not _FOUND_SSL:
raise RuntimeError('Cannot evaluate _NumBytesBn because ssl library was '
'not found')
size_in_bits = ssl.BN_num_bits(bn)
return int(math.ceil(size_in_bits / 8.0)) | [
"def nbytes(self) -> int:\n nbits = self.nbits()\n if nbits % 8 == 0:\n return int(nbits / 8)\n return int(nbits / 8) + 1",
"def num_bytes(n):\n b = 1\n while 2**b <= n:\n b += 1\n b = b / 8.0\n intb = int(b)\n if intb == b:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses openssl, if available, to do a^b mod c where a,b,c are longs. | def ModExp(a, b, c):
if not _FOUND_SSL:
return pow(a, b, c)
# convert arbitrary long args to bytes
bytes_a = number.LongToBytes(a)
bytes_b = number.LongToBytes(b)
bytes_c = number.LongToBytes(c)
# convert bytes to (pointer to) Bignums.
bn_a = ssl.BN_bin2bn(bytes_a, len(bytes_a), 0)
bn_b = ssl.BN_bi... | [
"def modpower_new(a, b, c):\n\n result = 1 # a**0\n while b > 0:\n if b % 3 == 0:\n result = result % c\n a = a*a*a % c\n if b % 3 == 1:\n result = result*a % c\n a = a*a*a % c\n if b % 3 == 2:\n result = result*a*a % c\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test openssl BN functions ctypes setup for regressions. | def TestSslRegression():
if not _FOUND_SSL:
return
a = 13237154333272387305 # random
b = 14222796656191241573 # random
c = 14335739297692523692 # random
expect_m = 10659231545499717801 # pow(a, b, c)
m = ModExp(a, b, c)
assert m == expect_m, 'TestSslRegression: unexpected ModExp result' | [
"def test_built_libraries(self):\n recipe = Recipe.get_recipe('openssl', self.ctx)\n self.assertTrue(recipe.built_libraries)\n\n recipe = Recipe.get_recipe('pyopenssl', self.ctx)\n self.assertFalse(recipe.built_libraries)",
"def test_ssl_default(self):\n assert security.security... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite the biothings query handler to add graphml format (&format=graphml) added &download=True to download .graphml file automatically, can disable (&download=False) | def write(self, chunk):
try:
if self.format == "graphml":
chunk = edges2graphml(chunk, self.request.uri, self.request.protocol, self.request.host, edge_default="directed")
self.set_header("Content-Type", "text/graphml; charset=utf-8")
if self.args.down... | [
"def get_graphml(self):\n script = self.client.scripts.get('save_graphml')\n return self.gremlin.command(script, params=None)",
"def load_graphml(self,uri):\n script = self.client.scripts.get('load_graphml')\n params = dict(uri=uri)\n return self.gremlin.command(script, params)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if NAPI deny an IPv4 manually creation in a full network. Refactor to allow create the ip. | def test_try_create_ip_in_full_network(self):
name_file = 'api_ip/tests/sanity/ipv4/json/post/ipv4_10_0_4_1_net_8.json'
response = self.client.post(
'/api/v3/ipv4/',
data=json.dumps(self.load_json_file(name_file)),
content_type='application/json')
self.compa... | [
"def OSSupportsIPv4(self) -> bool:",
"def test_ipv4_in_net(self):\n test_ip = ip_address.IPAddress(\"192.168.178.4\", force_v4=True)\n assert test_ip.in_network(\"192.168.178.0/24\")\n assert test_ip.in_network(\"192.168.178.0/29\")\n \n test_ip = ip_address.IPAddress(\"192.168.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if NAPI deny out of range network IPv4 manually creation. | def test_try_create_out_of_range_ip_in_network(self):
name_file = 'api_ip/tests/sanity/ipv4/json/post/out_of_range_ipv4_172_0_0_5_net_5.json'
response = self.client.post(
'/api/v3/ipv4/',
data=json.dumps(self.load_json_file(name_file)),
content_type='application/json... | [
"def test_ipv4_in_range(self):\n\n test_ip = ip_address.IPAddress(\"192.168.178.4\", force_v4=True)\n \n assert test_ip.in_range(\"191.167.0.0\",\"193.169.0.0\")\n assert test_ip.in_range(\"192.167.0.0\",\"192.169.0.0\")\n assert test_ip.in_range(\"192.168.0.0\",\"192.168.255.0\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function implements sieve of Eratosthenes (for all numbers uptil N). Returns array erat_sieve If erat_sieve[i] is True, then 2i + 3 is a prime. | def sieve_of_erat(N):
erat_sieve = [True]*int(N/2)
prime_list = []
prime_list.append(2)
for i in range(int((math.sqrt(N)-3)/2)+1): # Only need to run till sqrt(n)
if erat_sieve[i] == True:
j = i + (2*i+3)
while j < int(N/2):
erat_sieve[j] = False
... | [
"def erathostenes_sieve(n: int) -> List[int]:\n i = 2\n sieve = [[x, True] for x in range(2, n + 1)]\n while i <= sqrt(n):\n j = i\n if sieve[i][1] is False:\n i += 1\n continue\n while j <= n // i:\n sieve[(i * j) - 2][1] = False\n j += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle file(s) arguments from command line This method takes the string(s) which were passed to the cli which indicate the files on which to operate. It expands the path arguments and creates a list of `pathlib.Path` objects which unambiguously point to the files indicated by the cli arguments. | def handle_files_args(*paths_args):
paths = []
for paths_arg in paths_args:
# Handle paths implicitly rooted at user home dir
paths_arg = os.path.expanduser(paths_arg)
# Expand wildcards
paths_arg = glob.glob(paths_arg)
# Create list of pathlib.Path objects
pat... | [
"def add_file_path_args(parser: ArgumentParser):\n\n add_cohort_arg(parser=parser)\n add_iteration_arg(parser=parser)\n add_dataset_arg(parser=parser)\n add_n_kept_feats_arg(parser=parser)\n add_n_clusters_arg(parser=parser)\n add_cluster_method_arg(parser=parser)",
"def get_path_args(args):\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory method to return child of RefFile This method returns either a BibFile or NonbibFile object depending on which is appropriate based on if the `path` arg points to a file containing valid BibTeX or invalid BibTeX, respectively. | def reffile_factory(path):
try:
b = BibFile(path)
except UnparseableBibtexError:
b = NonbibFile(path)
return b | [
"def _create(cls, repo, path, resolve, reference, force, logmsg=None):\r\n full_ref_path = cls.to_full_path(path)\r\n abs_ref_path = join(repo.git_dir, full_ref_path)\r\n \r\n # figure out target data\r\n target = reference\r\n if resolve:\r\n target = repo.rev_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of data corresponding to individual bib files | def construct_bibfile_data(*paths):
bibs = [reffile_factory(path) for path in paths]
return bibs | [
"def _FindBibEntries(self):\n bibs = \" \".join(glob.glob(\"*.bib\"))\n cat_process = subprocess.Popen(shlex.split(\"cat %s\" % bibs),\n stdout=subprocess.PIPE)\n grep_process = subprocess.Popen(shlex.split(\"grep ^@\"),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sublist of bibfile_data whos elements are val_type This method examines each bib_dict element of a bibfile_data list and returns the subset which can be classified according to val_type. | def bib_sublist(bibfile_data, val_type):
sublist = [bibfile for bibfile in bibfile_data if isinstance(bibfile.bib, val_type)]
return sublist | [
"def test_bib_sublist(self):\n bibfile_data = utils.construct_bibfile_data(self.empty, self.invalid)\n self.assertIsInstance(utils.bib_sublist(bibfile_data, BibliographyData), list)",
"def bib_subvalues(self):\n\n\t\tif not self.subvals:\n\n\t\t\t# à remplir dict de listes\n\t\t\txml_subtexts_by_fie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate appropriate message for STDOUT This method creates the string to be printed to STDOUT from the items of the `bibfile_data` list argument. It generates either a terse or verbose message based on the state of the `verbose` argument. | def gen_stdout_test_msg(bibfile_data, verbose=False):
msg_list = [bibfile.test_msg(verbose) for bibfile in bibfile_data]
msg = "\n".join(msg_list)
return msg | [
"def verbose(message):\n if args.verbose:\n print(message)",
"def test_gen_stdout_test_msg(self):\n bibfile_data = utils.construct_bibfile_data(self.empty)\n self.assertIsInstance(utils.gen_stdout_test_msg(bibfile_data), unicode)",
"def verbose_print(self, msg=\"\", prefix=\"\", end=\"\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function determines if the user input is a valid player. If input is 'Q', exits program. | def is_valid_player(user_input):
i = user_input.upper()
if i in Board.player_decoder:
return True
elif i == 'Q':
exit("\nExiting program. Thanks for using Clue Detective!\n")
else:
return False | [
"def validate_user_input(user_input):\n responses = ['t', 'r', 'q']\n return user_input in responses",
"def player_input():\n x_o = ['X', 'O']\n player = \"\"\n while True:\n player = input('Choose your player X or O: ')\n if player.upper() in x_o:\n break\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function determines if the user input is a valid card. If skip = True, also allows 'X' as a valid input. If input is 'Q', exits program. | def is_valid(user_input, card_type=None, skip=False):
i = user_input.upper()
if i == 'Q':
exit("\nExiting program. Thanks for using Clue Detective!\n")
if skip:
if i == 'X':
return True
if card_type:
key_list = [key for key in Board.input_decoder
... | [
"def is_valid_player(user_input):\n \n i = user_input.upper()\n if i in Board.player_decoder:\n return True\n elif i == 'Q':\n exit(\"\\nExiting program. Thanks for using Clue Detective!\\n\")\n else:\n return False",
"def validDealInput(self):\n \"\"\"Function to get a ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function collects a list user inputs for players and suspects and decodes them. | def collect_players_and_suspects_list():
players_list = []
while (players_input := input("Enter player: ")) != '#':
i = players_input.upper()
if not is_valid_player(i):
print("Please enter a valid Suspect.")
continue
if i not in players_list:
play... | [
"def collect_players_list():\n \n players_list = []\n while (players_input := input(\"Enter player: \")) != '#':\n i = players_input.upper()\n if not is_valid_player(i):\n print(\"Please enter a valid Suspect.\")\n continue\n if i not in players_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function collects a list user inputs for players and decodes them. | def collect_players_list():
players_list = []
while (players_input := input("Enter player: ")) != '#':
i = players_input.upper()
if not is_valid_player(i):
print("Please enter a valid Suspect.")
continue
if i not in players_list:
players_list.appe... | [
"def collect_players_and_suspects_list():\n \n players_list = []\n while (players_input := input(\"Enter player: \")) != '#':\n i = players_input.upper()\n if not is_valid_player(i):\n print(\"Please enter a valid Suspect.\")\n continue\n if i not in players_list:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function collects a list user inputs for cards and decodes them. | def collect_cards():
cards_list = []
while (cards_input := input("Enter card: ")) != '#':
i = cards_input.upper()
if not is_valid(i):
print(f"Please enter a valid card.")
continue
cards_list.append(i)
cards_decoded = [Board.translate(card) for card in car... | [
"def collect_players_list():\n \n players_list = []\n while (players_input := input(\"Enter player: \")) != '#':\n i = players_input.upper()\n if not is_valid_player(i):\n print(\"Please enter a valid Suspect.\")\n continue\n if i not in players_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tuple with name and symbol order of symbol table node gdbval | def get_symbol_name_order(gdbval):
return (symtab_node_name (gdbval), int(gdbval["order"])) | [
"def build_gdb_symbol_table():\n\n tab = Symtab()\n n = gdb.parse_and_eval (\"symtab->nodes\")\n while (long(n)):\n if symtab_node_is_function (n):\n current_symbol = GdbFunction(tab, n)\n tab.all_functions.append (current_symbol)\n elif symtab_node_is_variable (n):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return pruned candidates containing only flags that are set in gdbval | def bool_attr_list(gdbval, candidates):
r = []
for i in candidates:
if long (gdbval[i]) != 0:
r.append(i)
pass
pass
return r | [
"def _parse_refprune_flags():\n flags = config.LLVM_REFPRUNE_FLAGS.split(',')\n if not flags:\n return 0\n val = 0\n for item in flags:\n item = item.strip()\n try:\n val |= getattr(ll.RefPruneSubpasses, item.upper())\n except AttributeError:\n warnings.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To be made method. Loads common attributes from symbol base | def load_symtab_base_attrs(self):
sym = self.gdbval
vis = bool_attr_list (sym, ["in_other_partition",
"used_from_other_partition", "force_output",
"forced_by_abi", "externally_visible"])
vis.extend(bool_attr_list_1(sym["decl"]["base"],
... | [
"def __extract_common_attrs(self, raw_data: Dict) -> None:\n for attr in self.COMMON_ATTRS:\n if attr not in self.ATTRS and attr in raw_data:\n setattr(self, attr, raw_data[attr])",
"def load_attribute_data():\n global attr_value_counts, attr_counts, value_counts, \\\n attr_va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return orders of nodes ipa_ref_list references | def gather_references_orders (gdbval):
# TODO: Somehow also note speculative references and attributes in
# general
vec = gdbval["references"]
return [int(i["referred"]["order"]) for i in vec_iter(vec)] | [
"def gather_referring_orders (gdbval):\n# TODO: Somehow also note speculative references and attributes in\n# general\n vec = gdbval[\"referring\"]\n return [int(i[\"referring\"][\"order\"]) for i in vec_iter(vec)]",
"def topo_sort_adjacent_nodes(self,n,ref_nbr=None):\n nbrs=list(self.node_to_nodes(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return orders of nodes referring node associated with ipa_ref_list | def gather_referring_orders (gdbval):
# TODO: Somehow also note speculative references and attributes in
# general
vec = gdbval["referring"]
return [int(i["referring"]["order"]) for i in vec_iter(vec)] | [
"def gather_references_orders (gdbval):\n# TODO: Somehow also note speculative references and attributes in\n# general\n vec = gdbval[\"references\"]\n return [int(i[\"referred\"][\"order\"]) for i in vec_iter(vec)]",
"def topo_sort_adjacent_nodes(self,n,ref_nbr=None):\n nbrs=list(self.node_to_nodes(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build and return our representation of the symbol table | def build_gdb_symbol_table():
tab = Symtab()
n = gdb.parse_and_eval ("symtab->nodes")
while (long(n)):
if symtab_node_is_function (n):
current_symbol = GdbFunction(tab, n)
tab.all_functions.append (current_symbol)
elif symtab_node_is_variable (n):
current... | [
"def get_symbol_table(self):\n return self.symbol_table",
"def __str__(self):\n dictt = self.getFullDict()\n return \"SymbolTable(\\n{}\\n)\".format(pprint.pformat(dictt))",
"def symbol_table(self) -> str:\n return self._symbol_table",
"def getSymbolTable(self) -> ghidra.app.util.b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a question ID, returns a tuple containing a list of the reference answers, human answers (Answer objects), and the canonical answer id | def __getitem__(self, qid):
ref = []
if qid in self._reference:
ref = self._reference[qid]
hum = []
if qid in self._human:
hum = self._human[qid]
aid = [-1, ""]
if qid in self._id:
aid = self._id[qid]
else:
logger.warning("Answer ID %s missing" % qid)
return r... | [
"def get_answer(self, answer_id):\n return self.answers[answer_id]",
"def get_answers_by_answer_id(self, answer_id):\n return self._answers_by_id.get(answer_id)",
"def get_answers(self, assessment_section_id, item_id):\n return # osid.assessment.AnswerList",
"def get_answer_comments(answe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a question, find where "ftp" occurs. Assumes features have been preprocessed. | def find_ftp(features):
ftp_pos = -1
for ii in xrange(len(features)):
index, word = features[ii]
if word == 'ftp':
ftp_pos = index
return ftp_pos | [
"def get_local_ftp_listing(prod_id_to_chk):\n # print(\"I'm in \"+sys._getframe().f_code.co_name)\n #logging.info(\"I am in \"+sys._getframe().f_code.co_name)\n\n # <Removing ZIP-Storage>: for use with ZIP-files\n# product_match = findfile(prod_id_to_chk+'*', config['local.ftp_inpath'], splitpath=Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
String. WWID of current mpath. | def wwid(self):
return self._uuid | [
"def wwid(self) -> str:\n return pulumi.get(self, \"wwid\")",
"def wwid(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"wwid\")",
"def windows_path(self):\n return self._windows_path.replace(\"\\\\\", \"/\")",
"def device_get_wwid(udev_info):\n serial = device_get_ser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of DMMP_path objects | def paths(self):
rc = []
for pg in self.path_groups:
rc.extend(pg.paths)
return rc | [
"def listPaths():\n try:\n paths = [x[1] for x in parseFstab(FSTAB)]\n return paths\n except DMException:\n return []",
"def htmllibmanager_path_list(self) -> ConfigNodePropertyArray:\n return self._htmllibmanager_path_list",
"def _get_path_objs(self, path_list):\n objs ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns n points evenly spaced along the perimeter of a circle of diameter d centered at the origin, if type = 'int' the coordinates are rounded to the neares integer | def perimeter_points(d,n,type = 'int'):
rimpointsx = np.sin(np.linspace(0,2*np.pi,num=n,endpoint = False)) + 1
rimpointsy = np.cos(np.linspace(0,2*np.pi,num=n,endpoint = False)) + 1
rimpoints = (((d-1)/2))*np.array([rimpointsy,rimpointsx])
if type == 'int':
rimpoints = np.round(rimpoints)
... | [
"def discretized_circle(radius, n_pts):\n x1 = np.zeros(n_pts)\n y1 = np.zeros(n_pts)\n for i in range(0, n_pts):\n x1[i] = np.cos(2 * np.pi / n_pts * i) * radius\n y1[i] = np.sin(2 * np.pi / n_pts * i) * radius\n\n x2 = np.roll(x1, -1)\n y2 = np.roll(y1, -1)\n return x1, y1, x2, y2"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Outputs the matrix with with to adjust the gradient after adding the line between p1 and p2 | def line_contribution(p1,p2,alpha = 1):
adjust = np.zeros((worksize,worksize,2))
x1 = p1[0]
y1 = p1[1]
x2 = p2[0]
y2 = p2[1]
coordinates = coordinate_matrix(worksize)
numerator = np.sum(np.multiply(coordinates,np.reshape(np.array(((y2-y1,-(x2-x1)))),(2,1,1))),axis = 0) + x2*y1 - y2*x1
... | [
"def calculate_gradient(p1, p2):\n # Ensure that the line is not vertical\n if p1[0] == p2[0]:\n return None\n m = (p1[1] - p2[1]) / (p1[0] - p2[0])\n return m",
"def gradient(self):\n y_pred = self.X.dot(self.coef)\n self.grad_coef = np.array(-(self.y - y_pred... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |