query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Display all the videos whose titles contain the search_term. | def search_videos(self, search_term):
videos = self._video_library.get_all_videos()
temp_list = []
for vid in videos:
# Convoluted way to display tags in required format
tags = "["
for tag in vid.tags:
tags = tags + tag + " "
tags... | [
"def search_videos(self, search_term):\n videos = self._video_library.get_all_videos()\n matched_videos = []\n for video in videos:\n if search_term.upper() in video.title.upper() and video.flag_reason == None:\n matched_videos.append(video)\n if len(matched_vid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display all videos whose tags contains the provided tag. | def search_videos_tag(self, video_tag):
videos = self._video_library.get_all_videos()
temp_list = []
for vid in videos:
# Convoluted way to display tags in required format
tags ="["
for tag in vid.tags:
tags = tags + tag + " "
tag... | [
"def search_videos_tag(self, video_tag):\n results = []\n for video in self._video_library.get_all_videos():\n if video_tag.lower() in video.tags and video.flag is None:\n results.append(video)\n self.output_search_results(results, video_tag)",
"def search_videos_tag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get current active operational dataset in TLVS format, or None. | async def get_active_dataset_tlvs(self) -> bytes | None:
return await self.api.get_active_dataset_tlvs() | [
"async def async_get_active_dataset_tlvs(hass: HomeAssistant) -> bytes | None:\n if DOMAIN not in hass.data:\n raise HomeAssistantError(\"OTBR API not available\")\n\n data: OTBRData = hass.data[DOMAIN]\n return await data.get_active_dataset_tlvs()",
"def ata_smart_data(self) -> SmartSsdAtaSmartDa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an active operational dataset. | async def create_active_dataset(
self, dataset: python_otbr_api.OperationalDataSet
) -> None:
return await self.api.create_active_dataset(dataset) | [
"def create_dataset(store, dataset, author=None, initial_head='main'):\n dataset_path = store.get_dataset_path(dataset)\n if os.path.isdir(dataset_path):\n raise Exception('Dataset already exists')\n if not author:\n author = pygit2.Signature(COMMITTER_NAME, COMMITTER_EMAIL)\n repo = pygit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Warn user if insecure default network settings are used. | def _warn_on_default_network_settings(
hass: HomeAssistant, entry: ConfigEntry, dataset_tlvs: bytes
) -> None:
dataset = tlv_parser.parse_tlv(dataset_tlvs.hex())
insecure = False
if (
network_key := dataset.get(tlv_parser.MeshcopTLVType.NETWORKKEY)
) is not None and bytes.fromhex(network_ke... | [
"def suppress_insecure_request_warns(env) -> bool:\n verify = True\n if env in SUPPRESS_WARNING_ENVS:\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n verify = False\n return verify",
"def check_deprecated_options(self):\r\n creds = config.nova_creds\r\n if creds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unload a config entry. | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.pop(DOMAIN)
return True | [
"async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):\n return await hass.config_entries.async_forward_entry_unload(entry, PLATFORM)",
"async def async_unload_entry(hass, config_entry):\n hass.data.pop(DOMAIN)\n return True",
"async def async_unload_entry(hass, config_entry):\n unl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get current active operational dataset in TLVS format, or None. Returns None if there is no active operational dataset. Raises if the http status is 400 or higher or if the response is invalid. | async def async_get_active_dataset_tlvs(hass: HomeAssistant) -> bytes | None:
if DOMAIN not in hass.data:
raise HomeAssistantError("OTBR API not available")
data: OTBRData = hass.data[DOMAIN]
return await data.get_active_dataset_tlvs() | [
"async def get_active_dataset_tlvs(self) -> bytes | None:\n return await self.api.get_active_dataset_tlvs()",
"def _load_data(self):\n url = urljoin(self.base_url, 'levels')\n resp = requests.get(url, headers=self.headers)\n # TOOD: Confirm/deny that this is a real API for the levels c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is the_cats_ass. That's an overstatement. This is an understatement. See what I did there? What _you_ can do here is save the sys.ENVIRONMENT by reducing printed waste. Mew. | def the_cats_ass():
return __cat_whisperer()[Cat.ASS] | [
"def getEnv():",
"def env_cleanup(self):\n pass",
"def get_environment():\n\n complus_vars = defaultdict(lambda: \"\")\n \n for key in os.environ:\n if \"complus\" in key.lower():\n complus_vars[key] = os.environ[key]\n os.environ[key] = ''\n elif \"superpmi\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
You really shouldn't be poking cats. But if you insist, it is recommended to bring catnip as it's not unusual for cats to attack dicks who poke them. | def poke_the_cat(where, catnip=False):
if not catnip:
from random import randint
class BadCat(InterruptedError):
pass
if randint(1, 10) == 7:
mew = "You attempt to poke the cat but it attacks. " \
"Maybe if you gave it some catnip?"
rai... | [
"def schrodingers_cat(peek=False):\n from random import choice, randint\n if peek:\n if randint(1, 10) % 2 == 0:\n # RIP\n return \"Nothing at all\"\n else:\n return poke_the_cat(Cat.LEGS, catnip=True)\n else:\n garbled_cries = \"mew meow wokka beocat e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Peek in the box for a 50/50 shot of retrieving your desired output, while the other half of the time the cat is dead and the function returns nothing at all. If you decide not to peek, the cat being neither dead nor alive responds with random nonsense. | def schrodingers_cat(peek=False):
from random import choice, randint
if peek:
if randint(1, 10) % 2 == 0:
# RIP
return "Nothing at all"
else:
return poke_the_cat(Cat.LEGS, catnip=True)
else:
garbled_cries = "mew meow wokka beocat ekkie".split()
... | [
"def test_peek_shows_value_of_current_tail(dq_3):\n assert dq_3.peek() == 'ragtime'",
"def poke_the_cat(where, catnip=False):\n if not catnip:\n from random import randint\n\n class BadCat(InterruptedError):\n pass\n\n if randint(1, 10) == 7:\n mew = \"You attempt ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Thread that polls to get the current force on the FSR. Populates the self._average_force value. | def _force_loop(self):
NUM_SAMPLES = 10.0
# Get the initial readings
time.sleep(1)
readings = []
for i in range(0, int(NUM_SAMPLES)):
readings.insert(0, self._sensor.value)
time.sleep(self._sampling_rate)
self._average_force = sum(r for r in read... | [
"def get_force(self):\n # @todo: Probably need to check the state of the landing gear for this (e.g. are they on the track?).\n # Note: you can get the state of the landing gear by going through self.sim \n return 0.0",
"def _update_average(self):\n\n # do request\n r = requests... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a natural gutter between start and stop, inclusive. | def get_gutter(start_obj, stop_obj):
log.debug(f'get_gutter({start_obj.group(0)}, {stop_obj.group(0)})')
start = start_obj.end(0)
stop = stop_obj.start(0)-1
gutters = list()
for column in range(start, stop+1):
if all(line.rjust(column+1)[column] == ' ' for line in lines):
gutters.append(column)
i... | [
"def GetNiceExtentsBySpacing(minval,maxval,spacing,tolerance):\n pass",
"def gutter(self):\n return self._sectPr.gutter",
"def find_midpoint(start, end):\n mid = (start + end) / 2\n return int(mid)",
"def range_1(stop: int) -> range:\n return range(1, stop + 1)",
"def scanner_pos_at_round... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of request names of requests in runningopen state | def getRunningOpen(self, teamName):
result = []
for request in self.status:
if self.status[request] == 'running-open':
result.append(request)
return result | [
"def get_active_requests_from_wmstats(self):\n self.logger.info('Will get list of requests which are currently putting data to DBS')\n url = '/wmstatsserver/data/filtered_requests?mask=RequestName'\n request_list = make_cmsweb_request(url).get('result', [])\n request_list = [request['Req... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for rendering the home page | def render_home():
return render_template("index.html") | [
"def home():\r\n return render_template('home.html')",
"def home():\n return render_template(\n 'home.html',\n title='Home Page',\n )",
"def home_page() -> str:\r\n return render_template(\"home.html\")",
"def homepage():\n return render_template('home/index.html')",
"def homepa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for rendering an existing session page | def render_player_session(id):
sess = get_player_session(id)
if sess:
pass
#return render_template("session.html")
else:
pass
#some kind of 404
| [
"def get(self, _: str) -> None:\n\n self.render_template('practice-session-page.mainpage.html')",
"def angular_main_page():\n print(session)\n return render_template(\"/angular_main_page.html\")",
"def session_view(course_id, section, classname):\n cur = get_db().cursor()\n\n cur.execute(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for rendering a DM session page | def render_DM_session(id):
sess = get_DM_session(id)
if sess:
pass
else:
pass | [
"def render_player_session(id):\r\n\tsess = get_player_session(id)\r\n\tif sess:\r\n\t\tpass\r\n\t\t#return render_template(\"session.html\")\r\n\telse:\r\n\t\tpass\t\t\r\n\t\t#some kind of 404\r",
"def get(self, _: str) -> None:\n\n self.render_template('practice-session-page.mainpage.html')",
"def show... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return user properties from OGDS. Always returns a minimal set of the properties 'ogg.user.userid' and 'ogg.user.title' even when no ogdsuser is found. | def _collect_properties(self):
properties = {
'userid': self.user_id,
'title': self.get_fullname()
}
if not self.ogds_user:
return properties
for attribute_name in self.ogds_user_attributes:
value = getattr(self.ogds_user, attribute_name)
... | [
"def getdat(user):\r\n profile = user.profile\r\n return [user.username, user.email] + [getattr(profile, xkey, '') for xkey in profkeys]",
"def get_pet_user_info():\n\n return db.session.query(User.email, Pet.pet_name, Pet.pet_type, Pet.pet_breed, \n Pet.pe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls functions in each NN file to get results. Starts with python, calls run file for c++ versions | def get_results():
#Get python results
import mnist_nn
import mnist_nn_gpu
mnist_nn.save_results()
mnist_nn_gpu.save_results()
#Get cpp results
import subprocess
subprocess.call(['c++//./run.sh']) | [
"def main():\n home = expanduser(\"~\")\n project_dir = \"handwritten_digit_classifer/\"\n path_to_project = os.path.join(home, project_dir)\n train_model(path_to_project)",
"def main():\n args = get_flags()\n\n noun_classes_per_sense = pd.read_csv(\n args.ncfile, sep='\\\\', names=['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create tables Start with Times table, load in the data and put into useful lists. Load lists into numpy array, then create cell text. Create columns, column colors, then create the table and save it. Repeat for accuracy table. | def create_tables(times, accuracies, batch_sizes):
#Get time data
p_cpu_times = list(times[0].values())
p_gpu_times = list(times[1].values())
c_cpu_times = list(times[2].values())
c_gpu_times = list(times[3].values())
#Get differences in times
p_diff_times = [a - b for a, b in zip(p... | [
"def table_maker():\r\n try:\r\n off_copy = off.copy()\r\n man_copy = man.copy()\r\n exe_copy = exe.copy()\r\n ceo_copy = ceo.copy()\r\n list_of_lists = [off_copy, man_copy, exe_copy, ceo_copy]\r\n\r\n for i in list_of_lists:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create accuracy plots for each batch size Load in accuracy information into useful lists, then create a plot. Each plot has the accuracy for all 4 datasets listed | def create_batch_plots(accuracies, batch_sizes):
#Get accuracy data
p_cpu_accuracy = list(accuracies[0].values())
p_gpu_accuracy = list(accuracies[1].values())
c_cpu_accuracy = list(accuracies[2].values())
c_gpu_accuracy = list(accuracies[3].values())
#Create plot for each batch size... | [
"def accuracy_plot(LS_sizes, data_fun):\r\n\r\n opt_neigh = []\r\n\r\n #plot of optimal n_neighbors as a function of the LS size\r\n\r\n for size in LS_sizes:\r\n\r\n acc = []\r\n neighbors_values = np.arange(1,size+1,1)\r\n\r\n # For a given LS size, plots of accuracy(n_neighbors)\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables some of the global JAX flags for debugging. | def enable_jax_debugging_flags():
# Enable the NaN-checker behavior to cause JAX to hard-break on the first
# occurrence of a NaN.
jax.config.update('jax_debug_nans', True)
# Enable the compilation logger to check whether or not we're accidentally
# causing a lot of re-compilation (inspect logs for excessiv... | [
"def debug(self, flag):\n self.debugging = flag",
"def _pma_set_debug_flag(flag):\n global _pma_debug\n\n if not isinstance(flag, (bool)):\n raise Exception(\"flag argument must be of class bool\")\n _pma_debug = flag\n if flag is True:\n print(\"Debug flag enabled. You will recei... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse an input specs into a jax.ShapeDtypeStruct. | def input_spec_to_jax_shape_dtype_struct(
spec: Union[Tuple[Tuple[int, ...], jnp.dtype], Tuple[int, ...]],
batch_size: Optional[int] = None) -> jax.ShapeDtypeStruct:
spec = tuple(spec)
if len(spec) == 2 and isinstance(spec[0], collections.abc.Iterable):
shape = (batch_size,) + tuple(spec[0][1:]) if batc... | [
"def read_struct_skeleton(xdrdata):\n # Read Number of tags\n ntags = xdrdata.unpack_uint()\n # Read names of tags\n tags = [xdrdata.unpack_string() for n in range(ntags)]\n # Read the tag type\n tagdict = OrderedDict()\n for tt in tags:\n dim = xdrdata.unpack_uint()\n arr_size = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load dataset from file '../data/dataset.txt' and transfer to a list. | def load_data():
with open('../data/dataset.txt', 'r') as data_file:
return data_file.read().split('\n') | [
"def load_datasets(filepath):\n\n data_file = open(filepath, 'r')\n data_list = data_file.readlines()\n data_file.close()\n\n return data_list",
"def load_dataset(files):\n data = []\n for file in files:\n data.extend(read_file(file))\n return data",
"def load_data(file_name: str) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load stop words from file '../data/stop_words.txt' and transfer to a list. | def load_stop_words():
with open('../data/stop_words.txt', 'r') as stop_words_file:
return stop_words_file.read().split() | [
"def load_stop_list():\n stop_list = []\n with open(STOP_LIST, \"r\") as f:\n lines = f.readlines()\n stop_list = [word.strip() for word in lines]\n return stop_list",
"def load_stop_words_list(self):\n\n from os.path import join\n stop_word_obj = stop_words_parser()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a label list according to the first word in each line of dataset. | def generate_labels():
label_set = set([])
for data in load_data():
label = data.split(' ', 1)[0]
label_set.add(label)
labels = list(label_set)
labels.sort()
return labels | [
"def seperate_data_lables(data):\n features = []\n labels = []\n for element in data:\n #print(element)\n features.append(element[0])\n labels.append(element[1][0])\n return features, labels",
"def labels(data):\n\n return data[:,0]",
"def first_label(self):\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write labels to file '../data/labels.txt', each line is a label | def write_labels():
with open('../data/labels.txt', 'w') as labels_file:
labels = generate_labels()
labels_file.write('\n'.join(labels)) | [
"def write_output(labels):\n with open('./nboutput.txt', 'w', encoding='latin1') as f:\n for path, label in labels.items():\n f.write(label + '\\t' + path + '\\n')",
"def _write_labels(self, labels: List[str], labels_path: Path):\n labels_path.write_text(escape_line_delimited_texts(lab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate corpus from dataset, remove label from every question. | def generate_corpus():
data = load_data()
questions = [s.split(' ', 1)[1].lower() for s in data]
return questions | [
"def get_corpus(dataset_path, debug='no'):\n assert os.path.isdir(dataset_path), 'invalid dataset path.'\n all_files = get_all_files(dataset_path)\n corpus = []\n if len(all_files) > 0:\n with Pool(pool_size) as p:\n tokens_list = p.starmap(preprocess, zip(all_files, repeat(debug)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write vocabulary to '../data/vocabulary.txt', each line contains a word and its frequency. | def write_vocabulary():
with open('../data/vocabulary.txt', 'w') as vocabulary_file:
vocabulary = generate_vocabulary()
word_count = sum(vocabulary.values())
print(word_count)
vocabs_str = [("%s %d" % (key, value)) for key, value in vocabulary.items()]
vocabulary_file.write('... | [
"def dump_vocab(vocab, path, encoding=\"Utf-8\"):\n with open(path, \"w\", encoding=encoding) as fout:\n for word, freq in vocab:\n fout.write(\"%s\\t%d\\n\" % (word, freq))",
"def save_vocab(self):\n opts = self._options\n self._logger.info('Saving vocabulary to file.'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns variable value from launch params | def get_action_var_val_from_launch_params(launch_vars, var_name):
filtered_launch_vars = list(
filter(
lambda e: e["name"] == var_name,
launch_vars,
)
)
if len(filtered_launch_vars) > 1:
LOG.error(
"Unable to populate runtime editables: Multiple ... | [
"def getParameter(self,value):\n if value in self.commandLineDefaults:\n return self.commandLineDefaults[value]\n if value in self.defaults:\n return self.defaults[value]\n return None",
"def getParameter(self, value):\n if value in self.commandLineDefaults:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns patch arguments or variable data | def get_patch_runtime_args(
app_uuid, deployments, patch_payload, ignore_runtime_variables, runtime_params_file
):
patch_name = patch_payload["name"]
patch_args = {}
patch_args["patch"] = patch_payload
patch_args["variables"] = []
attrs_list = patch_payload["attrs_list"]
if ignore_runtim... | [
"def arguments(self):\n return parse_arguments(self['data'])",
"def build_patchargs(self, **kwargs):\n raise NotImplementedError(\"This method should be overridden in the child class\")",
"def _patches(s):\n if hasattr(s,'dict'):\n pp=s.patches\n elif isinstance(s,dispatch._dispatch._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download runlogs, given runlog uuid and app name | def download_runlog(runlog_id, app_name, file_name):
client = get_api_client()
app = _get_app(client, app_name)
app_id = app["metadata"]["uuid"]
if not file_name:
file_name = "runlog_{}.zip".format(runlog_id)
res, err = client.application.download_runlog(app_id, runlog_id)
if not err:... | [
"def fetch_run_logs(id_, **kwargs):\n run = get_run_object(id_)\n check_run_permission(run, kwargs[\"token_info\"])\n query = \"ilyde-run-{}\".format(run.id)\n return query_elasticsearch(query)",
"def serve_download_experiment_log(log_name):\n key = f'experiment:log:{log_name}'\n log = r.get(key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an auto configured output to the layout This will place the output in a sensible location in the layout. The coordinates of the output in the layout may adjust dynamically when the layout changes. If the output is already in the layout, it will become auto configured. If the position of the output is set such as wi... | def add_auto(self, output: Output) -> None:
lib.wlr_output_layout_add_auto(self._ptr, output._ptr) | [
"def add(self, output: Output, lx: int, ly: int) -> None:\n lib.wlr_output_layout_add(self._ptr, output._ptr, lx, ly)",
"def move(self, output: Output, lx: int, ly: int) -> None:\n lib.wlr_output_layout_move(self._ptr, output._ptr, lx, ly)",
"def outputPin(self):\r\n start = self._yCenter +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine coordinates of the output in the layout Given x and y in layout coordinates, adjusts them to local output coordinates relative to the given reference output. | def output_coords(self, output: Output) -> tuple[float, float]:
ox = ffi.new("double *")
oy = ffi.new("double *")
lib.wlr_output_layout_output_coords(self._ptr, output._ptr, ox, oy)
return ox[0], oy[0] | [
"def compute_position(layout):\n\n if layout.children:\n toyplot_vertical_align = layout.style[\"-toyplot-vertical-align\"]\n # Align the first line's baseline with the anchor.\n if toyplot_vertical_align == \"first-baseline\":\n offset_y = 0\n # Ali... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the output layout in a context manager | def __enter__(self) -> OutputLayout:
return self | [
"def Output(self):\n self.Open()\n self.Header()\n self.Body()\n self.Footer()",
"def _generate_layout(self):\n\n pass",
"def output(self, layout: Optional[dict] = None) -> OutputWidget:\n return OutputWidget(self, layout)",
"def _create_output_layout(self):\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the output at the specified layout coordinates. Returns None if no output matches the coordinates. | def output_at(self, x: float, y: float) -> Output | None:
output_ptr = lib.wlr_output_layout_output_at(self._ptr, x, y)
if output_ptr == ffi.NULL:
return None
return Output(output_ptr) | [
"def output_coords(self, output: Output) -> tuple[float, float]:\n ox = ffi.new(\"double *\")\n oy = ffi.new(\"double *\")\n lib.wlr_output_layout_output_coords(self._ptr, output._ptr, ox, oy)\n\n return ox[0], oy[0]",
"def find_output(self, name):\n return self.output_index.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the output to the layout at the specified coordinates. If the output is already part of the output layout, this moves the output. | def add(self, output: Output, lx: int, ly: int) -> None:
lib.wlr_output_layout_add(self._ptr, output._ptr, lx, ly) | [
"def move(self, output: Output, lx: int, ly: int) -> None:\n lib.wlr_output_layout_move(self._ptr, output._ptr, lx, ly)",
"def add_output(self, output):\n self._outputs.append(output)",
"def output_position(self, output_position: int):\n\n self._output_position = output_position",
"def output... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move an output to specified coordinates. | def move(self, output: Output, lx: int, ly: int) -> None:
lib.wlr_output_layout_move(self._ptr, output._ptr, lx, ly) | [
"def move_to(self, destination_coords):\n self.x = destination_coords[0]\n self.y = destination_coords[1]\n return",
"def moveOutputs(model):\n fn = model.outputgrid\n os.system('mv %s %s%s' % (fn, model.directory, fn))\n return",
"def move_stage_to_xy(self, coordinates):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove an output from the layout. | def remove(self, output: Output) -> None:
lib.wlr_output_layout_remove(self._ptr, output._ptr) | [
"def remove_layout(self, layout: Layout):\n self.layouts.pop(layout, None)",
"def removeLayout(self, *args):\n return _libsbml.LayoutModelPlugin_removeLayout(self, *args)",
"def removeOutput(self, *args):\n return _libsbml.Transition_removeOutput(self, *args)",
"def _remove_output(self, n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the box of the layout for the given reference output in layout coordinates. If `reference` is None, the box will be for the extents of the entire layout. If the output isn't in the layout, the box will be empty. | def get_box(
self, reference: Output | None = None, dest_box: Box | None = None
) -> Box:
if reference:
reference_ptr = reference._ptr
else:
reference_ptr = ffi.NULL
if not dest_box:
dest_box = Box(ptr=ffi.new("struct wlr_box *"))
lib.wlr... | [
"def node_format(surface, node, reference=True):\n reference_size = 'xy' if reference else (0, 0)\n width = size(surface, node.get('width', '100%'), reference_size[0])\n height = size(surface, node.get('height', '100%'), reference_size[1])\n viewbox = node.get('viewBox')\n if viewbox:\n viewbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the closest point on this layout from the given point from the reference output. If reference is NULL, gets the closest point from the entire layout. | def closest_point(
self, lx: float, ly: float, reference: Output | None = None
) -> tuple[float, float]:
if reference:
reference_ptr = reference._ptr
else:
reference_ptr = ffi.NULL
dest_lx = ffi.new("double *")
dest_ly = ffi.new("double *")
li... | [
"def closest_point(self, point):\n return self.point_on_line(self.closest_point_param(point))",
"def get_closest_point(self, point):\n distance_to_start_point = find_distance(self.start_point, point)\n distance_to_end_point = find_distance(self.end_point, point)\n return self.start_poi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the current_state to the initial_state (0) and sets input_symbol to None. | def reset (self):
self.currentState = self.initialState
self.inputSymbol = None | [
"def reset(self):\n\t\t\n\t\tself.current_state = self.initial_state\n\t\tself.input_symbol = None",
"def reset (self):\n\n self.current_state = self.initial_state\n self.input_symbol = None",
"def reset(self):\n self.current_state = None",
"def reset(self):\n self.state = self.res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This sets the default transition. This defines an action and next_state if the FSM cannot find the input symbol provided by the user and the current state in the transition list. The default transition can be removed by setting the attribute defaultTransition to None. In this case, for default the nextState will be the... | def setDefaultTransition (self, action, nextState):
if nextState is not None:
self.defaultTransition = (action, nextState)
else:
self.defaultTransition = (action, self.initialState) | [
"def ForceDefaultStates(self):\n self.TransitionTo(_standing)\n self.TransitionTo(_stopped)\n self.TransitionTo(_idle)",
"def getTransition (self, inputSymbol, state):\n\n if (inputSymbol, state) in self.stateTransitions:\n return self.stateTransitions[(inputSymbol, state)]\n eli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method returns the tuples (action, next state) given an inputSymbol and state. | def getTransition (self, inputSymbol, state):
if (inputSymbol, state) in self.stateTransitions:
return self.stateTransitions[(inputSymbol, state)]
elif self.defaultTransition is not None:
return self.defaultTransition
else:
raise ExceptionFSM ('Transition is ... | [
"def get_next_state(self, state, action):\n pass",
"def get_next_states(self, state, action):\n pass",
"def __getNextState(self, action, state=None):\n if state is None:\n x = self.__state\n else:\n x = state\n # Formula :\n # yn = yn-1 + h * y'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the main method that process user input. This cause the FSM to change state and call an action. This method calls getTransition() to find the correct action and nextState associated with the inputSymbol and currentState. This method processes one complete input symbol. | def process (self, inputSymbol):
self.inputSymbol = inputSymbol
(self.action, self.nextState) = self.getTransition (self.inputSymbol, self.currentState)
if self.action is not None:
self.action (self)
self.memoryState.append(self.currentState)
... | [
"def input(self, symbol, *args, **kwargs):\n if self.__state is None:\n raise ValueError(\"FSM state is undefined\")\n try:\n transition = self.__get_state_attr(self._transition_prefix)\n except AttributeError:\n raise Exception(\"unable to find transition funct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup all of the IP addresses for a given AWS instance name. Multiple instances with the same name is a result of instances belonging to an auto scale group. Useful when an action needs to happen to all machines in an auto scale group. | def machine_lookup_all(session, hostname, public_ip = True):
client = session.client('ec2')
response = client.describe_instances(Filters=[{"Name":"tag:Name", "Values":[hostname]},
{"Name":"instance-state-name", "Values":["running"]}])
addresses = []
ite... | [
"def get_instances_by_name(client, instance_name):\n response = client.describe_instances()\n instances = []\n # response[\"Reservations\"][0][\"Instances\"][0][\"Tags\"]\n try:\n for r in response[\"Reservations\"]:\n for i in r[\"Instances\"]:\n for t in i[\"Tags\"]:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the public DNS for a given AWS RDS instance name. | def rds_lookup(session, hostname):
client = session.client('rds')
response = client.describe_db_instances(DBInstanceIdentifier=hostname)
item = response['DBInstances']
if len(item) == 0:
print("Could not find DNS for '{}'".format(hostname))
return None
else:
return item[0][... | [
"def instance_public_lookup(session, hostname):\n if session is None:\n return None\n\n client = session.client('ec2')\n response = client.describe_instances(\n Filters=[{\"Name\": \"tag:Name\", \"Values\": [hostname]},\n {\"Name\": \"instance-state-name\", \"Values\": [\"runn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Locate an item in a list based on a predicate function. | def _find(xs, predicate):
for x in xs:
if predicate(x):
return x
return None | [
"def find(l,func):\n for i,item in enumerate(l):\n if func(item):\n return i\n return -1",
"def finditem(func, seq):\n return next((item for item in seq if func(item)))",
"def first(a_list, predicate):\n for item in a_list:\n if predicate(item):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Terminate all of the instances for an ASG, with the given timeout between each termination. | def asg_restart(session, hostname, timeout, callback=None):
client = session.client('ec2')
resource = session.resource('ec2')
response = client.describe_instances(Filters=[{"Name":"tag:Name", "Values":[hostname]},
{"Name":"instance-state-name", "Values":["ru... | [
"def terminate(self):\n self.terminateDaskWorker()\n\n # Terminate any running dask scheduler\n self.terminateDaskScheduler()\n\n log.info(f\"Terminating instances: {self.__instances}\")\n\n ec2 = boto3.resource('ec2', region_name=self.region)\n\n responses = []\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Group name for the ASG creating the EC2 instances with the given hostname | def asg_name_lookup(session, hostname):
if session is None:
return None
client = session.client('autoscaling')
response = client.describe_auto_scaling_groups()
if len(response['AutoScalingGroups']) == 0:
return None
else:
# DP NOTE: Unfortunatly describe_auto_scaling_groups(... | [
"def host_group_name(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"host_group_name\")",
"def name(self):\n return self._nfvi_host_group.name",
"def instanceid_lookup(session, hostname):\n if session is None:\n return None\n\n client = session.client('ec2')\n response = cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Id for the VPC with the given domain name. | def vpc_id_lookup(session, vpc_domain):
if session is None:
return None
client = session.client('ec2')
response = client.describe_vpcs(Filters=[{"Name": "tag:Name", "Values": [vpc_domain]}])
if len(response['Vpcs']) == 0:
return None
else:
return response['Vpcs'][0]['VpcId'] | [
"def subnet_id_lookup(session, subnet_domain):\n if session is None:\n return None\n\n client = session.client('ec2')\n response = client.describe_subnets(Filters=[{\"Name\": \"tag:Name\", \"Values\": [subnet_domain]}])\n if len(response['Subnets']) == 0:\n return None\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Id for the Subnet with the given domain name. | def subnet_id_lookup(session, subnet_domain):
if session is None:
return None
client = session.client('ec2')
response = client.describe_subnets(Filters=[{"Name": "tag:Name", "Values": [subnet_domain]}])
if len(response['Subnets']) == 0:
return None
else:
return response['Sub... | [
"def get_subnet_id(self, sn_name):\n nw = self.get_subnets()\n for n in nw:\n if n['name'] == sn_name:\n return n['id']\n return None",
"def resolve_subnet_id(self, id_or_name):\n conn = self._get_vpc_conn()\n for subnet in conn.get_all_subnets():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Id for the AMI with the given name. If ami_name ends with '.boss', the AMI_VERSION environmental variable is used to either search for the latest commit hash tagged AMI ('.bossh') or for the AMI with the specific tag ('.boss'). | def ami_lookup(session, ami_name, version = None):
if session is None:
return None
specific = False
if ami_name.endswith(".boss"):
ami_version = os.environ["AMI_VERSION"] if version is None else version
if ami_version == "latest":
# limit latest searching to only version... | [
"def ami_lookup(bosslet_config, ami_name, version = None):\n specific = False\n if ami_name.endswith(bosslet_config.AMI_SUFFIX):\n ami_version = bosslet_config.ami_version if version is None else version\n if ami_version == \"latest\":\n # limit latest searching to only versions tagge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Ids for all of the VPC Security Groups. | def sg_lookup_all(session, vpc_id):
if session is None:
return NoneDict()
client = session.client('ec2')
response = client.describe_security_groups(Filters=[{"Name": "vpc-id", "Values": [vpc_id]}])
if len(response['SecurityGroups']) == 0:
return NoneDict()
else:
sgs = NoneD... | [
"def get_sg_ids(vpc):\n list = [i.id for i in vpc.security_groups.all()]\n return list",
"def security_group_ids(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:\n return pulumi.get(self, \"security_group_ids\")",
"def security_group_ids(self) -> Optional[Sequence[str]]:\n return pulumi.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Id for the VPC Security Group with the given name. | def sg_lookup(session, vpc_id, group_name):
if session is None:
return None
client = session.client('ec2')
response = client.describe_security_groups(Filters=[{"Name": "vpc-id", "Values": [vpc_id]},
{"Name": "tag:Name", "Values": [group_name]}... | [
"def get_sg_id(sg_name):\n print()\n print(\"Searching for SG ID\")\n client = boto3.client('ec2')\n all_sg = client.describe_security_groups()\n print(sg_name)\n grp_id = \"None\"\n for sec_grp in all_sg['SecurityGroups']:\n print(sec_grp['GroupName'])\n if sg_name == sec_grp['Gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Id for the VPC Route Table with the given name. | def rt_lookup(session, vpc_id, rt_name):
if session is None:
return None
client = session.client('ec2')
response = client.describe_route_tables(Filters=[{"Name": "vpc-id", "Values": [vpc_id]},
{"Name": "tag:Name", "Values": [rt_name]}])
if l... | [
"def route_table_id(self) -> str:\n return pulumi.get(self, \"route_table_id\")",
"def transit_route_table_id(self) -> str:\n return pulumi.get(self, \"transit_route_table_id\")",
"def transit_router_route_table_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"transit_ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name the default Route Table that is created for a new VPC. Find the default VPC Route Table and give it a name so that it can be referenced latter. Needed because by default the Route Table does not have a name and rt_lookup() will not find it. The default VPC Route Table is determined as the first Route Table without... | def rt_name_default(session, vpc_id, new_rt_name):
client = session.client('ec2')
response = client.describe_route_tables(Filters=[{"Name": "vpc-id", "Values": [vpc_id]}])
rt_id = None
for rt in response['RouteTables']:
nt = _find(rt['Tags'], lambda x: x['Key'] == 'Name')
if nt is None ... | [
"def create_route_table(stack, env, name):\n\n return stack.stack.add_resource(\n RouteTable(\n '{0}{1}RouteTable'.format(env, name),\n VpcId=Ref(stack.vpc),\n Tags=[\n {\n 'Key': 'Name',\n 'Value': '{0}{1}'.format(env, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the names of valid Key Pair. If the SSH_KEY enviro variable is defined and points to a valid keypair, that keypair name is returned. Else all of the keypairs are printed to stdout and the user is prompted to select which keypair to use. | def keypair_lookup(session):
if session is None:
return None
client = session.client('ec2')
response = client.describe_key_pairs()
# If SSH_KEY exists and points to a valid Key Pair, use it
key = os.environ.get("SSH_KEY", None) # reuse bastion.py env vars
if key is not None:
k... | [
"def check_key_pair(ec2, kp_name):\n if not [i for i in ec2.get_all_key_pairs() if str(i).split(':')[1] == kp_name]:\n sys.stderr.write(\"Key pair: {} does not exist, please import_key_pair prior to running.\\n\".format(kp_name))\n sys.exit(1)",
"def key_default_name(self):\n\n def ask_key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look up instance id by hostname (instance name). | def instanceid_lookup(session, hostname):
if session is None:
return None
client = session.client('ec2')
response = client.describe_instances(
Filters=[{"Name": "tag:Name", "Values": [hostname]}])
item = response['Reservations']
if len(item) == 0:
return None
else:
... | [
"def get_instance_id(self) -> str:\n import socket\n\n hostname = socket.gethostname()\n session = self.session.client(\"ec2\")\n for reservation in session.describe_instances()[\"Reservations\"]:\n for instance in reservation[\"Instances\"]:\n if instance[\"Pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looks up the ARN for a SSL Certificate | def cert_arn_lookup(session, domain_name):
if session is None:
return None
client = session.client('acm')
response = client.list_certificates()
for certs in response['CertificateSummaryList']:
if certs['DomainName'] == domain_name:
return certs['CertificateArn']
if c... | [
"def get_ssl_certificate_arn(environment):\n name = Constants['SslCertificateName'][environment]\n\n certificates = ACM.list_certificates(CertificateStatuses=[ 'ISSUED' ])['CertificateSummaryList']\n arns = [ c['CertificateArn'] for c in certificates if c['DomainName'] == name ]\n\n if len(arns) == 0:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Public DNS name for a EC2 instance | def instance_public_lookup(session, hostname):
if session is None:
return None
client = session.client('ec2')
response = client.describe_instances(
Filters=[{"Name": "tag:Name", "Values": [hostname]},
{"Name": "instance-state-name", "Values": ["running"]}])
item = resp... | [
"def compose_public_dns_name(instance):\n ip = '-'.join(instance.public_ip_address.split('.'))\n # Exclude zone identifier from availability zone for region\n region = instance.placement['AvailabilityZone'][:-1]\n subdomain = \"compute.amazonaws.com\"\n return \"ec2-{ip}.{region}.{subdomain}\".format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup cloudfront public domain name which has hostname as the origin. | def cloudfront_public_lookup(session, hostname):
if session is None:
return None
client = session.client('cloudfront')
response = client.list_distributions(
MaxItems='100'
)
items = response["DistributionList"]["Items"]
for item in items:
cloud_front_domain_name = item["... | [
"def get_domain():\n domain=\"\"\n for item in re.split(\"\\.\", env.host)[1:]:\n domain = domain + \".\" + item\n return domain.lstrip(\".\")",
"def _parse_domainname():\n return _parse_resolve().get(\"domain\", \"\")",
"def _getHostname(fqdn):\n\treturn fqdn.split('.')[0]",
"def dns_domai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup the Public DNS name for a ELB | def elb_public_lookup(session, hostname):
if session is None:
return None
client = session.client('elb')
responses = client.describe_load_balancers()
hostname_ = hostname.replace(".", "-")
for response in responses["LoadBalancerDescriptions"]:
if response["LoadBalancerName"].star... | [
"def elb_public_lookup(session, hostname):\n\n if session is None:\n return None\n\n hostname_ = hostname.replace(\".\", \"-\")\n\n client = session.client('elb')\n responses = client.describe_load_balancers()\n for response in responses[\"LoadBalancerDescriptions\"]:\n if response[\"Lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup up SNS topic ARN given a topic name | def sns_topic_lookup(session, topic_name):
if session is None:
return None
client = session.client('sns')
response = client.list_topics()
topics_list = response['Topics']
for topic in topics_list:
arn_topic_name = topic["TopicArn"].split(':').pop()
if arn_topic_name == topic... | [
"def build_topic_arn(topic_name):\n # https://stackoverflow.com/a/37723278/1558022\n sts_client = boto3.client('sts')\n account_id = sts_client.get_caller_identity().get('Account')\n\n return f'arn:aws:sns:eu-west-1:{account_id}:{topic_name}'",
"def get_full_topicarn ( base_topicarn, topicname ) :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete all of the SQS Queues that start with the given domain name | def sqs_delete_all(session, domain):
client = session.client('sqs')
resp = client.list_queues(QueueNamePrefix=domain.replace('.','-'))
for url in resp.get('QueueUrls', []):
client.delete_queue(QueueUrl=url) | [
"def clean_test_queues(prefix=TEST_NAME_PREFIX, region_name=None):\n sqs = boto3.resource('sqs', region_name=region_name)\n num_queues = 0\n try:\n for queue in sqs.queues.all():\n if re.match(r'.+%s\\d+' % TEST_NAME_PREFIX, queue.url):\n queue.delete()\n num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup up SQS url given a name. | def sqs_lookup_url(session, queue_name):
client = session.client('sqs')
resp = client.get_queue_url(QueueName=queue_name)
return resp['QueueUrl'] | [
"def get_bucket_url(self, bucket_name):\n return \"http://{}.{}\".format(\n bucket_name,\n util.get_endpoint(self.get_bucket_location(bucket_name)).host\n )",
"def _find_url_name(self, index_url, url_name, req):\r\n if not index_url.url.endswith('/'):\r\n # Va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Requests a certificate in the AWS Certificate Manager for the domain name | def request_cert(session, domain_name, validation_domain):
if session is None:
return None
client = session.client('acm')
validation_options = [
{
'DomainName': domain_name,
'ValidationDomain': validation_domain
},
]
response = client.request_certific... | [
"def request(domain):\n if not domain:\n logger.error(\n \"ctl:info:generate\", \"Choose a fully-qualified domain name of the \"\n \"certificate. Must match a domain present on the system\"\n )\n domain = click.prompt(\"Domain name\")\n try:\n client().certifi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get hosted zone by looking up account name and using that to tell which zone to return. | def get_hosted_zone(session):
account = get_account_id_from_session(session)
if account == hosts.PROD_ACCOUNT:
return hosts.PROD_DOMAIN
elif account == hosts.DEV_ACCOUNT:
return hosts.DEV_DOMAIN
else:
return None | [
"def ex_get_zone(self, name):\n if name.startswith('https://'):\n short_name = name.split('/')[-1]\n request = name\n else:\n short_name = name\n request = '/zones/%s' % name\n # Check zone cache first\n if short_name in self.zone_dict:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates or Creates a domain name with FQDN resource. | def set_domain_to_dns_name(session, domain_name, dns_resource, hosted_zone):
if session is None:
return None
client = session.client('route53')
hosted_zone_id = get_hosted_zone_id(session, hosted_zone)
if hosted_zone_id is None:
print("Error: Unable to find Route 53 Hosted Zone, " + ho... | [
"def create_domain(self):\n url = '{}/domains/'.format(API_ENDPOINT)\n r1 = requests.get(url + self.domain, headers=self.headers)\n\n if r1.status_code == 200:\n msg = 'Warning: Domain \"{}\" already exists. Continue anyways? (Y/n) '\n cont = raw_input(msg.format(self.doma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete all of the matching CNAME records from a DNS Zone | def route53_delete_records(session, hosted_zone, cname):
if session is None:
return None
client = session.client('route53')
hosted_zone_id = get_hosted_zone_id(session, hosted_zone)
if hosted_zone_id is None:
print("Could not locate Route53 Hosted Zone '{}'".format(hosted_zone))
... | [
"def delete_cname(\n cname_domain: str, aws_access_key_id: str, aws_secret_access_key: str\n) -> None:\n logger = get_logger(__name__)\n logger.info(\"delete_cname\", cname_domain=cname_domain)\n\n if not cname_domain.endswith(\".\"):\n cname_domain = cname_domain + \".\"\n\n session = boto3.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unsubscribe all subscriptions for the given SNS topic | def sns_unsubscribe_all(session, topic, region="us-east-1", account=None):
if session is None:
return None
if account is None:
account = get_account_id_from_session(session)
topic = "arn:aws:sns:{}:{}:{}".format(region, account, topic.replace(".", "-"))
client = session.client('sns')
... | [
"def sns_unsubscribe_all(bosslet_config, topic):\n session = bosslet_config.session\n region = bosslet_config.REGION\n account = bosslet_config.ACCOUNT_ID\n topic = \"arn:aws:sns:{}:{}:{}\".format(region, account, topic.replace(\".\", \"-\"))\n\n client = session.client('sns')\n response = client.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete all of the IAM policies that start with the given domain name | def policy_delete_all(session, domain, path="/"):
client = session.client('iam')
resp = client.list_policies(Scope='Local', PathPrefix=path)
prefix = domain.replace('.', '-')
for policy in resp.get('Policies', []):
if policy['PolicyName'].startswith(prefix):
ARN = policy['Arn']
... | [
"def destroy_all(self):\n for name in self.app.config['SIMPLE_DOMAINS']:\n self.connection.delete_domain(name)",
"def delete_all_from_target(self):\n\n self._logger.info(\"Deleting policies...\")\n\n policies = self._api_target.policies.list_all()\n\n for policy in policies:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the account id from the session using the iam client. This method will work even if you have assumed a role in another account. | def get_account_id_from_session(session):
if session is None:
return None
return session.client('iam').list_users(MaxItems=1)["Users"][0]["Arn"].split(':')[4] | [
"def account_id():\n return client.get_caller_identity()['Account']",
"def account_id(self) -> str:\n return self[\"requestContext\"][\"accountId\"]",
"def account_id(self) -> str:\n return pulumi.get(self, \"account_id\")",
"def get_client_id(account):\n return get_oauth_credentials(accou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the arn for a lambda given a lambda function name. | def lambda_arn_lookup(session, lambda_name):
if session is None:
return None
client = session.client("lambda")
response = client.get_function(FunctionName=lambda_name)
if response is None:
return None
else:
return response['Configuration']['FunctionArn'] | [
"def lambda_arn(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"lambda_arn\")",
"def lambda_function_arn(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"lambda_function_arn\")",
"def get_lambda_arn(region: str, first_part: str, second_part: str=None) -> str:\n client =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use SHA1 hash to hash a string, convert it to integer and shift right (160 m) places | def chord_hash(input_string):
h = hashlib.sha1() # 160 bit string
encoded_data = input_string.encode('utf-8')
h.update(encoded_data)
hex_string = h.hexdigest()
hex_value = int(hex_string, 16)
hash_integer_value = hex_value >> (160 - m)
return hash_integer_value | [
"def calculate_hash_value(self, string):\n return (ord(string[0]) * 100) + ord(string[1])",
"def sha1(self, s):\n\t\tself.sha1_calls += 1\n\t\treturn int(hashlib.sha1(s).hexdigest(), 16)",
"def hash_string(string):\n res = hashlib.md5(string.encode(encoding='UTF-8'))\n bigint_max = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a given value is in the range start to end while considering given options, i.e., including/excluding start and/or end of the range. | def is_between(value, start, end, including_start=False, including_end=False):
if not including_start and not including_end: # not include both start and end
if (start < value < end):
return True
elif (start > end) and (start < value <= (2**m - 1) or 0 <= value < end):
retu... | [
"def in_range(start, end, x):\n if start <= end:\n return start <= x <= end\n else:\n return start <= x or x <= end",
"def in_interval(start: int, end: int, addr: int):\n if end < start:\n return addr > start or addr < end\n else:\n return addr > start and addr < end",
"def check_ran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove a connection from a node, by the id of the other node in the connection | def remove_connection_by_id(self, node_id: int):
for conn in self.get_connections():
if conn.other.node_id == node_id:
self.remove_connection(conn)
break | [
"def remove_connection(self, source, target):\r\n\r\n connection = (self.coalesce_node(source), self.coalesce_node(target))\r\n self.connections.discard(connection)",
"def remove_node(self, id):\r\n\t\tif id in self._nodes:\r\n\t\t\tnode = self._nodes[id]\r\n\t\t\tedges = node.edges()\r\n\t\t\t# ugl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate key using random bytes with specified size. | def generate_key(self, size):
key = bytearray()
for i in range(0,size):
random_byte = ord(os.urandom(1))
key.append(random_byte)
return key | [
"def generate_key(size=20):\n return urandom(size)",
"def get_random_key(key_len: int = 16) -> bytes:\n return bytes(random.randint(0, 255) for _ in range(key_len))",
"def Generate(size=keyinfo.HMAC_SHA1.default_size):\n key_bytes = util.RandBytes(size / 8)\n key_string = util.Encode(key_bytes)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'Encrypt' the password with the key. Reverse key bytes and XOR with password bytes. Very low security but a bit obfuscated. | def mix_keys(self, password, key):
rev_key = list(reversed(key)) # Reverse bytes
result = bytearray()
for i in range(0, len(password)):
xored = password[i] ^ rev_key[i] # Mix each byte
result.append(xored)
return result | [
"def encrypt(self, password, key):\n\t\tPADDING = self._extract_key(key)[0]\n\t\tsecret = self._extract_key(key)[1]\n\t\t\n\t\tcipher = AES.new(secret)\n\n\t\tpasword_to_encrypt = password + (self.BLOCK_SIZE - len(password) % self.BLOCK_SIZE) * PADDING\n\t\tencrypted_password = base64.b64encode(cipher.encrypt(paswo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the peak in the specified time range. Finds the peak in the data in the specified time range. You must pass it pretrigger and timebase as well as the time and data series. timebase is an integer equal to (1 us)/(delta t of the digitizer). For example, if capturing data at 10 MHz, timebase = (1e6/1e7) = 10. For da... | def polyPeak_noPlot(time, data, timerange = [40,80],axis = 'x'):
# Find the indices corresponding to the ends of the time range
t1 = mj.tindex(time,timerange[0])#+pretrigger)
t2 = mj.tindex(time,timerange[1])#+pretrigger)
# print 't1=', t1
# print 't2=', t2
# generate an array of indices spanni... | [
"def polyPeak(time, data, timerange = [40,80],pretrigger=20):\n\n # Find the indices corresponding to the ends of the time range\n t1 = ssxf.tindex_min(time,timerange[0]+pretrigger)\n t2 = ssxf.tindex_min(time,timerange[1]+pretrigger)\n #print t1\n #print t2\n # generate an array of indices spanni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides positions in meters along probe stalks for 4x4 array of probes built by M. Kaur. | def get_probeLocs_calib_setup(dir, num_probes = 16):
position_vectors = [[0] * 3 for i in range(num_probes)]
#every x postion
# Convert to meters
x_pos = [-4.25*1e-3*25.4, -4.25*1e-3*25.4, 4.24*1e-3*25.4, 4.24*1e-3*25.4]
y_pos = [-4.25*1e-3*25.4, 4.24*1e-3*25.4, 4.24*1e-3*25.4, -4.25*1e-3*25.4]
... | [
"def get_probeLocs_calib_setup_cm(dir, num_probes = 16):\n position_vectors = [[0] * 3 for i in range(num_probes)]\n\n #every x postion\n\n # Convert to meters\n x_pos = [-4.25*2.54, -4.25*2.54, 4.24*2.54, 4.24*2.54]\n y_pos = [-4.25*2.54, 4.24*2.54, 4.24*2.54, -4.25*2.54]\n z_pos = [-2.25*2.54, -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides positions in meters along probe stalks for 4x4 array of probes built by M. Kaur. | def get_probeLocs_calib_setup_cm(dir, num_probes = 16):
position_vectors = [[0] * 3 for i in range(num_probes)]
#every x postion
# Convert to meters
x_pos = [-4.25*2.54, -4.25*2.54, 4.24*2.54, 4.24*2.54]
y_pos = [-4.25*2.54, 4.24*2.54, 4.24*2.54, -4.25*2.54]
z_pos = [-2.25*2.54, -0.75*2.54, 0.... | [
"def get_probeLocs_calib_setup(dir, num_probes = 16):\n position_vectors = [[0] * 3 for i in range(num_probes)]\n\n #every x postion\n\n # Convert to meters\n x_pos = [-4.25*1e-3*25.4, -4.25*1e-3*25.4, 4.24*1e-3*25.4, 4.24*1e-3*25.4]\n y_pos = [-4.25*1e-3*25.4, 4.24*1e-3*25.4, 4.24*1e-3*25.4, -4.25*1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This finds the ratio between the idealized helmholtz field and the actual recoreded signal This also corrects for inverted signals... however due to what I'm assuming is noise, finding the inverted ones are a bit tricky feel free to uncomment the plotting lines and see if it needs adjusments, though I did get it workin... | def ratio_4_doc(shot, dir, num_probes = 16):
# data = [[0] *3 for i in range(num_probes)]
# magdata = hdr.getMagData(shot)
probe_locs = get_probeLocs_calib_setup(shot)
data=hdr.getquikData(shot)
time,eastcurrent,westcurrent = loadcurrent(shot)#using eastcurrent
ratios = [[0]*3 for i in range(num... | [
"def get_signal2noise_ratio(self) -> float:",
"def det_ratio_index(self):\n if(self.det_WG <= 0 or self.det_T <= 0):\n print(\"replacing with insignificant\")\n return self.insignificant\n else:\n return self.det_T/self.det_WG",
"def test_none_noise_with_mag(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the .mat filenames for the troika dataset. Review the README in ./datasets/troika/ to understand the organization of the .mat files. | def LoadTroikaDataset():
data_dir = "./datasets/troika/training_data"
data_fls = sorted(glob.glob(data_dir + "/DATA_*.mat"))
ref_fls = sorted(glob.glob(data_dir + "/REF_*.mat"))
return data_fls, ref_fls | [
"def load_mat_data():\n filenames = glob.glob('%s/changjie/MAT_DATA/*.mat' % os.environ['DATA'])\n tier1_filenames = filter(tier1_test, filenames)\n data_list = [load_file(filename) for filename in tier1_filenames]\n data_list = [df for df in data_list if df is not None]\n all_site_data = pd.concat(data_list)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toplevel function evaluation function. Runs the pulse rate algorithm on the Troika dataset and returns an aggregate error metric. | def Evaluate():
global reg
reg = ModelRegression()
# Retrieve dataset files
data_fls, ref_fls = LoadTroikaDataset()
errs, confs = [], []
for data_fl, ref_fl in zip(data_fls, ref_fls):
# Run the pulse rate algorithm on each trial in the dataset
errors, confidence = RunPulseRa... | [
"def Evaluate():\n # Retrieve dataset files\n data_fls, ref_fls = LoadTroikaDataset()\n errs, confs = [], []\n for data_fl, ref_fl in zip(data_fls, ref_fls):\n # Run the pulse rate algorithm on each trial in the dataset\n errors, confidence = RunPulseRateAlgorithm(data_fl, ref_fl)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the string representation of a tagged token, return the corresponding tuple representation. The rightmost occurence of C{sep} in C{s} will be used to divide C{s} into a word string and a tag string. If C{sep} does not occur in C{s}, return C{(s, None)}. | def str2tuple(s, sep='/'):
loc = s.rfind(sep)
if loc >= 0:
return (s[:loc], s[loc+1:].upper())
else:
return (s, None) | [
"def tuple2str(tagged_token, sep='/'):\n word, tag = tagged_token\n if tag is None:\n return word\n else:\n assert sep not in tag, 'tag may not contain sep!'\n return '%s%s%s' % (word, sep, tag)",
"def parsePipeSeparatedTuple(str):\n tokens = str.split(TUPLE_SPLIT_STRING)\n second ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the tuple representation of a tagged token, return the corresponding string representation. This representation is formed by concatenating the token's word string, followed by the separator, followed by the token's tag. (If the tag is None, then just return the bare word string.) | def tuple2str(tagged_token, sep='/'):
word, tag = tagged_token
if tag is None:
return word
else:
assert sep not in tag, 'tag may not contain sep!'
return '%s%s%s' % (word, sep, tag) | [
"def tuple_to_string(letter_word_pair):\n letter, word = letter_word_pair\n return '{letter}: {word}'.format(letter=letter, word=word)",
"def tagify(x):\n\t\tm = tag_match.match(x)\n\t\tif m:\n\t\t\tg = m.groups()\n\n\t\t\tword = (g[0] if g[0] is not None else \"NA\")\n\t\t\ttag = (g[1] if g[1] is ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a tagged sentence, return an untagged version of that sentence. I.e., return a list containing the first element of each tuple in C{tagged_sentence}. >>> untag([('John', 'NNP'), ('saw', 'VBD'), ('Mary', 'NNP')] ['John', 'saw', 'mary'] | def untag(tagged_sentence):
return [w for (w, t) in tagged_sentence] | [
"def untag(self, tag, *items):\r\n return self.backend.untag_items(tag, *items)",
"def tag_unigram(self, untagged_string: str):\n untagged_tokens = wordpunct_tokenize(untagged_string)\n tagger = self._load_model(\"unigram\")\n tagged_text = tagger.tag(untagged_tokens)\n return t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select only rows representing extended sources from a catalog table | def select_extended(cat_table):
try:
l = [len(row.strip()) > 0 for row in cat_table['Extended_Source_Name'].data]
return np.array(l, bool)
except KeyError:
return cat_table['Extended'] | [
"def select_sources(cat_table, cuts):\n nsrc = len(cat_table)\n full_mask = np.ones((nsrc), bool)\n for cut in cuts:\n if cut == 'mask_extended':\n full_mask *= mask_extended(cat_table)\n elif cut == 'select_extended':\n full_mask *= select_extended(cat_table)\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select only rows passing a set of cuts from catalog table | def select_sources(cat_table, cuts):
nsrc = len(cat_table)
full_mask = np.ones((nsrc), bool)
for cut in cuts:
if cut == 'mask_extended':
full_mask *= mask_extended(cat_table)
elif cut == 'select_extended':
full_mask *= select_extended(cat_table)
else:
... | [
"def filter_catalog(catalog, row):\n filtered_catalog = catalog[\n (catalog.Lm_OPQ > row.L) & \n (catalog.Lm_OPQ < row.L + dL)\n ]\n filtered_catalog = filtered_catalog[\n (filtered_catalog.MLT_OPQ > ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the yaml file for a particular split key | def read_catalog_info_yaml(self, splitkey):
catalog_info_yaml = self._name_factory.catalog_split_yaml(sourcekey=splitkey,
fullpath=True)
yaml_dict = yaml.safe_load(open(catalog_info_yaml))
# resolve env vars
yaml_dict['cat... | [
"def load(key, path='farmboy.yaml'):\n try:\n doc = yaml.load(open(path))\n return doc.get(key, None)\n except IOError:\n # log.warn('No file found at %s' % path)\n return None",
"def read_yaml(file):\n lines = file.open().read().splitlines()\n if '---' in lines[:2]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a CatalogInfo object | def build_catalog_info(self, catalog_info):
cat = SourceFactory.build_catalog(**catalog_info)
catalog_info['catalog'] = cat
# catalog_info['catalog_table'] =
# Table.read(catalog_info['catalog_file'])
catalog_info['catalog_table'] = cat.table
catalog_info['roi_model'] ... | [
"def build_catalog(self):\n print('building catalog off of existing translations in PO file...')\n po_path = os.path.join(self.translations_path, self.language, 'LC_MESSAGES', self.translations_key + '.po')\n try:\n file = open(po_path, 'r+')\n except IOError as e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of full catalogs used | def catalogs(self):
return sorted(self._catalog_comp_info_dicts.keys()) | [
"def getCatalogs(self):\n return self.getCatalog(None)",
"def get_catalogs(self):\n rs = self.c.OpenSchema(1)\n return [record['CATALOG_NAME'] for record in _extract_recordset(rs)]",
"def catalogList( self ):\n return self.__data__[\"Catalog\"].split( \",\" )",
"def get(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of catalog split keys used | def splitkeys(self):
return sorted(self._split_comp_info_dicts.keys()) | [
"def catalogList( self ):\n return self.__data__[\"Catalog\"].split( \",\" )",
"def get_keys(self):\r\n\r\n #using database\r\n\r\n if self.using_database:\r\n aprint('GET KEYS')\r\n value_tuple = (notebookname,)\r\n db_cursor.execute(\"SELECT keyword\"\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the info for a particular split key | def split_comp_info(self, catalog_name, split_ver, split_key):
return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key] | [
"def getsplitinfo():\n \n splitvarlist = spss.GetSplitVariableNames()\n if len(splitvarlist) == 0:\n return [], None\n else:\n splittype = spssaux.getShow(\"split\", olang=\"english\")\n if splittype.lower().startswith(\"layer\"):\n splittype=\"layered\"\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores the given model. | def store_model(self, user_name, model_name, model):
print(f"sto {user_name}\n{model_name}\n{serialize(model)}")
return self.dao.store_serialized_model(user_name, model_name, serialize(model)) | [
"def save_model(self, model):\n raise NotImplementedError",
"def save_model(self):\n pass",
"def persist_model(self, model, trade_window):\n object_path = 'model_objects/'\n file_name = f'market_maker_model_{self.target_coin}_{trade_window}.pkl'\n self.s3_client.put_object(Buc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores the given model in redis. | def store_serialized_model(self, user_name, model_name, serialized_model):
try:
self.rconn.set(redis_keys.for_model(user_name, model_name), json.dumps(serialized_model))
return True
except redis.RedisError as e:
return False | [
"def save(self):\n Base._redis.sadd(self.name, self.ident)\n Base._redis.set(self.redis_key, self.object_id)\n for attr, value in self.__dict__.iteritems():\n key = self.make_key(self.redis_key, attr)\n Base._redis.set(key, value)",
"def save(self):\n self.redis_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the timestamps and sort them to permit simple concurrency tests. | def read_timestamps(self, tasks):
from reframe.core.deferrable import evaluate
self.begin_stamps = []
self.end_stamps = []
for t in tasks:
with open(evaluate(t.check.stdout), 'r') as f:
self.begin_stamps.append(float(f.readline().strip()))
sel... | [
"def test_sort_data_by_time():\n data = race.read_file_to_list()\n sorted_data = race.sort_data_by_time(data)\n assert data != sorted_data\n assert len(data) == len(sorted_data)\n assert type(sorted_data) == list\n for lines in sorted_data:\n assert type(lines) == dict",
"def sort_time(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a vao if the instance has a shape where we did not create an vao yet | def update_shape_vaos(self, instance, show):
shape = self._shape(instance)
shape_object_id = id(shape)
if not shape_object_id in self._shape_vaos:
self._shape_vaos[shape_object_id] = VertexArray({
'vertex_position': VertexBuffer.from_numpy(shape.verticies),
... | [
"def get_vao_of_shape(self, shape):\n\n vertices, indices, colors = shape.unpack()\n ibo = self._ctx.buffer(np.array(indices).astype('i4').tobytes())\n vbo = self._ctx.buffer(np.array(vertices).astype('f4').tobytes())\n cbo = self._ctx.buffer(np.array(colors).astype('f4').tobytes())\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
renders a texture containing the borders of all shapes. | def _render_borders(self):
# XXX
# - read the old glBlendFunc value and restore it if neccessary.
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
self.border_program.use()
for shape_object_id, instances in self._instances.items():
self._shape_vaos[shape_object_id]... | [
"def render( self, screen, dest ):\n # We're gonna draw a decorative border to surround the provided area.\n # Step one: Determine the size of our box. Both dimensions should be \n # a multiple of TEX_WIDTH. \n\n if self.border == None:\n self.border = image.Image( self.border... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy the score to the NN after each tick. | def update(self, game):
super().update(game)
self.nn_def.set_score(self.score) | [
"def update_score():\n pass",
"def update_score(self):\n self.score = TurboMQ.calculate_fitness(self.result, self.graph)",
"def score(self, score):\n\n self._score = score",
"def reset_score(self):\r\n self.score = 0\r\n self.__counter = 0",
"def increment_score(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |