query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
If full house (triple and double), return the sum of all dice
def _score_full_house(dice): # Test for full house if _score_yacht(dice) == 50: return 0 # The list is sorted. So there will be a full house if either # - the pair is at the start of the list, and dice[0]==dice[1] and # the triple is at the end of the list, and dice[2]==dice[4] # - t...
[ "def full_house(dice):\n\n counts = dice_counts(dice)\n if 2 in counts.values() and 3 in counts.values():\n return sum(dice)\n return 0", "def large_straight(dice):\n if sorted(dice) == [2, 3, 4, 5, 6]:\n return sum(dice)\n else:\n return 0", "def small_straight(dice):\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If 4 of a kind, return the sum of those 4
def _score_four_of_a_kind(dice): # The list is sorted. So there will be 4 of a kind if either # - the 4 of a kind is at the start of the list, and dice[0]==dice[3] # - the 4 of a kind is at the end of the list, and dice[1]==dice[4] if dice[0] == dice[3]: return 4 * dice[0] elif dice[1] == ...
[ "def testSum(self):\n f4 = self.f4\n self.assertTrue(f4(0, 1) + f4(1, 0) == f4(1, 1))", "def check_sum_of_four(a: List[int], b: List[int], c: List[int], d: List[int]) -> int:\n zero_counter = 0\n for var in itertools.product(a, b, c, d):\n if sum(var) == 0:\n zero_counter += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the reports' pages links
def get_reports_links(self): html = self.get_page_html(self.principal_url) table_links = html.find("table").findAll('a') report_links = [] for link in table_links: month_year = link.text if "UNSPECIFIED" in month_year: break year = m...
[ "def _wikipedia_Page_linkedPages(self):\n return [page for page in toolserver.Generators.getPagelinks(self)]", "def get_all_links_pages(total_pages):\n\tbase_url = 'http://torrentik.co'\n\tpage_part = '/page/'\n\tlinks_pages = []\n\tfor i in range(1, 2): # int(total_pages) + 1\n\t\turl = base_url + page_part +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a list of subject classifications associated with ScienceDirect content. Returns a list of subject classifications
def get_classifications() -> list: file = urlopen( 'https://api.elsevier.com/content/subject/scopus?httpAccept=text/xml') data = file.read() file.close() data = xmltodict.parse(data)['subject-classifications'] data = data['subject-classification'] return list(set([x['@abbrev'] ...
[ "def get_subjects(survey, content_type, desired_facts=None, value=None):\n facts = _get_facts(survey, content_type=content_type, \n desired_facts=desired_facts, value=value)\n subject_ids = _get_subject_ids_for_facts(facts)\n return content_type.model_class().objects.filter(pk__in=subject_ids)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
opens a file containing api keys and returns the specific key requested
def get_key(file='api_key.dict', key='ElsevierDeveloper'): return eval(open(file, 'r').read())[key]
[ "def get_api_key():\n\twith open('key.txt', 'r') as file:\n\t\tapi_key = file.readline()\n\n\treturn api_key", "def get_api_key(filename):\n api_key_file = open(filename, 'r')\n return api_key_file.read().rstrip()", "def get_api_key(self):\n key_data = os.path.join(os.path.dirname(os.path.dirname\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks at the total number of entities found and calculates the number of batches
def get_num_batches(self, num_entities) -> int: if (num_entities % self.batch_size) is not 0: num_batches = int(num_entities / self.batch_size) + 1 else: num_batches = int(num_entities / self.batch_size) return num_batches
[ "def num_entities(self) -> int:\n # TODO: Need to add functions in pymilvus-distributed\n return 0\n # raise NotImplementedError", "def get_num_batches(self, dataset: Dataset) -> int:\n raise NotImplementedError", "def get_num_batches(self, batch_size):\n\n return len(self) //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieves all entities associated with a give search term in a given year
def retrieve_all_in_year(self, term, year): results_year = list() batch_start = 0 search_results = self.search_by_term(term, start=batch_start, date=year) expected_num_of_ent = int(search_results["opensearch:totalResults"]) if self.status_code is not 200 or expected_num_of_ent i...
[ "def retrieve_all_in_year(self, term, year) -> list:\n results_year = list()\n batch_start = 0\n\n # test the connection to the servers and determine the number of\n # entities to expect for the given search parameters.\n search_results = self.search_by_term(term, start=batch_star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes the corpus builder initialised with the search terms and dates then iterates over each term for each year, saving the data in files by each year in a folder for each term. Returns NONE builds a pickled database of the data returned.
def build_corpus(self): logging.info('Start') make_folder(self.file_path) self.gen_info_file() for term in self.search_terms: term_path = os.path.join(self.file_path, term) make_folder(term_path) logging.info("searching for %s" % term) f...
[ "def build_corpus(self,\n search_terms=None,\n dates=(1900, datetime.today().year)) -> str:\n logging.info('Start building corpus')\n\n if search_terms is None:\n search_terms = []\n\n if len(search_terms) is 0:\n logging.error(\"No ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return pehashng for PE file, sha256 of PE structural properties.
def pehashng(pe_file): if isinstance(pe_file, PE): exe = pe_file else: try: exe = PE(pe_file, fast_load=True) except PEFormatError as exc: logging.error("Exception in pefile.PE('%s') - %s", pe_file, exc) return def align_down_p2(number...
[ "def get_hash(self):\r\n path = self.files[self.idx_image]\r\n filename = path.split(\"/\")[-1]\r\n with open(path,\"rb\") as f:\r\n hash_object = hashlib.sha512(f.read())\r\n hex_dig = hash_object.hexdigest()\r\n hash = filename + \" \"+ hex_dig\r\n return h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should get all valid subscribers, when requested by an authenticated admin.
def test_getting_all_subscribers(self): response = self.app.get( "/api/1.0/subscribers/", headers={ 'User': self.admin_id, 'Authorization': self.valid_tokens[2] } ) data = json.loads(response.data.decode()) self.assertE...
[ "def test_admin_subscriber_view_list(self):\n response = self.client.get('/admin/dialer_campaign/subscriber/')\n self.failUnlessEqual(response.status_code, 200)", "def test_admin_view_subscribers(self):\n\n self.client.login(\n email=\"superuser@testing.com\", password=\"superusert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get VSGs by page and count, limit the result using filter, sort and projection
def get(self, page=0, count=0, projection=None, filter=None, sort=None): return super(VolumeSecurityGroupAPI, self).get(page=page, count=count, projection=projection, filter=filter, sort=sort)
[ "def page(self):\n limit = self.get_limit()\n offset = self.get_offset()\n count = self.get_count()\n objects = self.get_slice(limit, offset)\n meta = {\n 'offset': offset,\n 'limit': limit,\n 'total_count': count,\n }\n\n if limit an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create empty Deque class.
def dq(): from deque import Deque return Deque()
[ "def new_empty_q():\n from queue_ds import Queue\n this_empty_q = Queue()\n return this_empty_q", "def test_deque_constructor_with_empty_iterable():\n from deque import Deque\n d = Deque([])\n assert d.end is None\n assert d.front is None\n assert d._values.length == 0", "def test_empty_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create instance of heap with two values.
def heap_2(): from binheap import Heap test_heap = Heap([7, 49]) return test_heap
[ "def heapify(self, values):\n return map(self.push, values)", "def _heap_children(self, heap, i):\n l = 2 * i\n r = 2 * i + 1\n if l >= len(heap):\n return tuple()\n elif r >= len(heap):\n return (heap[l],)\n else:\n return (heap[l], heap[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create priq with one value and no priority.
def priq_1(): from priorityq import PriQ new_priq = PriQ() new_priq.insert(7) return new_priq
[ "def priq_pri_1():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7, 1)\n return new_priq", "def priq_2_same():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7, 1)\n new_priq.insert(10, 2)\n new_priq.insert(14, 2)\n return new_priq", "def te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create priq with one value and a priority of one.
def priq_pri_1(): from priorityq import PriQ new_priq = PriQ() new_priq.insert(7, 1) return new_priq
[ "def priq_1():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7)\n return new_priq", "def priq_2_same():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7, 1)\n new_priq.insert(10, 2)\n new_priq.insert(14, 2)\n return new_priq", "def test_pq_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create priq with 2 priorities. One has two values.
def priq_2_same(): from priorityq import PriQ new_priq = PriQ() new_priq.insert(7, 1) new_priq.insert(10, 2) new_priq.insert(14, 2) return new_priq
[ "def priq_pri_1():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7, 1)\n return new_priq", "def priq_1():\n from priorityq import PriQ\n new_priq = PriQ()\n new_priq.insert(7)\n return new_priq", "def get_rand_p_and_q(primes):\n p = primes[random.randrange(1, len(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create graph with three nodes.
def graph_3(): from graph import Graph new_graph = Graph() new_graph.add_node(5) new_graph.add_node(20) new_graph.add_node(17) return new_graph
[ "def create_graph2():\n a,b,c,d,e = create_nodes(5)\n\n a.add_edges(b)\n b.add_edges(a,c,d,e)\n c.add_edges(b)\n d.add_edges(b,e)\n e.add_edges(b,d)\n\n return Graph([a,b,c,d,e])", "def create_graph1(nodes=None):\n # if isinstance(nodes, list):\n # return Graph(nodes)\n \n a,b,c,d,e,f = create_nodes(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create graph with node that has edge.
def graph_w_edge(): from graph import Graph new_graph = Graph() new_graph.add_node(84) new_graph.add_node(2) new_graph.add_edge(84, 2) return new_graph
[ "def graph_w_edges():\n from graph import Graph\n new_graph = Graph()\n new_graph.add_edge(1, 3)\n new_graph.add_edge(3, 4)\n new_graph.add_edge(3, 5)\n new_graph.add_edge(5, 1)\n return new_graph", "def from_edges(cls, edges):\n graph = cls()\n for u, v in edges:\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a graph with 5 nodes and edges.
def graph_5_w_edges(): from graph import Graph new_graph = Graph() new_graph.add_node(77) new_graph.add_node(8) new_graph.add_node(16) new_graph.add_edge(3, 59) new_graph.add_edge(59, 77) new_graph.add_edge(3, 8) new_graph.add_edge(8, 16) return new_graph
[ "def create_graph2():\n a,b,c,d,e = create_nodes(5)\n\n a.add_edges(b)\n b.add_edges(a,c,d,e)\n c.add_edges(b)\n d.add_edges(b,e)\n e.add_edges(b,d)\n\n return Graph([a,b,c,d,e])", "def create_graph1(nodes=None):\n # if isinstance(nodes, list):\n # return Graph(nodes)\n \n a,b,c,d,e,f = create_nodes(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create graph with node that has multiple edges.
def graph_w_edges(): from graph import Graph new_graph = Graph() new_graph.add_edge(1, 3) new_graph.add_edge(3, 4) new_graph.add_edge(3, 5) new_graph.add_edge(5, 1) return new_graph
[ "def create_graph2():\n a,b,c,d,e = create_nodes(5)\n\n a.add_edges(b)\n b.add_edges(a,c,d,e)\n c.add_edges(b)\n d.add_edges(b,e)\n e.add_edges(b,d)\n\n return Graph([a,b,c,d,e])", "def from_edges(cls, edges):\n graph = cls()\n for u, v in edges:\n if u not in graph.node:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an empty bst.
def bst_empty(): from bst import BST new_bst = BST() return new_bst
[ "def empty_bst():\n from bst import BST\n empty_bst = BST()\n return empty_bst", "def test_bst_initialized(bst_empty):\n assert bst_empty.root is None", "def full_bst():\n bst = BinarySearchTree(8)\n bst.insert(3)\n bst.insert(10)\n bst.insert(1)\n bst.insert(6)\n bst.insert(4)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create bst with three nodes.
def bst_three(): from bst import BST new_bst = BST((10, 5, 15)) return new_bst
[ "def assemble_tree(node_list: list) -> object:\n tree = BinarySearchTree()\n tree.root = BinarySearchTreeNode(node_list[0])\n index = 1\n while index <= len(node_list)-1:\n tree.insert_node(BinarySearchTreeNode(node_list[index]), tree.root)\n index += 1\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a large bst for testing.
def bst_big(): from bst import BST new_bst = BST((10, 5, 15, 2, 12, 8, 20, 22, 1, 7, 19, 3, 9, 11, 13)) return new_bst
[ "def test_breadth_first_gen_big(bst_big):\n gen = bst_big.breadth_first()\n output = []\n for i in range(15):\n output.append(next(gen))\n assert output == [10, 5, 15, 2, 8, 12, 20, 1, 3, 7, 9, 11, 13, 19, 22]", "def test_create_index_page_splits_in_order_large_final_item():\n proc = _start_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a bst that extends left.
def bst_long_branch_left(): from bst import BST new_bst = BST((10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) return new_bst
[ "def _generate_left_tree(self):\n left_tree = BinaryTree()\n left_tree.deserialize([0,1,None,2,None,3])\n\n return left_tree", "def binarize_left(self):\n nodes = list(self.bottomup())\n for node in nodes:\n if len(node.children) > 2:\n vlabel = node.la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints accuracy statistics for class predictions made, given actual (y) classes
def print_accuracy(y, predictions): assert(len(y)==len(predictions)) correct = 0 for i in range(len(y)): if y[i] == predictions[i]: correct += 1 print("correct: {}/{}".format(correct, len(y))) print("accuracy: {:.2%}".format(correct/len(y)))
[ "def print_classifier_accuracies(self):\n sorted_accuracies = [c.accuracy for c in self.clf]\n sorted_accuracies.sort()\n print sorted_accuracies", "def _eval_classification_accuracy(self):\n batch_size = len(self._targets)\n\n pred = torch.cat(self._predictions, dim=1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compare two people eigen
def compare(p1, p2): distance = p1.eigen - p2.eigen return np.dot(distance, distance)
[ "def comparisonEigenvalues(iterations):\n A = np.random.rand(100,100)\n B = A.T.dot(A)\n B = (B+B.T)/2.0\n\n #QR algorithm\n eigenvaluesQR = np.diagonal(QRAlgorithm(B, iterations))\n eigenvaluesQR = np.sort(eigenvaluesQR)\n eigenvaluesQR = eigenvaluesQR[::-1] #Reverse the array to get larger va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
perform znormalization over vector
def z_normalize(vector): mean = np.mean(vector) std = np.std(vector) if std != 0: vector = (vector - mean) / std else: vector = vector - vector return vector
[ "def z_normalize(A: np.ndarray) -> np.ndarray:\n mean = np.expand_dims(A.mean(axis=A.ndim - 1), -1)\n std = np.expand_dims(A.std(axis=A.ndim - 1), -1)\n std[std == 0] = 1 # set std to 1 when it is 0 to avoid division by 0\n return (A - mean) / std", "def normalise(vect):\n return vect / np.sum(vec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the names from another file info object to the col_index specified of the infile1only and infile2only attributes. The id_col in fi_object must match the column specified. Also edit the header using the header from the fi_object.
def label_edits(self, col_index, fi_object): file1_ids = bf.sorted_ids(self.infile1only, col_index) file2_ids = bf.sorted_ids(self.infile2only, col_index) file1_lookupdict = pf.list_search_zipped_file(file1_ids, fi_object.file1, fi_object.id_col, fi_object.name_col, fi_object.datatypes, header =...
[ "def renameByCoordinates(self, filename_path, line, col, newname):", "def headerWriter(originalFileNames, newFileNames):\n newFileNameTuple = (newFileNames.getDroneFileName(), newFileNames.getParcelFileName())\n originalFile = originalFileNames.getDroneFileName()\n\n for fileName in newFileNameTuple:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints several edf frames in pdf files. The frames can be organised by individual in a single folder or they can come as a list that contains the full path plus edf names.
def multiple_pages(param_path=None, param_list=None, par_nrows=5, par_ncols=4, par_dist=300, par_dpi=300, title_override=False): # param_path and param_list can't be both None and can't # be both different to None if param_path is not None and param_list is not None: raise ValueEr...
[ "def create_df(self):\n alldf= pd.DataFrame()\n pdffiles= glob.glob(self.input_lib+'/**/*.pdf', recursive=True)\n for pdf_file in pdffiles:\n pdf_page_count= self.count_pages(pdf_file)\n for pg in range(1,pdf_page_count+1):\n pg = str(pg)\n cm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Commands to list data_product(s) and code_run(s)
def list(ctx, debug, remote) -> None: if ctx.obj is None: ctx.obj = {} ctx.obj['DEBUG'] = debug ctx.obj['REMOTE'] = remote _current_args = " ".join(sys.argv) if not ("data-products" in _current_args or "code-runs" in _current_args): ctx.invoke(data_products) ctx.invoke(code_r...
[ "def get_programs() :\n\n [prog_names, descriptions, cmd_line_prefixes] = db.get_programs()\n\n return [prog_names, descriptions, cmd_line_prefixes]", "def _get_input_files_for_code_run(code_run):\n all_code_run_inputs = []\n for component in code_run.inputs.all():\n all_code_run_inputs.extend(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a new FAIR repository user YAML config file
def create(debug, output: str) -> None: output = ( output[0] if output else os.path.join(os.getcwd(), fdp_com.USER_CONFIG_FILE) ) click.echo(f"Generating new user configuration file '{output}'") with fdp_session.FAIR(os.getcwd(), debug=debug) as fair_session: fair_session...
[ "def create_user_config(config_file):\n src = pkg_resources.resource_stream(__name__, 'pbs_gestor_config.json')\n try:\n with open(config_file, 'wb+') as dest:\n dest.writelines(src)\n except IOError:\n os.makedirs(os.path.dirname(config_file))\n with open(config_file, 'wb+'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uninstall the local registry from the system
def uninstall(debug: bool): _confirm = click.confirm( "Are you sure you want to remove the local registry and its components?", default=False, ) if not _confirm: return try: if debug: logging.getLogger("FAIRDataPipeline").setLevel(logging.DEBUG) fdp_sv...
[ "def localuninstall():\n files = os.listdir(\"bin\")\n for path in files:\n os.system(\"rm ~/.local/bin/\" + path)", "def uninstall():\n files = os.listdir(\"bin\")\n for path in files:\n os.system(\"rm /usr/bin/\" + path)", "def uninstall(self):\n sh.systemctl.disable(self.name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the local registry on the system
def install(debug: bool, force: bool, directory: str, version: str): try: if debug: logging.getLogger("FAIRDataPipeline").setLevel(logging.DEBUG) _version = fdp_svr.install_registry( install_dir=directory, reference=version, force=force ) click.echo(f"Installe...
[ "def localinstall():\n #does not require root\n #get working directory\n localpath = os.popen(\"pwd\").read()[0:-1]\n #get home directory\n homepath = os.popen(\"echo $HOME\").read()[0:-1]\n if not os.path.exists(homepath + \"/.local\"):\n os.mkdir(homepath + \"/.local/\")\n if not os.pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View log for a given job
def view(job_id: str, debug: bool) -> None: try: fdp_hist.show_job_log(os.getcwd(), job_id) except fdp_exc.FAIRCLIException as e: e.err_print() if e.level.lower() == "error": sys.exit(e.exit_code)
[ "def job_log(self, job_id):\n ENDPOINT = \"/job/\" + job_id + \"/log\"\n return self._call_api(ENDPOINT)", "def info(job_id):\n print(json.dumps(API().info(job_id), indent=True))", "def show_job_info(job_id='',show_output=False):\n from balsam.launcher.dag import BalsamJob as Job\n import...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the state_monitor variable "vm" vs. time.
def plot_data(state_monitor, title=None): fig, ax = plt.subplots(1, figsize=(10, 3)) ax.plot(state_monitor.t / b2.ms, state_monitor.vm[0] / b2.mV, lw=2, c='k') ax.set_xlabel("t [ms]") ax.set_ylabel("v [mV]") plt.grid() plt.axis(( 0, np.max(state_monitor.t / b2.ms), -1...
[ "def sysVmVAR(mirror, blkFlag=True):\n import matplotlib.pyplot as plt\n\n mir = mirror\n xend = max(mir.r_t)\n\n fig, ax = plt.subplots(nrows=2, ncols=1,)\n ax[0].set_title('System Bus Voltage Magnitude')\n ax[0].grid(True)\n ax[1].set_title('System Bus Voltage Angle')\n ax[1].grid(True)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A HodgkinHuxley neuron implemented in Brian2.
def simulate_HH_neuron(I_e, simulation_time): # neuron parameters El = -59. * b2.mV EK = -82. * b2.mV ENa = 45. * b2.mV gl = 0.3 * b2.msiemens gK = 36. * b2.msiemens gNa = 120. * b2.msiemens C = 1. * b2.ufarad # forming HH model with differential equations eqs = """ membran...
[ "def hodgkin_huxley(tt, I, u_off=-65.):\n \n # Sodium: m³ is probability, h gating variable\n α_m = lambda u: (2.5 - 0.1*(u - u_off)) / (np.exp(2.5 - 0.1*(u - u_off)) - 1)\n β_m = lambda u : 4*np.exp(-(u - u_off)/18)\n α_h = lambda u: 0.07 * np.exp(-(u - u_off)/20)\n β_h = lambda u : 1/(np.exp(3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
counts number of syllables in a given wav file using autobi
def count_syllables_wav(in_fname): # run autobi comp_proc = subprocess.run( ['java', '-cp', '../vendor/AuToBI.jar', 'edu.cuny.qc.speech.AuToBI.core.syllabifier.VillingSyllabifier', in_fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, check=True) ...
[ "def sylablelen(a):\r\n lab=songseg(a)\r\n freq=a[1]\r\n sylno=lab[1]\r\n inc=1\r\n out=[]\r\n lst=list(lab[0])\r\n while inc<=sylno:\r\n len=lst.count(inc)\r\n out.append(len)\r\n inc=inc+1\r\n out=out/freq\r\n return out", "def syllable_count(word: str):\n if l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
counts number of syllables in a given string sends the string to marytts for a phoneme computation and determines the number of syllables based on the number of vowels in the response (works only for 'en_US')
def count_syllables_text(in_str, ip_addr=None, port=None): ip_addr = ip_addr if ip_addr else '127.0.0.1' port = port if port else 59125 # send text to mary for phoneme computation params = { 'INPUT_TEXT': in_str, 'INPUT_TYPE': 'TEXT', 'OUTPUT_TYPE': 'PHONEMES', 'LOCALE':...
[ "def syllable_count(word: str):\n if len(word.split()) > 1:\n return [syllable_count(w) for w in word.split()]\n word = G2pModel.get_cmu([G2pModel.preprocess(word)])\n return cmu_syllable_count(word[0][0])", "def num_syllables(word):\n return len(list(y for y in cmu_lookup(word) if y[-1].isdigi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates wav from plain text with given speech rate, intensity and pitch
def synthesize_with_features(in_str, speech_rate=None, intensity=None, pitch=None, in_str_is_fname=False, out_fname=None, tts_type=None, ip_addr=None, port=None, voice=None, speech_rates_dict=None, repeat_until_close=False, ...
[ "def make_wav(text, speed=1.0, emotion='normal', output_file='__temp.wav', output_dir=os.getcwd(), voice_name='mei',\n openjtalk_binpath='/usr/bin',\n openjtalk_dicpath='/var/lib/mecab/dic/open-jtalk/naist-jdic',\n openjtalk_voicepath='/usr/share/hts-voice/{voice_name}/{voice_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
runs praat script to adapt given wav's speech rate, intensity, pitch script allows flexibility in terms of which features are adapted, if parameter is none, that feature will not be actively adapted (a change in another feature can still cause a change in an "unadapted" feature, though)
def adapt_wav(in_fname, out_fname, syll_count=None, speech_rate=None, intensity=None, pitch=None): syll_count = syll_count if syll_count else 0 # in the script, "<= 0" means "do not adapt" speech_rate = speech_rate if speech_rate else 0 intensity = intensity if intensity else 0 pitch =...
[ "def test():\n # imports specific to this test\n import sys\n import warnings\n from scipy.io import wavfile\n import matplotlib.pyplot as plt\n from psola.experiment_config import ExperimentConfig\n\n # get the data and do the estimation\n filename = sys.argv[1] # filename is first comma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates transcription of a given wav file
def transcribe_wav(in_fname): tmp_fname1 = get_unique_fname('../tmp/extended', '.wav') tmp_fname2 = get_unique_fname('../tmp/transcribe', '.log') # prepend some silence (first bit of speech might else be treated as noise) subprocess.check_call(['praat', '--run', '../misc/prepend_silence.praat', ...
[ "def create_wav_and_transcripts(path, data_tag, sample_rate, extracted_dir, wav_subfolder_name):\n tag_path = os.path.join(path,data_tag)\n transcript_path_new = os.path.join(tag_path, 'txt')\n wav_path_new = os.path.join(tag_path, 'wav')\n\n path_utils.try_create_directory(transcript_path_new)\n pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns ssml markup for given string with target prosody values for rate, pitch and volume are not checked here, incorrect inputs will cause an error; see ssml specification for legal values must have same interface as get_sable (assumed in synthesize_with_features)!
def get_ssml(in_str, rate='default', pitch='default', volume='default'): return ('<?xml version="1.0"?>' '<speak version="1.0"' ' xmlns="http://www.w3.org/2001/10/synthesis"' ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' ' xsi:schemaLocation="http://www.w3....
[ "def get_sable(in_str, rate='default', pitch='default', volume='default'):\n return ( # no xml version declaration since it causes a warning in festival\n '<SABLE>'\n # voice is only set to placeholder, filled in synthesize\n ' <SPEAKER NAME=\"<<<voice>>>\">'\n ' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns sable markup for given string with target prosody values for rate, pitch and volume are not checked here, incorrect inputs will cause an error; see sable specification for legal values must have same interface as get_ssml (assumed in synthesize_with_features)!
def get_sable(in_str, rate='default', pitch='default', volume='default'): return ( # no xml version declaration since it causes a warning in festival '<SABLE>' # voice is only set to placeholder, filled in synthesize ' <SPEAKER NAME="<<<voice>>>">' ' <RATE ...
[ "def get_ssml(in_str, rate='default', pitch='default', volume='default'):\n return ('<?xml version=\"1.0\"?>'\n '<speak version=\"1.0\"'\n ' xmlns=\"http://www.w3.org/2001/10/synthesis\"'\n ' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"'\n ' xsi:schemaLocati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads a small corpus of sentences annotated with syllable counts
def load_syllable_count_corpus(): corpus = [] with open('../misc/syllable_count_corpus.txt', 'r') as corpus_file: for line in corpus_file.readlines(): index = line.find(' ') corpus.append([int(line[:index]), line[index+1:].replace('\n', '')]) return corpus
[ "def load_corpus(self, dir):\n word_fn = codecs.open(dir + \"word.dic\", \"r\", \"utf-8\")\n for line in word_fn:\n word_nr, word = line.strip().split(\"\\t\")\n self.int_to_word.append(word)\n self.word_dict[word] = int(word_nr)\n word_fn.close()\n tag_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads a json file which matches target speech rates to modifiers
def load_speech_rates_dict(): return json.load(open('../misc/speech_rates_inverse.json'))
[ "def load_levin(self, path):\n try:\n lexicon_file = open(path)\n self.levin_dict = json.loads(lexicon_file.read())\n except:\n print 'fail to laod levin verb classes'", "def load(self, file_name):\n model_data = codecs.open(file_name, 'r', encoding='utf-8').r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determines tts average speech rate for given rate modifier
def detect_tts_speech_rate(tts_type, voice, rate_modifier, ip_addr=None, port=None): syll_rates = [] corpus = load_syllable_count_corpus() # synthesize every line in the corpus, measuring the speech rate for each for line in corpus: if tts_type == TTS_TYPE_MARY: ...
[ "def mean_rate(self, t_start=None, t_stop=None):\n if t_start is None: \n t_start = self._t_start\n if t_stop is None: \n t_stop=self._t_stop\n idx = numpy.where((self._spike_times >= t_start) & (self._spike_times <= t_stop))[0]\n return len(idx)/(t_stop-t_start)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a connection to the postgres database and Drop and recreate empty databases
def create_learning_databases(): pg_client = DBClient() pg_client.setup_connection('postgres') cursor = pg_client.conn.cursor() cursor.execute('drop database if exists prd') cursor.execute('create database prd') cursor.execute('drop database if exists dev') curso...
[ "def postgres():\n utils.create_db()\n try:\n yield utils.get_postgres_dsn()\n finally:\n utils.drop_db()", "def create_database():\n # Connect to default database with presetup user\n conn = psycopg2.connect(\n f\"host=127.0.0.1 dbname=postgres user={config.db_username} passwo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a table in dev
def create_basic_table_in_dev(self): dev_table_sql = "create table {} ( col1 text, col2 int, col3 timestamp )".format(self.table_name) self.dev_db_conn.exec_ddl(dev_table_sql, None)
[ "def _table_creation_command(cls):\n return sql.Card.create_table()", "def _table_creation_command(cls) -> str:\n return sql.Metacard.create_table()", "def _create_table(self, table_name):\n raise NotImplementedError()", "def CreateTable(self, param):\n pass", "def Create_table(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a position into letter coordinates, for SGF
def pos_to_coord(pos): x, y = pos return "%s%s" % (string.letters[x], string.letters[y])
[ "def translate_to_alg_coords(self, list_pos):\n\n # list_pos would be something like [1, 3]\n # first element = row, second element = column\n row = list_pos[0]\n col = list_pos[1]\n\n # Add one for row since list coordinates start at zero but alg.\n # notation starts at 1\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and initialize the clock activity.
def __init__(self, handle): super(ClockActivity, self).__init__(handle) # TRANS: Title of the activity self.set_title(_('What Time Is It?')) # TRANS: The format used when writing the time in full # letters. You must take care to use a font size large enough # so that k...
[ "def __init__(self):\n DebugObject.__init__(self, \"TimeOfDay\")\n self._createProperties()", "def __init__(self):\n super(ClockFace, self).__init__()\n\n # Set to True when the variables to draw the clock are set:\n self.initialized = False\n\n # The time on the clock fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The user selected a clock display mode (simple clock, nice or digital).
def _display_mode_changed_cb(self, radiobutton, display_mode): self._clock.set_display_mode(display_mode)
[ "def on_clock_select_change(self):\n\n selected_time = self.clock_widget.selected_time\n\n # If we are in urge mode, and the user has not selected a urge time, do not allow next trial\n # until they have done so.\n if self.urge_mode:\n if selected_time is not None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The user clicked on the "write time" button to print the current time.
def _write_time_clicked_cb(self, button): self._write_time = button.get_active() if self._write_time: self._time_letters.show() self._write_and_speak(False) else: self._time_letters.hide()
[ "def time(self):\n now = datetime.datetime.now()\n self.speak(f\"Agora são {now.hour} horas e {now.minute} minutos\")", "def user_time(self, console):\n self.writeCommand('user_time', console)\n return self", "async def evetime(self):\r\n \r\n #Your code will go here\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The user clicked on the "speak time" button to hear the talking clock.
def _speak_time_clicked_cb(self, button): self._speak_time = button.get_active() if self._speak_time: self._write_and_speak(True)
[ "def time(self):\n now = datetime.datetime.now()\n self.speak(f\"Agora são {now.hour} horas e {now.minute} minutos\")", "def greet():\r\n hour = int(datetime.datetime.now().hour)\r\n if 12 > hour >= 0:\r\n speak('Good Morning, I am your voice assistant')\r\n elif 12 <= hour < 17:\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sugar notify us that the activity is becoming active or inactive. When we are inactive, we change the activity status of the clock face widget, so that it can stop updating every seconds.
def _notify_active_cb(self, widget, event): self._clock.active = self.props.active if self.props.active: self._inhibit_suspend() else: self._allow_suspend()
[ "def update(self):\n if self.active_flag:\n self.consider_deactivation()\n else:\n self.consider_activation()\n\n if self.active_flag:\n self.sense_and_act()", "def _set_active(self, active):\n self._active = active\n\n if active:\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write and speak the time (called in another thread not to block the clock).
def _write_and_speak(self, speak): # A helper function for the running thread def thread_write_and_speak(): # Only update the time in full letters when necessary if self._write_time or self._speak_time: self._do_write_time() # And if requested, say it...
[ "def time(self):\n now = datetime.datetime.now()\n self.speak(f\"Agora são {now.hour} horas e {now.minute} minutos\")", "def time_handler():\n global time\n time += 1\n format()", "def _do_speak_time(self):\n\n def gstmessage_cb(bus, message, pipe):\n if message.type in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Speak aloud the current time.
def _do_speak_time(self): def gstmessage_cb(bus, message, pipe): if message.type in (gst.MESSAGE_EOS, gst.MESSAGE_ERROR): pipe.set_state(gst.STATE_NULL) if self._time_speaker is None: self._time_speaker = Speaker() pipeline = 'espeak text="%(text)s" voi...
[ "def time(self):\n now = datetime.datetime.now()\n self.speak(f\"Agora são {now.hour} horas e {now.minute} minutos\")", "async def evetime(self):\r\n \r\n #Your code will go here\r\n await self.bot.say(strftime(\"EVE time is currently **%H:%M:%S** on **%d/%m/%Y**\", gmtime()))",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the clock widget. The mode defaults to the basic analog clock, with no hours mark or date.
def __init__(self): super(ClockFace, self).__init__() # Set to True when the variables to draw the clock are set: self.initialized = False # The time on the clock face self._time = datetime.now() self._old_minute = self._time.minute # Update the clock only when...
[ "def start_clock(self):\n st = self.get_state()\n self.set_trigger(st | 0x2)", "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def build_clock():\n return html.Div([\n daq.LEDDisplay(id='clock', value='00...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the type of clock to display (simple, nice, digital). 'mode' is one of MODE_XXX_CLOCK constants.
def set_display_mode(self, mode): self._mode = mode
[ "def _display_mode_changed_cb(self, radiobutton, display_mode):\n self._clock.set_display_mode(display_mode)", "def set_mode(self, mode):\n self._mode = mode", "def mode(self, mode):\n # type: (SrtMode) -> None\n\n if mode is not None:\n if not isinstance(mode, SrtMode):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the markup text given as parameter, centered on (x, y) coordinates. The markup must follow Pango markup syntax See
def _draw_markup(self, x, y, markup): pango_context = self.get_pango_context() layout = pango.Layout(pango_context) layout.set_markup(markup) layout.set_alignment(pango.ALIGN_CENTER) x_bearing, y_bearing, width, height = layout.get_pixel_extents()[1][:4] x_delta = int(x...
[ "def pango_markup(text: str, tag: str = \"span\", **attrib) -> str:\n e = Tree.Element(tag, attrib=attrib)\n e.text = text\n return Tree.tostring(e, encoding=\"unicode\")", "def plot_centered_text(f, ax, cell_x0, cell_y0, cell_x1, cell_y1,\n text, fontsize, fontweight='normal', c_ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the digital clock.
def _draw_digital_clock(self): self._draw_time_scale() self._draw_time()
[ "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def draw_clock(self):\n\n now = self.current_time()\n hour = now.hour\n minute = now.minute\n second = now.second\n\n x0 = 32*3+19\n y0 = 12...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a time scale for digital clock.
def _draw_time_scale(self): # Draw scales of hours, minutes and seconds, to give the children # an appreciation of the time flowing... hours_length = 2 * self._radius / 24 * self._time.hour minutes_length = 2 * self._radius / 60 * self._time.minute seconds_length = 2 * self._radi...
[ "def _draw_digital_clock(self):\n self._draw_time_scale()\n self._draw_time()", "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def _draw_nice_clock(self):\n self._draw_nice_background()\n self._draw_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the simple clock variants.
def _draw_simple_clock(self): self._draw_simple_background() self._draw_numbers() self._draw_hands()
[ "def _draw_nice_clock(self):\n self._draw_nice_background()\n self._draw_hands()", "def _draw_digital_clock(self):\n self._draw_time_scale()\n self._draw_time()", "def draw_clock(self):\n\n now = self.current_time()\n hour = now.hour\n minute = now.minute\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the background of the simple clock. The simple clock background is a white disk, with hours and minutes ticks, and the hour numbers.
def _draw_simple_background(self): # Simple clock background self._gc.set_foreground(self._COLOR_WHITE) x_delta = self._center_x - self._radius y_delta = self._center_y - self._radius self.window.draw_arc(self._gc, True, x_delta, y_delta, 2 * self._radius, 2 * self._ra...
[ "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def _draw_nice_clock(self):\n self._draw_nice_background()\n self._draw_hands()", "def draw_clock(self):\n\n now = self.current_time()\n hour = now.hour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the nice clock.
def _draw_nice_clock(self): self._draw_nice_background() self._draw_hands()
[ "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def draw_clock(self):\n\n now = self.current_time()\n hour = now.hour\n minute = now.minute\n second = now.second\n\n x0 = 32*3+19\n y0 = 12...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the hands of the analog clocks.
def _draw_hands(self): hours = self._time.hour minutes = self._time.minute seconds = self._time.second # Hour hand: # The hour hand is rotated 30 degrees (pi/6 r) per hour + # 1/2 a degree (pi/360) per minute self._gc.set_foreground(self._COLOR_HOURS) sel...
[ "def _draw_simple_clock(self):\n self._draw_simple_background()\n self._draw_numbers()\n self._draw_hands()", "def _draw_nice_clock(self):\n self._draw_nice_background()\n self._draw_hands()", "def analog_clock(self, width = 16, height = 16, **kwargs):\n \n def r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the numbers of the hours.
def _draw_numbers(self): self._gc.set_foreground(self._COLOR_HOURS) for i in xrange(12): # TRANS: The format of the font used to print hour # numbers, from 1 to 12. hour_number = _('<markup><span lang="en" \ font_desc="Sans Bold 20">%d</span></markup>') % (i + 1) ...
[ "def draw_half_hour(self):\n\n now = self.current_time()\n now_modified = datetime(2020, 1, 1, now.hour, now.minute, now.second)\n\n min30 = datetime(2020, 1, 1, now_modified.hour, 29, 59)\n min00 = datetime(2020, 1, 1, now_modified.hour, 59, 59)\n\n left30 = min30 - now_modified\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the activity state of the clock face. When Sugar reactivates the clock, we start a timer to be called every seconds and update the clock.
def _set_active(self, active): self._active = active if active: # We must redraw the clock... self._update_cb() # And update again the clock every seconds. gobject.timeout_add(1000, self._update_cb)
[ "def start_clock(self):\n st = self.get_state()\n self.set_trigger(st | 0x2)", "async def set_device_clock(call: ServiceCall) -> None:\n gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]]\n attr_date = call.data[ATTR_DATE]\n attr_time = call.data[ATTR_TI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract frames from a video.
def extract_video_frames(self, video_filename, video_name, save_dir): assert video_filename assert video_name assert save_dir # setup stdout suppression for subprocess try: from subprocess import DEVNULL # py3k except ImportError: DEVNULL = open(...
[ "def extract_frames(video_path):\r\n ########################################################################################################\r\n # You can change the lines below to implement your own frame extracting method (and possibly other preprocessing),\r\n # or just use the provided codes.\r\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the video filename.
def get_video_filename(self, all_files): assert all_files video_filename = [vname for vname in all_files if vname.endswith('.avi')] if not any(video_filename): video_filename = 'not_available' else: video_filename = video_filename[0] return video_filenam...
[ "def video_file_name(\n\t\tself,\n\t\tshow_url,\n\t\tseason_title,\n\t\tepisode_title):\n\t\treturn hashlib.sha1(bytes(show_url+season_title+episode_title,encoding='utf8')).hexdigest()", "def update_filename(instance, filename):\n extension = get_extension(filename)\n path = VIDEO_UPLOAD_PATH\n format = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load activities, videos and filenames paths from the data directory.
def get_files_paths(self): self.activities_dir = os.path.join('ucf_sports_actions', 'ucf action') self.root_dir_imgs = os.path.join(self.data_path, self.activities_dir) if self.verbose: print(' > Fetch videos and images paths from dir: {}' .format(self.root_dir_img...
[ "def load_directories(self):\n self.SRC_DIR = Path(__file__).parent / \"src\"\n self.ASSETS_DIR = self.SRC_DIR / \"assets\"\n self.IMAGES = self.ASSETS_DIR / \"images\" \n self.MAPS = self.ASSETS_DIR / \"maps\"\n self.SFX = self.ASSETS_DIR / \"sfx\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the metadata of a set.
def process_set_metadata(self, data, set_name): hdf5_handler = self.hdf5_manager.get_group(set_name) data_array = self.convert_data_to_arrays(data) hdf5_write_data(hdf5_handler, 'activities', data_array["activities"], dtype=np.uint8, fillvalue=0) ...
[ "def save_photoset(self, photoset):\n\n ps = photoset[\"photoset\"]\n\n defaults = {\n \"fetch_time\": photoset[\"fetch_time\"],\n \"user\": photoset[\"user_obj\"],\n \"flickr_id\": ps[\"id\"],\n \"title\": ps[\"title\"][\"_content\"],\n \"descrip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Senses an image with k measurements
def sense(img, k=1000, basis="wvt", wvt_level=4, alpha=None): print "Image size:", img.shape img_f = img.flatten() print "Build sensing matrix" A = np.random.normal(0, 1, len(img_f)*k).astype(np.float32).\ reshape(k, img.shape[0], img.shape[1]) print "Measurement" b = np.dot(A.reshape(...
[ "def zoom(image):", "def smooth(self,size=10):\n from scipy.ndimage import median_filter\n self.n = median_filter(self.n,size)\n self.k = median_filter(self.k,size)", "def rescaled_image():", "def find_seams(image, k, axis=1, efunc=energy_function, cfunc=compute_cost):\n\n image = np.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a new TetgenObject composed of selected_elems
def rebuild(self, selected_elems, elem_attr=None): new_points_map = dict() new_points_index = 0 for elem in selected_elems: for n in elem: if not n in new_points_map: new_points_map[n] = new_points_index new_points_index += 1 ...
[ "def prepareSelectionDocument(items, topic, roles):\n selection = ET.Element('selection')\n if None != items and 0 != len(items):\n selection.append(prepareItems(items))\n if None != topic:\n topicElement = ET.Element('topic')\n topicElement.text = topic\n selection.append(topic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through all prerequisite pipelines
def prerequisites(self): # Loop through the inputs to the pipeline and add the instancemethods # for the pipelines to generate each of the processed inputs pipelines = {} for input in self.inputs: # @ReservedAssignment try: spec = self._study.spec(input) ...
[ "def _assemble_pipelines(self):\n\n self.pipelines = []\n for clf in self.config[\"classifiers\"].keys():\n self.pipelines.append(self._assemble_pipeline(classifiers[clf](), clf))", "def iter_dependencies(self, item):\n if 'ACTIVE_PAPER_DEPENDENCIES' in item.attrs:\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects a study fileset_spec as an input to the provided node
def connect_input(self, spec_name, node, node_input, format=None, **kwargs): # @ReservedAssignment @IgnorePep8 if spec_name in self.study.ITERFIELDS: self._iterator_conns[spec_name].append((node, node_input, format)) else: name = self._map_name(spec_name, self._input_map) ...
[ "def inputnode(self, frequency):\n # Check to see whether there are any outputs for the given frequency\n inputs = list(self.frequency_inputs(frequency))\n # Get list of input names for the requested frequency, addding fields\n # to hold iterator IDs\n input_names = [i.name for i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a spec name to a new value based on the provided mapper
def _map_name(self, name, mapper): if mapper is not None: if isinstance(mapper, basestring): name = mapper + name try: name = mapper[name] except KeyError: pass return name
[ "def mapping_spec(spec):\n assert config.is_mapping_spec(spec), \"A .rmap, .imap, or .pmap file or date base specification is required but got: '%s'\" % spec\n return spec", "def _mapping_updater(new):\n\n def f(kv):\n n, v = kv\n if n in new:\n return (n, parse_quantity(new[n])....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs the connection in the wrapped NiPype workflow
def connect(self, *args, **kwargs): self._workflow.connect(*args, **kwargs)
[ "def delegate():\n # TODO: assistant\n block()\n\n communion_server.configure_master(\n transformation_job=True,\n transformation_status=True,\n )\n\n database.connect()\n communion_server.start()", "def __connect(self):\n self.session = xnatpy.connect(\n self.ser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all parameters, including parameters of prerequisites
def all_parameters(self): return chain(self.parameters, iter(self._prereq_parameters.items()))
[ "def parameters(self):\r\n param_list = []\r\n for arg in self.args:\r\n param_list += arg.parameters()\r\n # Remove duplicates.\r\n return list(set(param_list))", "def required_params(self) -> list:", "def parameters(self):\n return [n.parameters() for n in self.no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline.
def inputnode(self, frequency): # Check to see whether there are any outputs for the given frequency inputs = list(self.frequency_inputs(frequency)) # Get list of input names for the requested frequency, addding fields # to hold iterator IDs input_names = [i.name for i in inputs]...
[ "def outputnode(self, frequency):\n # Check to see whether there are any outputs for the given frequency\n outputs = list(self.frequency_outputs(frequency))\n if not outputs:\n raise ArcanaError(\n \"No outputs to '{}' pipeline for requested freqency '{}'\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates an output node for the given frequency. It also adds implicit file format conversion nodes to the pipeline.
def outputnode(self, frequency): # Check to see whether there are any outputs for the given frequency outputs = list(self.frequency_outputs(frequency)) if not outputs: raise ArcanaError( "No outputs to '{}' pipeline for requested freqency '{}'" .format...
[ "def inputnode(self, frequency):\n # Check to see whether there are any outputs for the given frequency\n inputs = list(self.frequency_inputs(frequency))\n # Get list of input names for the requested frequency, addding fields\n # to hold iterator IDs\n input_names = [i.name for i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the fileset matches the requested file format
def requires_conversion(cls, fileset, file_format): if file_format is None: return False try: filset_format = fileset.format except AttributeError: return False # Field input else: return (file_format != filset_format)
[ "def has_format(self, format):\n for f in self.formats:\n if f==format:\n return True\n return False", "def validate(self):\n if self._checkDatatype():\n subtools.validateFiles(self.inputFile, self.chromSizesFile, self.fileType, self.options)\n else...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if the given frequency requires iteration over the given iterfield
def iterates_over(self, iterfield, freq): return iterfield in self.study.FREQUENCIES[freq]
[ "def has_frequency(self, band):\n return band in self.sefd", "def checkValidFreq(freq, methodStr):\n\t# if False: raise ValueError(\"Invalid frequency passed to %s\" % methodStr)\n\tpass", "def every_n_iters(self, trainer, n):\n return (trainer.iter + 1) % n == 0 if n > 0 else False", "def ensur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unwraps potentially nested modification dictionaries to get values for name, input_map, output_map and study. Unsed in __init__.
def _unwrap_mods(self, mods, name, study=None, **inner_maps): # Unwrap nested name_maps if present if 'name' in mods: name = mods['name'] if 'prefix' in mods: name = mods['prefix'] + name if 'study' in mods: study = mods['study'] # Flatten inpu...
[ "def inputToInternal(self,input):\n inputDict = []\n for inp in input:\n if type(inp) == dict:\n return [inp]\n else:\n inputDictTemp = {'data':{}, 'metadata':{}}\n inputDictTemp['data']['input'] = copy.deepcopy(inp.getInpParametersValues())\n inputDictTemp['data']['outp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The list of sprites in the group, sorted by depth.
def sprites(self): return sorted(self.spritedict.keys(), key=lambda sprite: sprite.depth)
[ "def sprites(self):\r\n \r\n # Second parameter in sorted() allows for an anonymous function that dictates the attribute of each iterable to be sorted\r\n\r\n return sorted(self.spritedict.keys(), key=lambda sprite: sprite.depth)", "def sprites(self):\n return self._orderedsprites[:]",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the position and depth of the sprite on the map.
def _set_pos(self, pos): self.rect.midbottom = pos[0]*24+12, pos[1]*16+16 self.depth = self.rect.midbottom[1]
[ "def _set_pos(self, pos):\r\n \r\n self.rect.midbottom = pos[0]*MAP_TILE_WIDTH+(MAP_TILE_WIDTH/2), pos[1]*MAP_TILE_HEIGHT+(MAP_TILE_HEIGHT)\r\n self.depth = self.rect.midbottom[1]", "def setDepthMap(*args, **kwargs):\n \n pass", "def set_tile(self, pos, tile):\n x, y = pos\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is there a wall?
def is_wall(self, x, y): return self.get_bool(x, y, 'wall')
[ "def walls(self):", "def is_wall(self, x, y):\n return self.get_tile(x, y) == Tile.wall", "def isWall(mapObj, x, y):\n if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):\n return False # x and y aren't actually on the map.\n elif mapObj[x][y] in ('#', 'x'):\n return True ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if Account is sitting in the root of the Organization or in Protected OU
def is_account_in_invalid_state(ou_id, config): if ou_id.startswith('r-'): return "Is in the Root of the Organization, it will be skipped." protected = config.get('protected', []) if ou_id in protected: return "Is a in a protected Organizational Unit {0}, it will be skipped.".format(ou_id) ...
[ "def visible_organization(self):\n user_org = \\\n SchoolDB.models.getActiveDatabaseUser().get_active_organization_key()\n if (user_org == self.key()):\n return True\n else:\n sub_orgs = self.get_subordinate_organizations_list()\n return (sub_orgs.cou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update parameters on the deployment account across target regions based on the output of CloudFormation base stacks in the deployment account.
def update_deployment_account_output_parameters( deployment_account_region, region, kms_dict, deployment_account_role, cloudformation): deployment_account_parameter_store = ParameterStore( deployment_account_region, deployment_account_role ) parameter_store = ...
[ "def update_base_arch(self, param_set):\n for i in range(len(self.pc_arg_val)):\n self.base_arch.config_label[self.param_set_labels[i]] = param_set[i]\n self.pc_arg_val[i][0].comp_args[self.pc_arg_val[i][1]] = param_set[i]\n self.pc_arg_val[i][0].clear_cache()", "def update...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Worker thread function that is created for each account in which CloudFormation create_stack is called
def worker_thread( account_id, sts, config, s3, cache, kms_dict): LOGGER.debug("%s - Starting new worker thread", account_id) organizations = Organizations( role=boto3, account_id=account_id ) ou_id = organizations.get_parent_info().get("o...
[ "def _build(self, command, threading_events, stack_statuses, dependencies):\n num_stacks = len(self.stacks)\n with ThreadPoolExecutor(max_workers=num_stacks) as executor:\n futures = [\n executor.submit(\n self._manage_stack_build, stack,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the version of Observables instances under `root` to ``2.1``.
def _update_versions(self, root): nodes = self._get_versioned_nodes(root) for node in nodes: attribs = node.attrib attribs[common.TAG_CYBOX_MAJOR] = '2' attribs[common.TAG_CYBOX_MINOR] = '1' with utils.ignored(KeyError): del attribs[com...
[ "def _update_versions(self, root):\n nodes = self._get_versioned_nodes(root)\n for node in nodes:\n name = utils.get_localname(node)\n\n if name == \"Indicator\":\n node.attrib['version'] = '2.2'\n else:\n node.attrib['version'] = '1.2'", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates fields which have changed in structure or data type.
def _translate_fields(self, root): for field in self.TRANSLATABLE_FIELDS: field.translate(root)
[ "def _get_changed_fields(self):\n EmbeddedDocument = _import_class(\"EmbeddedDocument\")\n LazyReferenceField = _import_class(\"LazyReferenceField\")\n ReferenceField = _import_class(\"ReferenceField\")\n GenericLazyReferenceField = _import_class(\"GenericLazyReferenceField\")\n G...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds and removes empty xml elements and attributes which are optional in the next language release.
def _update_optionals(self, root): optional_elements = self.OPTIONAL_ELEMENTS optional_attribs = self.OPTIONAL_ATTRIBUTES typed_nodes = utils.get_typed_nodes(root) for optional in optional_elements: found = optional.find(root, typed=typed_nodes) utils.remove_xml...
[ "def strip_empty_tags(self):\n tag = self.root\n while True:\n next_tag = tag.findNext(True)\n if not next_tag: break\n if next_tag.contents or next_tag.attrs:\n tag = next_tag\n continue\n next_tag.extract()", "def strip_attr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the `disallowed` nodes from the source document.
def _clean_disallowed(self, disallowed, options): removed = [] for node in disallowed: dup = utils.copy_xml_element(node) utils.remove_xml_element(node) removed.append(dup) return removed
[ "def remove_noop_inline_elements(context, content):\n for node in content.findall('.//span'):\n if node.attrib:\n continue\n drop_node(node, add_padding=False, keep_content=True)", "def _remove_worksheet_protection(self):\n worksheet_xml_filepaths = self._get_file_listing(self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assigns a unique ID to each node in `duplicates`.
def _clean_duplicates(self, duplicates, options): new_id = options.new_id_func for _, nodes in iteritems(duplicates): for node in nodes: new_id(node) return duplicates
[ "def set_id(self):\n self._id = hash(\n (self.__class__, self.name)\n + tuple([child.id for child in self.children])\n + tuple([(k, tuple(v)) for k, v in self.domains.items() if v != []])\n )", "def make_unique(self):\r\n\r\n\t\tseen = {}\r\n\r\n\t\tfor motif in self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alice's quantum protocol for the CHSH game.
def alice_quantum(alice_host, referee_id, bob_id): for i in range(PLAYS): referee_message = alice_host.get_next_classical(referee_id, wait=5) x = int(referee_message.content) epr = alice_host.get_epr(bob_id) if x == 0: res = epr.measure() alice_host.send_clas...
[ "def bob_quantum(bob_host, referee_id, alice_id):\n\n for i in range(PLAYS):\n referee_message = bob_host.get_next_classical(referee_id, wait=5)\n\n y = int(referee_message.content)\n epr = bob_host.get_epr(alice_id)\n\n if y == 0:\n epr.ry(-2.0 * math.pi / 8.0)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bob's quantum protocol for the CHSH game.
def bob_quantum(bob_host, referee_id, alice_id): for i in range(PLAYS): referee_message = bob_host.get_next_classical(referee_id, wait=5) y = int(referee_message.content) epr = bob_host.get_epr(alice_id) if y == 0: epr.ry(-2.0 * math.pi / 8.0) res = epr.mea...
[ "def alice_quantum(alice_host, referee_id, bob_id):\n for i in range(PLAYS):\n referee_message = alice_host.get_next_classical(referee_id, wait=5)\n x = int(referee_message.content)\n epr = alice_host.get_epr(bob_id)\n\n if x == 0:\n res = epr.measure()\n alice_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an infinite sequence of random numbers. Yields int A random number.
def infinite_random_sequence(self): num_of_randoms = 0 randoms = [] while True: num_of_randoms += 1 randoms.append(self.rand()) yield randoms[num_of_randoms-1]
[ "def _integers_from(n):\n while True:\n yield n\n n += 1", "def seq_randint(a, b):\n while True:\n yield random.randint(a, b)", "def infinite_integer(i=0, step=1):\n while True:\n yield i\n i += step", "def integers():\n i = 1\n while True:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the next random number. Returns int A random number. Raises RuntimeError If the ``__next__`` method is called before ``__iter__``. StopIteration If ``self.length`` random numbers are generated.
def __next__(self): if self.num_generated_numbers is None: raise RuntimeError( f'{type(self)} is not initialised as an iterator.') if self.num_generated_numbers == self.length: raise StopIteration return self.generator.rand()
[ "def next( self ):\n\n try: \n value = self.__sequence[ self.__nextValue ]\n except IndexError:\n raise StopIteration\n else:\n self.__nextValue += 1\n return value", "def __next__(self):\n value = next(self._iterable)\n self._count += 1\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect to real facetcreation form.
def form_valid(self, form): template = form.data['template'] name = form.cleaned_data['name'] url = reverse("facet_add", kwargs={'template_id': template, 'story': self.kwargs['story']}) return redirect("{}?name={}".format(url, name))
[ "def page_create():\n return redirect(url_for('page_edit'))", "def form_valid(self):\n return HttpResponseRedirect(self.ticket.get_absolute_url())", "def after_valid_form_submission(self):", "def change_view(self, request, object_id, form_url='', extra_context=None):\n result = super(ThingAdmin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get discussion, comments and comment form for the facet.
def facet_discussion(self): self.object = self.get_object() discussion = self.object.discussion comments = discussion.comment_set.all().order_by('date') form = CommentForm() return {'discussion': discussion, 'comments': comments, 'form': form}
[ "def get_form():\n from django_comments.forms import CommentForm\n\n return CommentForm", "def get_comment_form(self):\n comment_form = self.browser.find_element_by_id('comment_form')\n return comment_form", "def facet(self):\n facet_values = self.get_feature('facet')\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }